FunGame-Server/FunGame.WebAPI/Services/CustomConsoleFormatter.cs
milimoe ccf75528cb
添加日志级别;添加匿名服务器监听;模组线程安全改进 (#41)
* 添加日志级别;添加匿名服务器监听(不要求客户端安装)

* 修复不同时间多客户端连接游戏模组时可能产生的线程安全问题

* 更新了匿名服务器令牌确认
2025-01-17 18:59:44 +08:00

40 lines
1.7 KiB
C#

using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Logging.Console;
namespace Milimoe.FunGame.WebAPI.Services
{
public class CustomConsoleFormatter() : ConsoleFormatter("CustomFormatter")
{
public override void Write<TState>(in LogEntry<TState> logEntry, IExternalScopeProvider? scopeProvider, TextWriter textWriter)
{
string message = logEntry.Formatter(logEntry.State, logEntry.Exception);
string level = logEntry.LogLevel.ToString()[..1].ToUpper();
string category = logEntry.Category.Split('.')[^1];
string colorLevel = GetColorCode(logEntry.LogLevel);
DateTime now = DateTime.Now;
string timestamp = now.AddMilliseconds(-now.Millisecond).ToString();
if ((int)logEntry.LogLevel >= (int)Server.Others.Config.LogLevelValue)
{
textWriter.Write("\r");
textWriter.WriteLine($"{colorLevel}{timestamp} {level}/[{category}] {message}");
}
textWriter.Write("\x1b[0m\r> ");
}
private static string GetColorCode(LogLevel logLevel)
{
return logLevel switch
{
LogLevel.Trace => "\x1b[37m", // 灰色 ConsoleColor.Gray
LogLevel.Debug => "\x1b[34m", // 蓝色 ConsoleColor.Blue
LogLevel.Information => "\x1b[32m", // 绿色 ConsoleColor.Green
LogLevel.Warning => "\x1b[33m", // 黄色 ConsoleColor.Yellow
LogLevel.Error => "\x1b[31m", // 红色 ConsoleColor.Red
LogLevel.Critical => "\x1b[31m", // 红色 ConsoleColor.Red
_ => "\x1b[0m" // 重置颜色
};
}
}
}