From 239c4fca3233a21ab9fde9c5f945253db67ddc86 Mon Sep 17 00:00:00 2001 From: Master Date: Sat, 14 Oct 2023 19:39:26 +0200 Subject: [PATCH] add proper logger, saves to file as well --- AscNet.Common/Util/Logger.cs | 101 --------- AscNet.GameServer/AscNet.GameServer.csproj | 1 + AscNet.GameServer/Packet.cs | 12 +- AscNet.GameServer/Server.cs | 16 +- AscNet.GameServer/Session.cs | 34 +-- AscNet.Logging/AscNet.Logging.csproj | 9 + AscNet.Logging/ILogger.cs | 18 ++ AscNet.Logging/LogLevel.cs | 13 ++ AscNet.Logging/Logger.cs | 201 ++++++++++++++++++ AscNet.Logging/LoggerFactory.cs | 23 ++ AscNet.Logging/LoggingExtensions.cs | 16 ++ AscNet.Logging/ThreadSafeStreamWriter.cs | 60 ++++++ AscNet.SDKServer/AscNet.SDKServer.csproj | 1 + .../Controllers/ConfigController.cs | 8 +- AscNet.SDKServer/SDKServer.cs | 10 +- AscNet.sln | 8 +- AscNet/Program.cs | 11 +- 17 files changed, 402 insertions(+), 140 deletions(-) delete mode 100644 AscNet.Common/Util/Logger.cs create mode 100644 AscNet.Logging/AscNet.Logging.csproj create mode 100644 AscNet.Logging/ILogger.cs create mode 100644 AscNet.Logging/LogLevel.cs create mode 100644 AscNet.Logging/Logger.cs create mode 100644 AscNet.Logging/LoggerFactory.cs create mode 100644 AscNet.Logging/LoggingExtensions.cs create mode 100644 AscNet.Logging/ThreadSafeStreamWriter.cs diff --git a/AscNet.Common/Util/Logger.cs b/AscNet.Common/Util/Logger.cs deleted file mode 100644 index b01d30bd..00000000 --- a/AscNet.Common/Util/Logger.cs +++ /dev/null @@ -1,101 +0,0 @@ -using System.Diagnostics; - -namespace AscNet.Common.Util -{ - // TODO: Extend, add file logging, correct some behavior, ensure proper formatting - public class Logger - { - public static readonly Logger c = new(nameof(AscNet), ConsoleColor.DarkRed); - private readonly string _name; - private readonly bool TraceOnError; - private readonly ConsoleColor _color; - - public Logger(string name, ConsoleColor color = ConsoleColor.Cyan, bool traceOnError = true) - { - _name = name; - _color = color; - TraceOnError = traceOnError; - } - - public void Log(params string[] message) - { - Console.ForegroundColor = ConsoleColor.White; - Console.Write(DateTime.Now.ToString("HH:mm:ss ")); - Console.ResetColor(); - Console.Write("<"); - Console.ForegroundColor = _color; - Console.Write(_name); - Console.ResetColor(); - Console.Write("> "); - Console.WriteLine(string.Join("\t", message)); - Console.ResetColor(); - } - - public void Warn(params string[] message) - { - Console.ForegroundColor = ConsoleColor.White; - Console.Write(DateTime.Now.ToString("HH:mm:ss ")); - Console.ResetColor(); - Console.Write("<"); - Console.ForegroundColor = ConsoleColor.Yellow; - Console.Write(_name); - Console.ResetColor(); - Console.Write("> "); - Console.WriteLine(string.Join("\t", message)); - Console.ResetColor(); - } - - public void Trail(params string[] msg) - { - Console.ForegroundColor = ConsoleColor.DarkGray; - Console.WriteLine($"\t└── {string.Join(' ', msg)}"); - Console.ResetColor(); - } - - public void Error(params string[] message) - { - Console.ForegroundColor = ConsoleColor.White; - Console.Write(DateTime.Now.ToString("HH:mm:ss ")); - Console.ResetColor(); - Console.Write("<"); - Console.ForegroundColor = ConsoleColor.Red; - Console.Write(_name); - Console.ResetColor(); - Console.Write("> "); - Console.ForegroundColor = ConsoleColor.White; - if (TraceOnError) - Console.BackgroundColor = ConsoleColor.DarkRed; - Console.WriteLine(string.Join("\t", message)); - Console.ResetColor(); -#if DEBUG - StackTrace trace = new(true); - if (TraceOnError) - Trail(trace.ToString()); -#endif - } - - public void Debug(params string[] message) - { -#if DEBUG - Console.ForegroundColor = ConsoleColor.White; - Console.Write(DateTime.Now.ToString("HH:mm:ss ")); - Console.ResetColor(); - Console.Write("<"); - Console.ForegroundColor = ConsoleColor.Cyan; - Console.Write(_name); - Console.ResetColor(); - Console.Write("> "); - Console.ForegroundColor = ConsoleColor.White; - Console.BackgroundColor = ConsoleColor.DarkMagenta; - Console.WriteLine(string.Join("\t", message)); - Console.ResetColor(); - Console.BackgroundColor = ConsoleColor.Black; - - StackTrace trace = new(true); - if (TraceOnError) - Trail(trace.ToString()); -#endif - } - } -} - diff --git a/AscNet.GameServer/AscNet.GameServer.csproj b/AscNet.GameServer/AscNet.GameServer.csproj index c7aa1d0d..b1053c0e 100644 --- a/AscNet.GameServer/AscNet.GameServer.csproj +++ b/AscNet.GameServer/AscNet.GameServer.csproj @@ -18,6 +18,7 @@ + diff --git a/AscNet.GameServer/Packet.cs b/AscNet.GameServer/Packet.cs index 41049cab..5725b9e2 100644 --- a/AscNet.GameServer/Packet.cs +++ b/AscNet.GameServer/Packet.cs @@ -1,5 +1,5 @@ using System.Reflection; -using AscNet.Common.Util; +using AscNet.Logging; using MessagePack; namespace AscNet.GameServer @@ -92,7 +92,9 @@ namespace AscNet.GameServer public static class PacketFactory { public static readonly Dictionary ReqHandlers = new(); - static readonly Logger c = new("Factory", ConsoleColor.Yellow); + + // TODO: Configure based on session? + static readonly Logger log = new(typeof(PacketFactory), LogLevel.DEBUG, LogLevel.DEBUG); public static void LoadPacketHandlers() { @@ -101,7 +103,7 @@ namespace AscNet.GameServer private static void LoadRequestPacketHandlers() { - c.Log("Loading Packet Handlers..."); + log.Info("Loading Packet Handlers..."); IEnumerable classes = from t in Assembly.GetExecutingAssembly().GetTypes() select t; @@ -112,11 +114,11 @@ namespace AscNet.GameServer if (attr == null || ReqHandlers.ContainsKey(attr.Name)) continue; ReqHandlers.Add(attr.Name, (RequestPacketHandlerDelegate)Delegate.CreateDelegate(typeof(RequestPacketHandlerDelegate), method)); #if DEBUG - c.Log($"Loaded {method.Name}"); + log.Info($"Loaded {method.Name}"); #endif } - c.Log("Finished Loading Packet Handlers"); + log.Info("Finished Loading Packet Handlers"); } public static RequestPacketHandlerDelegate? GetRequestPacketHandler(string name) diff --git a/AscNet.GameServer/Server.cs b/AscNet.GameServer/Server.cs index cec4ea58..a5d29994 100644 --- a/AscNet.GameServer/Server.cs +++ b/AscNet.GameServer/Server.cs @@ -1,12 +1,12 @@ using System.Net.Sockets; using System.Net; -using AscNet.Common.Util; +using AscNet.Logging; namespace AscNet.GameServer { public class Server { - public static readonly Logger c = new(nameof(GameServer), ConsoleColor.Cyan); + public static Logger log; public readonly Dictionary Sessions = new(); private static Server? _instance; private readonly TcpListener listener; @@ -21,6 +21,10 @@ namespace AscNet.GameServer public Server() { + // TODO: add loglevel based on appsettings + LogLevel logLevel = LogLevel.DEBUG; + LogLevel fileLogLevel = LogLevel.DEBUG; + log = new(typeof(Server), logLevel, fileLogLevel); listener = new(IPAddress.Parse("0.0.0.0"), Common.Common.config.GameServer.Port); } @@ -31,21 +35,21 @@ namespace AscNet.GameServer try { listener.Start(); - c.Log($"{nameof(GameServer)} started and listening on port {Common.Common.config.GameServer.Port}"); + log.Info($"{nameof(GameServer)} started and listening on port {Common.Common.config.GameServer.Port}"); while (true) { TcpClient tcpClient = listener.AcceptTcpClient(); string id = tcpClient.Client.RemoteEndPoint!.ToString()!; - c.Warn($"{id} connected"); + log.Warn($"{id} connected"); Sessions.Add(id, new Session(id, tcpClient)); } } catch (Exception ex) { - c.Error("TCP listener error: " + ex.Message); - c.Log("Waiting 3 seconds before restarting..."); + log.Error("TCP listener error: " + ex.Message); + log.Info("Waiting 3 seconds before restarting..."); Thread.Sleep(3000); } } diff --git a/AscNet.GameServer/Session.cs b/AscNet.GameServer/Session.cs index e6ef0168..9cc312a3 100644 --- a/AscNet.GameServer/Session.cs +++ b/AscNet.GameServer/Session.cs @@ -2,8 +2,10 @@ using System.Net.Sockets; using AscNet.Common; using AscNet.Common.Util; +using AscNet.Logging; using MessagePack; using Newtonsoft.Json; +using Logger = AscNet.Logging.Logger; namespace AscNet.GameServer { @@ -11,7 +13,7 @@ namespace AscNet.GameServer { public readonly string id; public readonly TcpClient client; - public readonly Logger c; + public readonly Logger log; private long lastPacketTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); private ushort packetNo = 0; private readonly MessagePackSerializerOptions lz4Options = MessagePackSerializerOptions.Standard.WithCompression(MessagePackCompression.Lz4Block); @@ -20,7 +22,8 @@ namespace AscNet.GameServer { this.id = id; client = tcpClient; - c = new(id, ConsoleColor.DarkGray); + // TODO: add session based configuration? maybe from database? + log = new(typeof(Session), LogLevel.DEBUG, LogLevel.DEBUG); Task.Run(ClientLoop); } @@ -62,7 +65,7 @@ namespace AscNet.GameServer } catch (Exception) { - c.Error("Failed to deserialize packet: " + BitConverter.ToString(packet).Replace("-", "")); + log.Error("Failed to deserialize packet: " + BitConverter.ToString(packet).Replace("-", "")); } } } @@ -81,34 +84,37 @@ namespace AscNet.GameServer RequestPacketHandlerDelegate? requestPacketHandler = PacketFactory.GetRequestPacketHandler(request.Name); if (requestPacketHandler is not null) { + // TODO: with new logger this will be unnecessary if (Common.Common.config.VerboseLevel > VerboseLevel.Silent) - c.Log($"{request.Name}{(Common.Common.config.VerboseLevel >= VerboseLevel.Debug ? (", " + JsonConvert.SerializeObject(MessagePackSerializer.Typeless.Deserialize(request.Content))) : "")}"); + log.Info($"{request.Name}{(Common.Common.config.VerboseLevel >= VerboseLevel.Debug ? (", " + JsonConvert.SerializeObject(MessagePackSerializer.Typeless.Deserialize(request.Content))) : "")}"); requestPacketHandler.Invoke(this, request); } else { if (Common.Common.config.VerboseLevel > VerboseLevel.Silent) - c.Warn($"{request.Name} handler not found!{(Common.Common.config.VerboseLevel >= VerboseLevel.Debug ? (", " + JsonConvert.SerializeObject(MessagePackSerializer.Typeless.Deserialize(request.Content))) : "")}"); + log.Warn($"{request.Name} handler not found!{(Common.Common.config.VerboseLevel >= VerboseLevel.Debug ? (", " + JsonConvert.SerializeObject(MessagePackSerializer.Typeless.Deserialize(request.Content))) : "")}"); } break; + case Packet.ContentType.Push: Packet.Push push = MessagePackSerializer.Deserialize(packet.Content); debugContent = push.Content; - c.Log(push.Name); + log.Info(push.Name); throw new NotImplementedException($"Packet push handlers not implemented ({push.Name})"); - break; + case Packet.ContentType.Exception: Packet.Exception exception = MessagePackSerializer.Deserialize(packet.Content); - c.Error($"Exception packet received: {exception.Code}, {exception.Message}"); + log.Error($"Exception packet received: {exception.Code}, {exception.Message}"); break; + default: - c.Error($"Unknown packet received: {packet}"); + log.Error($"Unknown packet received: {packet}"); break; } } catch (Exception ex) { - c.Error("Failed to invoke handler: " + ex.Message + $", Raw {packet.Type} packet: " + BitConverter.ToString(debugContent).Replace("-", "")); + log.Error("Failed to invoke handler: " + ex.Message + $", Raw {packet.Type} packet: " + BitConverter.ToString(debugContent).Replace("-", "")); } } } @@ -140,7 +146,7 @@ namespace AscNet.GameServer Type = Packet.ContentType.Push, Content = MessagePackSerializer.Serialize(packet) }); - c.Log(packet.Name); + log.Info(packet.Name); } public void SendPush(string name, byte[] push) @@ -156,7 +162,7 @@ namespace AscNet.GameServer Type = Packet.ContentType.Push, Content = MessagePackSerializer.Serialize(packet) }); - c.Log(packet.Name); + log.Info(packet.Name); } public void SendResponse(T response, int clientSeq = 0) @@ -173,7 +179,7 @@ namespace AscNet.GameServer Type = Packet.ContentType.Response, Content = MessagePackSerializer.Serialize(packet) }); - c.Log(packet.Name); + log.Info(packet.Name); } private void Send(Packet packet) @@ -194,7 +200,7 @@ namespace AscNet.GameServer if (Server.Instance.Sessions.GetValueOrDefault(id) is null) return; - c.Warn($"{id} disconnected"); + log.Warn($"{id} disconnected"); client.Close(); Server.Instance.Sessions.Remove(id); } diff --git a/AscNet.Logging/AscNet.Logging.csproj b/AscNet.Logging/AscNet.Logging.csproj new file mode 100644 index 00000000..cfadb03d --- /dev/null +++ b/AscNet.Logging/AscNet.Logging.csproj @@ -0,0 +1,9 @@ + + + + net7.0 + enable + enable + + + diff --git a/AscNet.Logging/ILogger.cs b/AscNet.Logging/ILogger.cs new file mode 100644 index 00000000..10cd49f5 --- /dev/null +++ b/AscNet.Logging/ILogger.cs @@ -0,0 +1,18 @@ +namespace AscNet.Logging +{ + public interface ILogger + { + void Debug(string message, string memberName = ""); + + void Error(string message, Exception ex = null, string memberName = ""); + + void Fatal(string message, Exception ex = null, string memberName = ""); + + void Info(string message, string memberName = ""); + + void Dispose(); + + void Warn(string message, Exception ex = null, string memberName = ""); + } + +} diff --git a/AscNet.Logging/LogLevel.cs b/AscNet.Logging/LogLevel.cs new file mode 100644 index 00000000..9284b86e --- /dev/null +++ b/AscNet.Logging/LogLevel.cs @@ -0,0 +1,13 @@ +namespace AscNet.Logging +{ + public enum LogLevel : byte + { + OFF = 0, + FATAL = 8, + ERROR = 16, + WARN = 32, + INFO = 64, + DEBUG = 128, + ALL = 255 + } +} diff --git a/AscNet.Logging/Logger.cs b/AscNet.Logging/Logger.cs new file mode 100644 index 00000000..91356953 --- /dev/null +++ b/AscNet.Logging/Logger.cs @@ -0,0 +1,201 @@ +namespace AscNet.Logging +{ + public class Logger : ILogger + { + #region Members + + private readonly string _logFilePath = "log.log"; + private readonly string _loggerName = "DefaultLogger"; + private readonly LogLevel _logLevel = LogLevel.ALL; + private readonly LogLevel _fileLogLevel = LogLevel.ALL; + private bool _disposed; + private Type _loggerType; + + #endregion + + #region Instantiation + + public Logger(string logFilePath) + { + _logFilePath = logFilePath; + } + + public Logger(string logFilePath, LogLevel logLevel) : this(logFilePath) => _logLevel = logLevel; + + public Logger(Type loggerType, string logFilePath, LogLevel logLevel) : this(logFilePath, logLevel) + { + _loggerType = loggerType; + _loggerName = loggerType.Namespace.RemoveBefore('.'); + } + + public Logger(Type loggerType, LogLevel logLevel, LogLevel fileLogLevel) + { + _logLevel = logLevel; + _fileLogLevel = fileLogLevel; + _loggerType = loggerType; + _loggerName = loggerType.Name; + } + + public Logger(Type loggerType, string loggerName, LogLevel logLevel, LogLevel fileLogLevel) + { + _logLevel = logLevel; + _fileLogLevel = fileLogLevel; + _loggerType = loggerType; + _loggerName = loggerName; + } + + #endregion + + #region Methods + + public void Debug(string message, string memberName = "") + { + if (!string.IsNullOrWhiteSpace(message)) + { + Append(message, memberName, LogLevel.DEBUG); + } + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + public void Error(string message, Exception ex = null, string memberName = "") + { + if (!string.IsNullOrWhiteSpace(message)) + { + if (ex == null) + { + Append(message, memberName, LogLevel.ERROR); + } + else + { + Append(message + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace, memberName, + LogLevel.ERROR); + } + } + } + + public void Fatal(string message, Exception ex = null, string memberName = "") + { + if (!string.IsNullOrWhiteSpace(message)) + { + if (ex == null) + { + Append(message, memberName, LogLevel.FATAL); + } + else + { + Append(message + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace, memberName, + LogLevel.FATAL); + } + } + } + + public void Info(string message, string memberName = "") + { + if (!string.IsNullOrWhiteSpace(message)) + { + Append(message, memberName, LogLevel.INFO); + } + } + + public void Trace(string message, Exception ex) + { + // TODO + throw new NotImplementedException(); + } + + public void Warn(string message, Exception ex = null, string memberName = "") + { + if (!string.IsNullOrWhiteSpace(message)) + { + if (ex == null) + { + Append(message, memberName, LogLevel.WARN); + } + else + { + Append(message + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace, memberName, + LogLevel.WARN); + } + } + } + + protected virtual void Dispose(bool disposing) + { + if (!_disposed) + { + if (disposing) + { + ThreadSafeStreamWriter.Instance.Dispose(); + } + + _loggerType = null; + _disposed = true; + } + } + + private void Append(string message, string memberName, LogLevel logLevel) + { + if (!string.IsNullOrWhiteSpace(memberName)) + { + AppendToConsole($"[{memberName}][{_loggerName}]: {message}", logLevel); + AppendToFile($"[{memberName}][{_loggerName}]: {message}", logLevel); + } + else + { + AppendToConsole($"[{_loggerName}]: {message}", logLevel); + AppendToFile($"[{_loggerName}]: {message}", logLevel); + } + } + + private void AppendToConsole(string message, LogLevel logLevel) + { + if (logLevel <= _logLevel) + { + switch (logLevel) + { + case LogLevel.DEBUG: + Console.ForegroundColor = ConsoleColor.Magenta; + break; + + case LogLevel.INFO: + Console.ForegroundColor = ConsoleColor.Green; + break; + + case LogLevel.WARN: + Console.ForegroundColor = ConsoleColor.Yellow; + break; + + case LogLevel.ERROR: + Console.ForegroundColor = ConsoleColor.Red; + break; + + case LogLevel.FATAL: + Console.ForegroundColor = ConsoleColor.DarkRed; + break; + + default: + throw new ArgumentOutOfRangeException(nameof(logLevel), logLevel, null); + } + + Console.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}][{logLevel}]{message}"); + Console.ResetColor(); + } + } + + private void AppendToFile(string message, LogLevel logLevel) + { + if (logLevel <= _fileLogLevel) + { + ThreadSafeStreamWriter.Instance.AppendLine($"[{DateTime.Now:dd.MM.yyyy HH:mm:ss.fff}][{_loggerType.Namespace}][{_loggerName}][{logLevel}]{message}"); + } + } + + #endregion + } + +} diff --git a/AscNet.Logging/LoggerFactory.cs b/AscNet.Logging/LoggerFactory.cs new file mode 100644 index 00000000..fbc983b2 --- /dev/null +++ b/AscNet.Logging/LoggerFactory.cs @@ -0,0 +1,23 @@ +using System.Runtime.CompilerServices; + +namespace AscNet.Logging +{ + public static class LoggerFactory + { + public static ILogger Logger { get; set; } + + public static void Debug(string message, [CallerMemberName] string memberName = "") => Logger.Debug(message, memberName); + + public static void Error(string message, Exception ex = null, [CallerMemberName] string memberName = "") => Logger.Error(message, ex, memberName); + + public static void Fatal(string message, Exception ex = null, [CallerMemberName] string memberName = "") => Logger.Fatal(message, ex, memberName); + + public static void Info(string message, [CallerMemberName] string memberName = "") => Logger.Info(message, memberName); + + public static void Warn(string message, Exception ex = null, [CallerMemberName] string memberName = "") => Logger.Warn(message, ex, memberName); + + public static void Dispose() => Logger.Dispose(); + + public static void InitializeLogger(ILogger log) => Logger = log; + } +} diff --git a/AscNet.Logging/LoggingExtensions.cs b/AscNet.Logging/LoggingExtensions.cs new file mode 100644 index 00000000..68c4e560 --- /dev/null +++ b/AscNet.Logging/LoggingExtensions.cs @@ -0,0 +1,16 @@ +namespace AscNet.Logging +{ + public static class LoggingExtensions + { + public static string RemoveBefore(this string value, char character) + { + int index = value.LastIndexOf(character); + if (index > 0) + { + value = value[(index + 1)..]; + } + + return value; + } + } +} diff --git a/AscNet.Logging/ThreadSafeStreamWriter.cs b/AscNet.Logging/ThreadSafeStreamWriter.cs new file mode 100644 index 00000000..6dfc2dd0 --- /dev/null +++ b/AscNet.Logging/ThreadSafeStreamWriter.cs @@ -0,0 +1,60 @@ +namespace AscNet.Logging +{ + public class ThreadSafeStreamWriter : IDisposable + { + private static ThreadSafeStreamWriter? _instance; + + private static StreamWriter _writer; + + private bool disposedValue; + + // TODO: add support for configuring + private string _logFilePath = "log.log"; + + private object _lock = new object(); + + public ThreadSafeStreamWriter() + { + _writer = new StreamWriter(_logFilePath, true); +#if !RELEASE + _writer.AutoFlush = true; +#endif + } + + public static ThreadSafeStreamWriter Instance + { + get + { + return _instance ??= new ThreadSafeStreamWriter(); + } + } + + public void AppendLine(string line) + { + lock (_lock) + { + _writer.WriteLine(line); + } + } + + protected virtual void Dispose(bool disposing) + { + if (!disposedValue) + { + if (disposing) + { + _writer.Flush(); + _writer.Close(); + _writer.Dispose(); + } + disposedValue = true; + } + } + + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + } +} diff --git a/AscNet.SDKServer/AscNet.SDKServer.csproj b/AscNet.SDKServer/AscNet.SDKServer.csproj index f561c44a..a3754a80 100644 --- a/AscNet.SDKServer/AscNet.SDKServer.csproj +++ b/AscNet.SDKServer/AscNet.SDKServer.csproj @@ -13,6 +13,7 @@ + diff --git a/AscNet.SDKServer/Controllers/ConfigController.cs b/AscNet.SDKServer/Controllers/ConfigController.cs index 15fb1c65..5baa934d 100644 --- a/AscNet.SDKServer/Controllers/ConfigController.cs +++ b/AscNet.SDKServer/Controllers/ConfigController.cs @@ -45,7 +45,7 @@ namespace AscNet.SDKServer.Controllers remoteConfigs.AddConfig("PcPayCallbackList", $"{Common.Common.config.GameServer.Host}/api/XPay/KuroPayResult"); string serializedObject = TsvTool.SerializeObject(remoteConfigs); - SDKServer.c.Log(serializedObject); + SDKServer.log.Info(serializedObject); return serializedObject; }); @@ -61,13 +61,13 @@ namespace AscNet.SDKServer.Controllers Title = "NOTICE" }; string serializedObject = JsonConvert.SerializeObject(notice); - SDKServer.c.Log(serializedObject); + SDKServer.log.Info(serializedObject); return serializedObject; }); app.MapPost("/feedback", (HttpContext ctx) => { - SDKServer.c.Log("1"); + SDKServer.log.Info("1"); return "1"; }); @@ -81,7 +81,7 @@ namespace AscNet.SDKServer.Controllers Token = token }; string serializedObject = JsonConvert.SerializeObject(gate); - SDKServer.c.Log(serializedObject); + SDKServer.log.Info(serializedObject); return serializedObject; }); } diff --git a/AscNet.SDKServer/SDKServer.cs b/AscNet.SDKServer/SDKServer.cs index f8270c46..082481b1 100644 --- a/AscNet.SDKServer/SDKServer.cs +++ b/AscNet.SDKServer/SDKServer.cs @@ -1,8 +1,10 @@ +using AscNet.Logging; + namespace AscNet.SDKServer { public class SDKServer { - public static readonly Common.Util.Logger c = new(nameof(SDKServer), ConsoleColor.Green); + public static readonly Logger log = new(typeof(SDKServer), Logging.LogLevel.DEBUG, Logging.LogLevel.DEBUG); public static void Main(string[] args) { @@ -25,14 +27,14 @@ namespace AscNet.SDKServer { controller.GetMethod(nameof(IRegisterable.Register))!.Invoke(null, new object[] { app }); #if DEBUG - c.Log($"Registered HTTP controller '{controller.Name}'"); + log.Info($"Registered HTTP controller '{controller.Name}'"); #endif } app.UseMiddleware(); new Thread(() => app.Run()).Start(); - c.Log($"{nameof(SDKServer)} started in port {string.Join(", ", app.Urls.Select(x => x.Split(':').Last()))}!"); + log.Info($"{nameof(SDKServer)} started in port {string.Join(", ", app.Urls.Select(x => x.Split(':').Last()))}!"); } private class RequestLoggingMiddleware @@ -53,7 +55,7 @@ namespace AscNet.SDKServer } finally { - c.Log($"{context.Response.StatusCode} {context.Request.Method.ToUpper()} {context.Request.Path + context.Request.QueryString}"); + log.Info($"{context.Response.StatusCode} {context.Request.Method.ToUpper()} {context.Request.Path + context.Request.QueryString}"); } } } diff --git a/AscNet.sln b/AscNet.sln index a9705dbe..899b1c71 100644 --- a/AscNet.sln +++ b/AscNet.sln @@ -11,7 +11,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AscNet.SDKServer", "AscNet. EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AscNet.GameServer", "AscNet.GameServer\AscNet.GameServer.csproj", "{EB20C0CB-7CA1-459F-8410-7A27CC99F98C}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AscNet.Test", "AscNet.Test\AscNet.Test.csproj", "{DD4C8BB1-2422-4AA4-A12C-9B3A25873887}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AscNet.Test", "AscNet.Test\AscNet.Test.csproj", "{DD4C8BB1-2422-4AA4-A12C-9B3A25873887}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AscNet.Logging", "AscNet.Logging\AscNet.Logging.csproj", "{1DFF24B2-A3E1-4E5B-A1E4-3FE7022828EF}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -39,6 +41,10 @@ Global {DD4C8BB1-2422-4AA4-A12C-9B3A25873887}.Debug|Any CPU.Build.0 = Debug|Any CPU {DD4C8BB1-2422-4AA4-A12C-9B3A25873887}.Release|Any CPU.ActiveCfg = Release|Any CPU {DD4C8BB1-2422-4AA4-A12C-9B3A25873887}.Release|Any CPU.Build.0 = Release|Any CPU + {1DFF24B2-A3E1-4E5B-A1E4-3FE7022828EF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1DFF24B2-A3E1-4E5B-A1E4-3FE7022828EF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1DFF24B2-A3E1-4E5B-A1E4-3FE7022828EF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1DFF24B2-A3E1-4E5B-A1E4-3FE7022828EF}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/AscNet/Program.cs b/AscNet/Program.cs index de0d2f55..6f891887 100644 --- a/AscNet/Program.cs +++ b/AscNet/Program.cs @@ -1,5 +1,5 @@ -using AscNet.Common.Util; -using AscNet.GameServer; +using AscNet.GameServer; +using AscNet.Logging; namespace AscNet { @@ -7,15 +7,16 @@ namespace AscNet { static void Main(string[] args) { - Logger.c.Log("Starting..."); - + // TODO: Add loglevel parsing from appsettings file + LoggerFactory.InitializeLogger(new Logger(typeof(Program), LogLevel.DEBUG, LogLevel.DEBUG)); + LoggerFactory.Logger.Info("Starting..."); #if DEBUG if (Common.Common.config.VerboseLevel < Common.VerboseLevel.Debug) Common.Common.config.VerboseLevel = Common.VerboseLevel.Debug; #endif PacketFactory.LoadPacketHandlers(); - Task.Run(GameServer.Server.Instance.Start); + Task.Run(Server.Instance.Start); SDKServer.SDKServer.Main(args); } }