diff --git a/Projects/Config/LogXnetConfig.json b/Projects/Config/LogXnetConfig.json new file mode 100644 index 0000000..4428544 --- /dev/null +++ b/Projects/Config/LogXnetConfig.json @@ -0,0 +1,79 @@ +{ + "ConsoleEnable": true, + "FileOutputEnable": true, + "TimeStampEnable": true, + "ThreadIdEnable": true, + "AutoRemoveEnable": true, + "OutputFilePath": "/log", + "TimeStampForamt": "yyyy-MM-dd HH:mm:ss.fff", + "AutoRemoveIntervalDay": 10, + "LogLevel": "Debug", + "LogDefines": [ + { + "LogLevel": "DEFAULT", + "LogLabel": "default", + "ForeColorRGB": "#fbebd2" + }, + + { + "LogLevel": "Debug", + "LogLabel": "Debug", + "ForeColorRGB": "#148CFF" + }, + { + "LogLevel": "Debug", + "LogLabel": "Db", + "ForeColorRGB": "#46BEFF" + }, + { + "LogLevel": "Debug", + "LogLabel": "HTTP", + "ForeColorRGB": "#6E6EFF" + }, + { + "LogLevel": "Debug", + "LogLabel": "CONTROLLER", + "ForeColorRGB": "#B4B4FF" + }, + { + "LogLevel": "Debug", + "LogLabel": "SOCKET", + "ForeColorRGB": "#5A78AF" + }, + { + "LogLevel": "Information", + "LogLabel": "Information", + "ForeColorRGB": "22;198;12" + }, + { + "LogLevel": "Information", + "LogLabel": "INFO", + "ForeColorRGB": "#419B4F" + }, + { + "LogLevel": "Warning", + "LogLabel": "Warning", + "ForeColorRGB": "#E1B002" + }, + { + "LogLevel": "Error", + "LogLabel": "Error", + "ForeColorRGB": "#ff0000" + }, + { + "LogLevel": "Error", + "LogLabel": "Exception", + "ForeColorRGB": "255;123;123" + }, + { + "LogLevel": "Critical", + "LogLabel": "Critical", + "ForeColorRGB": "#a70000" + }, + { + "LogLevel": "Critical", + "LogLabel": "Fatal", + "ForeColorRGB": "#FF6347" + } + ] +} \ No newline at end of file diff --git a/Projects/DLL/SystemX.Core.dll b/Projects/DLL/SystemX.Core.dll index cf2421f..1e63ab1 100644 Binary files a/Projects/DLL/SystemX.Core.dll and b/Projects/DLL/SystemX.Core.dll differ diff --git a/Projects/SystemX.Core/DBPatch/sqlScripts/dacpac/SystemX.DB.AccountDB.dacpac b/Projects/SystemX.Core/DBPatch/sqlScripts/dacpac/SystemX.DB.AccountDB.dacpac index 3dca7fa..503d4b3 100644 Binary files a/Projects/SystemX.Core/DBPatch/sqlScripts/dacpac/SystemX.DB.AccountDB.dacpac and b/Projects/SystemX.Core/DBPatch/sqlScripts/dacpac/SystemX.DB.AccountDB.dacpac differ diff --git a/Projects/SystemX.Core/SystemX.Core/Communication/Http.cs b/Projects/SystemX.Core/SystemX.Core/Communication/Http.cs index 9c92073..6198ff4 100644 --- a/Projects/SystemX.Core/SystemX.Core/Communication/Http.cs +++ b/Projects/SystemX.Core/SystemX.Core/Communication/Http.cs @@ -34,19 +34,19 @@ namespace SystemX.Core.Communication { await Task.Delay(1); try - { - Log4net.WriteLine($"[POST] Request({guid})::{url}{Environment.NewLine}{request?.ToJson()}", LogType.HTTP); + { + LogXnet.WriteLine($"[POST] Request({guid})::{url}{Environment.NewLine}{request?.ToJson()}", LogXLabel.HTTP); DateTime requestTime = DateTime.Now; var res = await httpClient.PostAsJsonAsync(url, request); response = await res.Content.ReadFromJsonAsync(); - Log4net.WriteLine($"[POST] Rseponse({guid}) ({(DateTime.Now - requestTime).TotalSeconds} sec)::{url}{Environment.NewLine}{response?.ToJson()}", LogType.HTTP); + LogXnet.WriteLine($"[POST] Rseponse({guid}) ({(DateTime.Now - requestTime).TotalSeconds} sec)::{url}{Environment.NewLine}{response?.ToJson()}", LogXLabel.HTTP); break; } catch (Exception e) - { - Log4net.WriteLine(e); + { + LogXnet.WriteLine(e); retry += 1; } @@ -79,16 +79,16 @@ namespace SystemX.Core.Communication if (string.IsNullOrEmpty(bearerToken) == false) httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", $"{bearerToken}"); - Log4net.WriteLine($"[GET] Request({guid})::{url}", LogType.HTTP); + LogXnet.WriteLine($"[GET] Request({guid})::{url}", LogXLabel.HTTP); DateTime requestTime = DateTime.Now; response = await httpClient.GetFromJsonAsync(url); - Log4net.WriteLine($"[GET] Rseponse({guid}) ({(DateTime.Now - requestTime).TotalSeconds} sec)::{url}", LogType.HTTP); + LogXnet.WriteLine($"[GET] Rseponse({guid}) ({(DateTime.Now - requestTime).TotalSeconds} sec)::{url}", LogXLabel.HTTP); } catch (Exception e) { - Log4net.WriteLine(e); + LogXnet.WriteLine(e); } } @@ -112,17 +112,17 @@ namespace SystemX.Core.Communication if (string.IsNullOrEmpty(bearerToken) == false) httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", $"{bearerToken}"); - Log4net.WriteLine($"[GET] Request({guid})::{url}", LogType.HTTP); + LogXnet.WriteLine($"[GET] Request({guid})::{url}", LogXLabel.HTTP); DateTime requestTime = DateTime.Now; var response = await httpClient.GetAsync(url); stream = await response.Content.ReadAsStreamAsync(); - Log4net.WriteLine($"[GET] Rseponse({guid}) ({(DateTime.Now - requestTime).TotalSeconds} sec)::{url}", LogType.HTTP); + LogXnet.WriteLine($"[GET] Rseponse({guid}) ({(DateTime.Now - requestTime).TotalSeconds} sec)::{url}", LogXLabel.HTTP); } catch (Exception e) { - Log4net.WriteLine(e); + LogXnet.WriteLine(e); } } diff --git a/Projects/SystemX.Core/SystemX.Core/Communication/Socket/Listener.cs b/Projects/SystemX.Core/SystemX.Core/Communication/Socket/Listener.cs index a118396..21f3e4b 100644 --- a/Projects/SystemX.Core/SystemX.Core/Communication/Socket/Listener.cs +++ b/Projects/SystemX.Core/SystemX.Core/Communication/Socket/Listener.cs @@ -53,12 +53,12 @@ namespace SystemX.Core.Communication } else { - Log4net.WriteLine(args.SocketError.ToString(), LogType.Error); + LogXnet.WriteLine(args.SocketError.ToString(), LogXLabel.Error); } } catch(Exception e) { - Log4net.WriteLine(e, LogType.Error); + LogXnet.WriteLine(e); } RegisterAccept(args); diff --git a/Projects/SystemX.Core/SystemX.Core/Communication/Socket/Session.cs b/Projects/SystemX.Core/SystemX.Core/Communication/Socket/Session.cs index 4013e0c..3f9e858 100644 --- a/Projects/SystemX.Core/SystemX.Core/Communication/Socket/Session.cs +++ b/Projects/SystemX.Core/SystemX.Core/Communication/Socket/Session.cs @@ -138,7 +138,7 @@ namespace SystemX.Core.Communication } catch (Exception e) { - Log4net.WriteLine($"RegisterSend Failed {e}", LogType.Error); + LogXnet.WriteLine($"RegisterSend Failed {e}", LogXLabel.Exception); } } @@ -160,7 +160,7 @@ namespace SystemX.Core.Communication } catch (Exception e) { - Log4net.WriteLine($"OnSendCompleted Failed {e}", LogType.Error); + LogXnet.WriteLine($"OnSendCompleted Failed {e}", LogXLabel.Exception); } } else @@ -187,7 +187,7 @@ namespace SystemX.Core.Communication } catch (Exception e) { - Log4net.WriteLine($"RegisterRecv Failed {e}", LogType.Error); + LogXnet.WriteLine($"RegisterRecv Failed {e}", LogXLabel.Exception); } } @@ -223,7 +223,7 @@ namespace SystemX.Core.Communication } catch (Exception e) { - Log4net.WriteLine($"OnRecvCompleted Failed {e}", LogType.Error); + LogXnet.WriteLine($"OnRecvCompleted Failed {e}", LogXLabel.Exception); } } else diff --git a/Projects/SystemX.Core/SystemX.Core/DB/DBTransaction.cs b/Projects/SystemX.Core/SystemX.Core/DB/DBTransaction.cs index b1ee905..71cc638 100644 --- a/Projects/SystemX.Core/SystemX.Core/DB/DBTransaction.cs +++ b/Projects/SystemX.Core/SystemX.Core/DB/DBTransaction.cs @@ -31,7 +31,7 @@ namespace SystemX.Core.DB } catch (Exception ex) { - Log4net.WriteLine(ex); + LogXnet.WriteLine(ex); } return entity; @@ -52,13 +52,13 @@ namespace SystemX.Core.DB transaction.Commit(); result = true; - Log4net.WriteLine("Transaction Commit", LogType.Debug); + LogXnet.WriteLine("Transaction Commit", LogXLabel.Debug); } catch (Exception ex) { transaction.Rollback(); - Log4net.WriteLine("Transaction Rollback", LogType.Error); - Log4net.WriteLine(ex); + LogXnet.WriteLine("Transaction Rollback", LogXLabel.Exception); + LogXnet.WriteLine(ex); } transaction.Dispose(); @@ -81,13 +81,13 @@ namespace SystemX.Core.DB await transaction.CommitAsync(); result = true; - Log4net.WriteLine("Transaction Commit", LogType.Debug); + LogXnet.WriteLine("Transaction Commit", LogXLabel.Debug); } catch (Exception ex) { await transaction.RollbackAsync(); - Log4net.WriteLine("Transaction Rollback", LogType.Error); - Log4net.WriteLine(ex); + LogXnet.WriteLine("Transaction Rollback", LogXLabel.Exception); + LogXnet.WriteLine(ex); } await transaction.DisposeAsync(); diff --git a/Projects/SystemX.Core/SystemX.Core/Log4net/Log4net.cs b/Projects/SystemX.Core/SystemX.Core/Log4net/Log4net.cs deleted file mode 100644 index 4eb1b00..0000000 --- a/Projects/SystemX.Core/SystemX.Core/Log4net/Log4net.cs +++ /dev/null @@ -1,405 +0,0 @@ -using log4net; -using log4net.Repository; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; - - -#region LogType -public enum LogType -{ - //default level - Info = 0, - Warn = 1, - Error = 2, - Debug = 3, - Fatal = 4, - - //custom level - Exception = 7, - - DB = 10, - - HTTP = 20, - SOCKET = 21, - CONTROLLER = 22, -} -#endregion - -#region CustomLevel -public static class Log4netCustomLevel -{ - public static readonly log4net.Core.Level EXCEPTION = new log4net.Core.Level(10007, LogType.Exception.ToString()); - public static readonly log4net.Core.Level DB = new log4net.Core.Level(10010, LogType.DB.ToString()); - public static readonly log4net.Core.Level HTTP = new log4net.Core.Level(10020, LogType.HTTP.ToString()); - public static readonly log4net.Core.Level SOCKET = new log4net.Core.Level(10021, LogType.SOCKET.ToString()); - public static readonly log4net.Core.Level CONTROLLER = new log4net.Core.Level(10022, LogType.CONTROLLER.ToString()); - - public static void SetCustomLevel(ILoggerRepository repo) - { - repo.LevelMap.Add(EXCEPTION); - repo.LevelMap.Add(DB); - repo.LevelMap.Add(HTTP); - repo.LevelMap.Add(SOCKET); - repo.LevelMap.Add(CONTROLLER); - } -} -#endregion - -public static class Log4net -{ - private static ILog? Manager; - - private static ILoggerRepository repo = LogManager.GetRepository(); - - public static bool IsConfigLoad { get; set; } = false; - - public static string Log4netConfigPath { get; } = @"../../Config/log4net.config"; - - //로그 사용여부 - public static bool IsDebugEnabled { get; set; } = true; - public static bool IsDBEnabled { get; set; } = true; - public static bool IsHttpEnabled { get; set; } = true; - public static bool IsSocketEnabled { get; set; } = true; - public static bool IsControllerEnabled { get; set; } = true; - - //자동삭제 - private static bool AutoRemove { get; set; } = false; - private static int AutoRemoveKeepingDay = 30; - - static Log4net() - { - string log4netConfigPath = Log4netConfigPath; - - if (File.Exists(log4netConfigPath) == true) - { - File.Delete(log4netConfigPath); - } - - Console.WriteLine($"Create log4netConfig: {log4netConfigPath}"); - File.WriteAllText(log4netConfigPath, Config); - - IsConfigLoad = OpenConfig(log4netConfigPath); - } - - private static bool OpenConfig(string path) - { - bool result = true; - - try - { - Log4netCustomLevel.SetCustomLevel(repo); - - if (File.Exists(path) == false) - result = false; - - log4net.Config.XmlConfigurator.Configure(new FileInfo(path)); - Manager = LogManager.GetLogger(""); - } - catch (Exception e) - { - Console.WriteLine("Log4net Init Error"); - Console.WriteLine(e.Message); - result = false; - } - - return result; - } - - public static void AutoRemoveLog(int autoRemoveKeepingDay = 30) - { - if (AutoRemove == false) - { - AutoRemove = true; - AutoRemoveKeepingDay = autoRemoveKeepingDay; - - string logDirectory = @$"{Path.GetDirectoryName(Environment.ProcessPath)}\log"; - Log4net.WriteLine($"Log4net Auto Remove: {AutoRemove}, Remove Day: -{AutoRemoveKeepingDay}", LogType.Warn); - Log4net.WriteLine($"Log4net Auto Path: {logDirectory}", LogType.Warn); - - Task.Run(async () => - { - //1분후 시작 - await Task.Delay(TimeSpan.FromMinutes(1)); - while (true) - { - var files = Directory.GetFiles(logDirectory, "*.log", SearchOption.AllDirectories); - foreach (var file in files) - { - var lastAccessDateTime = File.GetLastWriteTime(file); - if (lastAccessDateTime < DateTime.Now.AddDays(AutoRemoveKeepingDay * -1)) - { - try - { - File.Delete(file); - WriteLine($"Remove log: {Path.GetFileName(file)}", LogType.Warn); - } - catch - { - WriteLine($"Using log file: {Path.GetFileName(file)}", LogType.Warn); - } - } - } - - //일정시간마다 반복 - Log4net.WriteLine($"Log Auto Remove Run", LogType.Warn); - await Task.Delay(TimeSpan.FromHours(12)); - } - }); - } - } - - public static void WriteLine(T log, LogType logType = LogType.Info, bool trace = false, - [System.Runtime.CompilerServices.CallerMemberName] string memberName = "", - [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "", - [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0) - { - if (IsConfigLoad == false) - { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine($"[Log4net Initialize Error] {log}"); - return; - } - - if(log is Exception ex) - { - WriteLineException(ex, memberName, sourceFilePath, sourceLineNumber); - return; - } - - string strTrace = $"TRACE::[{Path.GetFileName(sourceFilePath)}][Method:{memberName}][LINE:{sourceLineNumber}]"; - - switch (logType) - { - case LogType.Info: - { - if (trace == true) - { - Manager?.Info($"{strTrace}"); - } - Manager?.Info(log); - break; - } - case LogType.Warn: - { - if (trace == true) - { - Manager?.Warn($"{strTrace}"); - } - Manager?.Warn(log); - break; - } - case LogType.Error: - { - if (trace == true) - { - Manager?.Error($"{strTrace}"); - } - Manager?.Error(log); - break; - } - case LogType.Debug: - { - if (IsDebugEnabled == true) - { - if (trace == true) - { - Manager?.Debug($"{strTrace}"); - } - Manager?.Debug(log); - } - break; - } - case LogType.Fatal: - { - Manager?.Fatal($"{strTrace}"); - Manager?.Fatal(log); - break; - } - case LogType.Exception: - { - Type? t = MethodBase.GetCurrentMethod()?.DeclaringType; - if (t != null) - { - if (trace == true) - { - Manager?.Logger.Log(t, Log4netCustomLevel.EXCEPTION, $"{strTrace}", null); - } - Manager?.Logger.Log(t, Log4netCustomLevel.EXCEPTION, log, null); - } - break; - } - case LogType.DB: - { - if(IsDBEnabled == true) - { - Type? t = MethodBase.GetCurrentMethod()?.DeclaringType; - if (t != null) - { - if (trace == true) - { - Manager?.Logger.Log(t, Log4netCustomLevel.DB, $"{strTrace}", null); - } - Manager?.Logger.Log(t, Log4netCustomLevel.DB, log, null); - } - } - break; - } - case LogType.HTTP: - { - if(IsHttpEnabled == true) - { - Type? t = MethodBase.GetCurrentMethod()?.DeclaringType; - if (t != null) - { - if (trace == true) - { - Manager?.Logger.Log(t, Log4netCustomLevel.HTTP, $"{strTrace}", null); - } - Manager?.Logger.Log(t, Log4netCustomLevel.HTTP, log, null); - } - } - break; - } - case LogType.SOCKET: - { - if(IsSocketEnabled == true) - { - Type? t = MethodBase.GetCurrentMethod()?.DeclaringType; - if (t != null) - { - if (trace == true) - { - Manager?.Logger.Log(t, Log4netCustomLevel.SOCKET, $"{strTrace}", null); - } - Manager?.Logger.Log(t, Log4netCustomLevel.SOCKET, log, null); - } - } - break; - } - case LogType.CONTROLLER: - { - if(IsControllerEnabled == true) - { - Type? t = MethodBase.GetCurrentMethod()?.DeclaringType; - if (t != null) - { - if (trace == true) - { - Manager?.Logger.Log(t, Log4netCustomLevel.CONTROLLER, $"{strTrace}", null); - } - Manager?.Logger.Log(t, Log4netCustomLevel.CONTROLLER, log, null); - } - } - break; - } - } - } - - private static void WriteLineException(Exception? ex, - [System.Runtime.CompilerServices.CallerMemberName] string memberName = "", - [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "", - [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0) - { - WriteLine($"TRACE::[{Path.GetFileName(sourceFilePath)}][Method:{memberName}][LINE:{sourceLineNumber}]", LogType.Exception); - WriteLine(ex?.Message, LogType.Exception); - } - - #region Config - static string Config = @$" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"; - #endregion -} - - -/* -log4net 지정 가능 색상 -Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, Gray, -DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White - */ \ No newline at end of file diff --git a/Projects/SystemX.Core/SystemX.Core/LogXnet/ChannelLogger.cs b/Projects/SystemX.Core/SystemX.Core/LogXnet/ChannelLogger.cs new file mode 100644 index 0000000..8a791a8 --- /dev/null +++ b/Projects/SystemX.Core/SystemX.Core/LogXnet/ChannelLogger.cs @@ -0,0 +1,171 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Channels; +using System.Threading.Tasks; + +public class ChannelLogger : ILogger, IDisposable +{ + public class ChannelLog + { + public string message { get; set; } = string.Empty; + public string rgb { get; set; } = string.Empty; + } + + // + private readonly string _categoryName; + private static readonly Channel _logChannel = Channel.CreateUnbounded(new UnboundedChannelOptions + { + SingleReader = true, + SingleWriter = false + }); + + private static readonly Task _processorTask; + private static readonly object _initLock = new(); + private static bool _initialized = false; + + private static LogXnetConfig? _config; + private static LogLevel _currentLogLevel = LogLevel.Debug; + + static ChannelLogger() + { + _processorTask = Task.Run(ProcessLogMessagesAsync); + } + + public ChannelLogger(string categoryName) + { + _categoryName = categoryName; + + // Ensure static constructor ran + if (!_initialized) + { + lock (_initLock) + { + if (!_initialized) + { + _initialized = true; + } + } + } + } + + public IDisposable BeginScope(TState state) => default!; + public bool IsEnabled(LogLevel logLevel) + { + return logLevel >= _currentLogLevel; + } + + public void Log(LogLevel logLevel, EventId eventId, + TState state, Exception? exception, Func formatter) + { + if (!IsEnabled(logLevel)) return; + + var message = formatter(state, exception); + var timestamp = DateTime.Now.ToString($"yyyy-MM-dd HH:mm:ss.fff"); + + var fullMessage = string.Empty; + if(_config.TimeStampEnable == true) + { + fullMessage += $"[{timestamp}]"; + } + if(_config.ThreadIdEnable == true) + { + fullMessage += $"[{Environment.CurrentManagedThreadId}]"; + } + + fullMessage += $"[{eventId.Name}] {message}"; + _logChannel.Writer.TryWrite(new ChannelLog { message = fullMessage, rgb = $"{_config.LogDefines.Find(x=>x.LogLabel.ToLower() == eventId.Name.ToLower())?.ForeColorRGB}" } ); + } + + private static async Task ProcessLogMessagesAsync() + { + DateTime currentDate = DateTime.Now.Date; + StreamWriter? writer = null; + + await foreach (var msg in _logChannel.Reader.ReadAllAsync()) + { + // 현재 날짜 구함 + var logDate = DateTime.Now.Date; + + if (currentDate != logDate || writer == null) + { + // 날짜가 바뀐 경우: 기존 파일 닫고 새 파일 생성 + writer?.Dispose(); + + string folderPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + var logDir = $@"{folderPath}/{_config.OutputFilePath}/{logDate.Year}/{logDate.Month}/"; + Directory.CreateDirectory(logDir); + + var logFile = Path.Combine(logDir, $"{logDate.ToString("yyyy-MM-dd")}.log"); + writer = new StreamWriter(new FileStream(logFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) + { + AutoFlush = true + }; + + currentDate = logDate; + } + + if(_config.ConsoleEnable == true) + { + // 색상 지정, 로그출력 + if (string.IsNullOrEmpty(msg.rgb) == false) + { + try + { + if (msg.rgb.Contains("#")) + { + var color = ColorTranslator.FromHtml(msg.rgb); + msg.rgb = $"{color.R};{color.G};{color.B}"; + } + + Console.Write($"\u001b[38;2;{msg.rgb}m"); + } + catch (Exception ex) + { + } + } + Console.WriteLine(msg.message); + Console.Write("\u001b[0m"); + } + + if(_config.FileOutputEnable == true) + { + // 파일 출력 + await writer.WriteLineAsync(msg.message); + } + } + + writer?.Dispose(); + } + + public static async Task ShutdownAsync() + { + _logChannel.Writer.Complete(); + await _processorTask; + } + + public static void SetConfig(LogXnetConfig config) + { + _config = config; + + if(Enum.TryParse(_config.LogLevel, out var logLevel) == true) + { + _currentLogLevel = logLevel; + } + } + + public static void SetLogLevel(LogLevel level) + { + _currentLogLevel = level; + } + + public void Dispose() + { + } +} + diff --git a/Projects/SystemX.Core/SystemX.Core/LogXnet/ChannelLoggerProvider.cs b/Projects/SystemX.Core/SystemX.Core/LogXnet/ChannelLoggerProvider.cs new file mode 100644 index 0000000..45b3e02 --- /dev/null +++ b/Projects/SystemX.Core/SystemX.Core/LogXnet/ChannelLoggerProvider.cs @@ -0,0 +1,20 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +public class ChannelLoggerProvider : ILoggerProvider +{ + public ILogger CreateLogger(string categoryName) + { + return new ChannelLogger(categoryName); + } + + public void Dispose() + { + ChannelLogger.ShutdownAsync().Wait(); + } +} + diff --git a/Projects/SystemX.Core/SystemX.Core/LogXnet/LogXLabel.cs b/Projects/SystemX.Core/SystemX.Core/LogXnet/LogXLabel.cs new file mode 100644 index 0000000..1c196c9 --- /dev/null +++ b/Projects/SystemX.Core/SystemX.Core/LogXnet/LogXLabel.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +public enum LogXLabel +{ + DEFAULT = 0, + + Debug = 1000, + DB = 1100, + HTTP = 1200, + CONTROLLER = 1250, + SOCKET=1300, + + Information = 2000, + INFO = 2010, + + Warning = 3000, + + Error = 4000, + Exception = 4100, + + Critical = 5000, + Fatal = 5001, +} + diff --git a/Projects/SystemX.Core/SystemX.Core/LogXnet/LogXnet.cs b/Projects/SystemX.Core/SystemX.Core/LogXnet/LogXnet.cs new file mode 100644 index 0000000..1ae38e2 --- /dev/null +++ b/Projects/SystemX.Core/SystemX.Core/LogXnet/LogXnet.cs @@ -0,0 +1,162 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Reflection.Emit; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; + +public static class LogXnet +{ + private static ILoggerFactory? _factory; + private static ILogger? _logger; + + public static bool ConfigLoad { get; private set; } = false; + private static LogXnetConfig? _config { get; set; } + + static LogXnet() + { + Initialize(); + } + + public static bool ReadConfig(string configPath) + { + try + { + var readConfigJson = File.ReadAllText(configPath); + _config = JsonSerializer.Deserialize(readConfigJson); + + if(_config != null) + { + var level = Enum.Parse(_config.LogLevel); + SetConfig(_config); + + //Auto Config + if (_config.AutoRemoveEnable == true) + { + Task.Run(FileAutoRemove); + WriteLine($"Auto log remove enable: Keeping {_config.AutoRemoveIntervalDay} day.", LogXLabel.INFO); + } + else + { + WriteLine($"Auto log remove disnable", LogXLabel.Warning); + } + } + + ConfigLoad = true; + } + catch(Exception ex) + { + WriteLine(ex); + } + + return ConfigLoad; + } + + private static void Initialize() + { + _factory = LoggerFactory.Create(builder => + { + builder.ClearProviders(); + builder.AddProvider(new ChannelLoggerProvider()); + builder.SetMinimumLevel(LogLevel.Debug); + }); + + _logger = _factory.CreateLogger("Global"); + } + + public static void WriteLine(string message, string logLabel) + { + if(_config != null) + { + var logLevelStr = _config.LogDefines.Find(x => $"{x.LogLabel.ToLower()}" == $"{logLabel.ToLower()}")?.LogLevel; + if (Enum.TryParse(logLevelStr, out var logLevel) == true) + { + switch (logLevel) + { + case LogLevel.Trace: + _logger?.LogTrace(new EventId(1000, $"{logLabel}"), message); + break; + case LogLevel.Debug: + _logger?.LogDebug(new EventId(1000, $"{logLabel}"), message); + break; + case LogLevel.Information: + _logger?.LogInformation(new EventId(1000, $"{logLabel}"), message); + break; + case LogLevel.Warning: + _logger?.LogWarning(new EventId(1000, $"{logLabel}"), message); + break; + case LogLevel.Error: + _logger?.LogError(new EventId(1000, $"{logLabel}"), message); + break; + case LogLevel.Critical: + _logger?.LogCritical(new EventId(1000, $"{logLabel}"), message); + break; + + default: + break; + } + } + else + { + _logger?.LogCritical(new EventId(1000, $"DEFAULT"), message); + } + } + } + + public static void WriteLine(string message, LogXLabel logLabel = LogXLabel.DEFAULT) + { + WriteLine(message, logLabel.ToString()); + } + + public static void WriteLine(Exception ex) + { + WriteLine(ex.Message, LogXLabel.Exception.ToString()); + } + + public static void SetLogLevel(LogLevel level) + { + ChannelLogger.SetLogLevel(level); + } + + private static void SetConfig(LogXnetConfig config) + { + ChannelLogger.SetConfig(config); + } + + private static async Task FileAutoRemove() + { + while (true) + { + if (_config.AutoRemoveEnable == false) + { + break; + } + + string folderPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + var logDir = $@"{folderPath}/{_config.OutputFilePath}"; + var files = Directory.GetFiles(logDir, "", SearchOption.AllDirectories); + + foreach (var f in files) + { + var fileName = Path.GetFileNameWithoutExtension(f); + if (DateTime.Now - DateTime.Parse(fileName) >= TimeSpan.FromDays(_config.AutoRemoveIntervalDay)) + { + File.Delete(f); + WriteLine($"Remove Log: {fileName}.log", LogXLabel.Warning); + } + } + + await Task.Delay(new TimeSpan(0, 1, 0)); + } + } + + public static void Shutdown() + { + _factory?.Dispose(); + } +} + diff --git a/Projects/SystemX.Core/SystemX.Core/LogXnet/LogXnetConfig.cs b/Projects/SystemX.Core/SystemX.Core/LogXnet/LogXnetConfig.cs new file mode 100644 index 0000000..e7e8a19 --- /dev/null +++ b/Projects/SystemX.Core/SystemX.Core/LogXnet/LogXnetConfig.cs @@ -0,0 +1,30 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +public class LogXnetConfig +{ + public bool ConsoleEnable { get; set; } = true; + public bool FileOutputEnable { get; set; } = true; + public bool TimeStampEnable { get; set; } = true; + public bool ThreadIdEnable { get; set; } = true; + public bool AutoRemoveEnable { get; set; } = true; + + + public string OutputFilePath { get; set; } = string.Empty; + public string TimeStampForamt { get; set; } = "yyyy-MM-dd HH:mm:ss.fff"; + public int AutoRemoveIntervalDay { get; set; } = 30; + public string LogLevel { get; set; } = $"Information"; + + public List LogDefines { get; set; } = new List(); + + public class LogDefine + { + public string LogLevel { get; set; } = string.Empty; + public string LogLabel { get; set; } = string.Empty; + public string ForeColorRGB { get; set; } = string.Empty; + } +} \ No newline at end of file diff --git a/Projects/SystemX.Core/SystemX.Core/Model/Auth/Login.cs b/Projects/SystemX.Core/SystemX.Core/Model/Auth/Login.cs index 58d60b3..3702a63 100644 --- a/Projects/SystemX.Core/SystemX.Core/Model/Auth/Login.cs +++ b/Projects/SystemX.Core/SystemX.Core/Model/Auth/Login.cs @@ -1,5 +1,4 @@ -using log4net.Core; -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; diff --git a/Projects/SystemX.Core/SystemX.Core/Model/Auth/Logout.cs b/Projects/SystemX.Core/SystemX.Core/Model/Auth/Logout.cs index 85767d2..88faba0 100644 --- a/Projects/SystemX.Core/SystemX.Core/Model/Auth/Logout.cs +++ b/Projects/SystemX.Core/SystemX.Core/Model/Auth/Logout.cs @@ -1,5 +1,4 @@ -using log4net.Core; -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; diff --git a/Projects/SystemX.Core/SystemX.Core/Model/Auth/Register.cs b/Projects/SystemX.Core/SystemX.Core/Model/Auth/Register.cs index 738162c..cde0682 100644 --- a/Projects/SystemX.Core/SystemX.Core/Model/Auth/Register.cs +++ b/Projects/SystemX.Core/SystemX.Core/Model/Auth/Register.cs @@ -1,5 +1,4 @@ -using log4net.Core; -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; diff --git a/Projects/SystemX.Core/SystemX.Core/Services/DBContextProvider.cs b/Projects/SystemX.Core/SystemX.Core/Services/DBContextProvider.cs index 0e7e12d..07a9e43 100644 --- a/Projects/SystemX.Core/SystemX.Core/Services/DBContextProvider.cs +++ b/Projects/SystemX.Core/SystemX.Core/Services/DBContextProvider.cs @@ -23,7 +23,7 @@ namespace SystemX.Core.Services if (DBDictionary.ContainsKey($"{db.DBName}") == false) DBDictionary.Add($"{db.DBName}", db); else - Log4net.WriteLine($"Exist key DB Dictionary {db.DBName}", LogType.Error); + LogXnet.WriteLine($"Exist key DB Dictionary {db.DBName}", LogXLabel.Error); } } } diff --git a/Projects/SystemX.Core/SystemX.Core/SystemX.Core.csproj b/Projects/SystemX.Core/SystemX.Core/SystemX.Core.csproj index ed90dae..29111eb 100644 --- a/Projects/SystemX.Core/SystemX.Core/SystemX.Core.csproj +++ b/Projects/SystemX.Core/SystemX.Core/SystemX.Core.csproj @@ -19,7 +19,6 @@ - all diff --git a/Projects/SystemX.Core/SystemX.Core/Utils/JsonUtils.cs b/Projects/SystemX.Core/SystemX.Core/Utils/JsonUtils.cs index 16ae4c1..8e570d0 100644 --- a/Projects/SystemX.Core/SystemX.Core/Utils/JsonUtils.cs +++ b/Projects/SystemX.Core/SystemX.Core/Utils/JsonUtils.cs @@ -16,8 +16,8 @@ public static class JsonUtils } catch (Exception e) { - Log4net.WriteLine("JsonUtils.ToJson()", LogType.Error); - Log4net.WriteLine(e); + LogXnet.WriteLine("JsonUtils.ToJson()", LogXLabel.Exception); + LogXnet.WriteLine(e); } return result; @@ -32,7 +32,7 @@ public static class JsonUtils } catch(Exception e) { - Log4net.WriteLine("JsonUtils.ToObject()", LogType.Warn); + LogXnet.WriteLine("JsonUtils.ToObject()", LogXLabel.Warning); } return result;