[성현모] Log4net 제거, LogXnet 기능 추가

This commit is contained in:
SHM
2025-07-24 16:00:18 +09:00
parent f8a3ee436e
commit f03bf86d31
19 changed files with 521 additions and 440 deletions

View File

@ -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"
}
]
}

Binary file not shown.

View File

@ -35,18 +35,18 @@ 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<RESPONSE>();
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<RESPONSE>(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);
}
}

View File

@ -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);

View File

@ -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

View File

@ -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();

View File

@ -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>(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 = @$"<?xml version=""1.0"" encoding=""utf-8"" ?>
<configuration>
<log4net>
<root>
<level value=""ALL""/>
<appender-ref ref=""Console""/>
<appender-ref ref=""file""/>
<appender-ref ref=""fatal_file""/>
</root>
<appender name=""Console"" type=""log4net.Appender.ManagedColoredConsoleAppender"">
<layout type=""log4net.Layout.PatternLayout"">
<conversionPattern value=""[%date] [%thread] %-2level: %message%newline"" />
</layout>
<mapping>
<level value=""FATAL"" />
<foreColor value=""White"" />
<backColor value=""Red"" />
</mapping>
<mapping>
<level value=""ERROR"" />
<foreColor value=""Red"" />
</mapping>
<mapping>
<level value=""WARN"" />
<foreColor value=""Yellow"" />
</mapping>
<mapping>
<level value=""INFO"" />
<foreColor value=""Green"" />
</mapping>
<mapping>
<level value=""DEBUG"" />
<foreColor value=""Blue"" />
</mapping>
<mapping>
<level value=""EXCEPTION"" />
<foreColor value=""DarkRed"" />
</mapping>
<mapping>
<level value=""DB"" />
<foreColor value=""DarkMagenta"" />
</mapping>
<mapping>
<level value=""HTTP"" />
<foreColor value=""DarkYellow"" />
</mapping>
<mapping>
<level value=""SOCKET"" />
<foreColor value=""DarkCyan"" />
</mapping>
<mapping>
<level value=""CONTROLLER"" />
<foreColor value=""Magenta"" />
</mapping>
</appender>
<appender name=""file"" type=""log4net.Appender.RollingFileAppender"">
<file value=""log/"" />
<datepattern value=""yyyy////MM////yyyy-MM-dd'.log'""/>
<appendToFile value=""true"" />
<rollingStyle value=""Date"" />
<staticLogFileName value=""false"" />
<layout type=""log4net.Layout.PatternLayout"">
<conversionPattern value=""[%date] [%thread] %level %logger - %message%newline"" />
</layout>
</appender>
<appender name=""fatal_file"" type=""log4net.Appender.RollingFileAppender"">
<file value=""log/"" />
<datepattern value=""yyyy////MM////yyyy-MM-dd'_fatal.log'""/>
<appendToFile value=""true"" />
<rollingStyle value=""Date"" />
<staticLogFileName value=""false"" />
<filter type=""log4net.Filter.LevelRangeFilter"">
<param name=""LevelMin"" value=""FATAL"" />
<param name=""LevelMax"" value=""FATAL"" />
</filter>
<layout type=""log4net.Layout.PatternLayout"">
<conversionPattern value=""[%date] [%thread] %level %logger - %message%newline"" />
</layout>
</appender>
</log4net>
</configuration>";
#endregion
}
/*
log4net 지정 가능 색상
Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, Gray,
DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White
*/

View File

@ -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<ChannelLog> _logChannel = Channel.CreateUnbounded<ChannelLog>(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>(TState state) => default!;
public bool IsEnabled(LogLevel logLevel)
{
return logLevel >= _currentLogLevel;
}
public void Log<TState>(LogLevel logLevel, EventId eventId,
TState state, Exception? exception, Func<TState, Exception?, string> 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<LogLevel>(_config.LogLevel, out var logLevel) == true)
{
_currentLogLevel = logLevel;
}
}
public static void SetLogLevel(LogLevel level)
{
_currentLogLevel = level;
}
public void Dispose()
{
}
}

View File

@ -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();
}
}

View File

@ -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,
}

View File

@ -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<LogXnetConfig>(readConfigJson);
if(_config != null)
{
var level = Enum.Parse<LogLevel>(_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<LogLevel>(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();
}
}

View File

@ -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<LogDefine> LogDefines { get; set; } = new List<LogDefine>();
public class LogDefine
{
public string LogLevel { get; set; } = string.Empty;
public string LogLabel { get; set; } = string.Empty;
public string ForeColorRGB { get; set; } = string.Empty;
}
}

View File

@ -1,5 +1,4 @@
using log4net.Core;
using System;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;

View File

@ -1,5 +1,4 @@
using log4net.Core;
using System;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;

View File

@ -1,5 +1,4 @@
using log4net.Core;
using System;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;

View File

@ -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);
}
}
}

View File

@ -19,7 +19,6 @@
<ItemGroup>
<PackageReference Include="CsvHelper" Version="33.0.1" />
<PackageReference Include="log4net" Version="3.0.4" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.3.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.6">
<PrivateAssets>all</PrivateAssets>

View File

@ -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;