diff --git a/backend/Magic.Web.Core/Startup.cs b/backend/Magic.Web.Core/Startup.cs index 185c8bd7408b30b41523bb9a9eb2e2ed05acf36c..8e99b2bd68017d36ba1893f0ae6438fde341b74f 100644 --- a/backend/Magic.Web.Core/Startup.cs +++ b/backend/Magic.Web.Core/Startup.cs @@ -16,6 +16,7 @@ using System.Text.Json; using System.Text.Json.Serialization; using System.Text.Unicode; using Yitter.IdGenerator; +using Furion.Templates; namespace Magic.Web.Core; @@ -97,49 +98,26 @@ public class Startup : AppStartup builder.AddSubscriber(); }); - // 日志记录 + // 日志记录 + // 错误级别日志归类 + // 每天创建一个日志文件 services.AddLogging(builder => { - // 错误级别日志归类 + + builder.AddFile("logs/error/{0:yyyyMMdd}_.log", options => { - options.WriteFilter = (logMsg) => - { - return logMsg.LogLevel == LogLevel.Error; - }; - options.FileNameRule = fileName => - { - return string.Format(fileName, DateTime.UtcNow); - }; - options.FileSizeLimitBytes = 500 * 1024; + SetLogOptions(options, LogLevel.Error); }); - // 每天创建一个日志文件 builder.AddFile("logs/info/{0:yyyyMMdd}_.log", options => { - options.WriteFilter = (logMsg) => - { - return logMsg.LogLevel == LogLevel.Information; - }; - options.FileNameRule = fileName => - { - return string.Format(fileName, DateTime.UtcNow); - }; - options.FileSizeLimitBytes = 500 * 1024; + SetLogOptions(options, LogLevel.Information); }); builder.AddFile("logs/warn/{0:yyyyMMdd}_.log", options => { - options.WriteFilter = (logMsg) => - { - return logMsg.LogLevel == LogLevel.Warning; - }; - options.FileNameRule = fileName => - { - return string.Format(fileName, DateTime.UtcNow); - }; - options.FileSizeLimitBytes = 500 * 1024; + SetLogOptions(options, LogLevel.Warning); }); }); - } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) @@ -180,4 +158,30 @@ public class Startup : AppStartup }); } + + private void SetLogOptions(FileLoggerOptions options, LogLevel logLevel) + { + options.WriteFilter = (logMsg) => + { + return logMsg.LogLevel == logLevel; + }; + options.FileNameRule = fileName => + { + return string.Format(fileName, DateTime.UtcNow); + }; + options.FileSizeLimitBytes = 500 * 1024; + options.MessageFormat = (logMsg) => + { + List msg = new List() { + $"##日志时间## {DateTime.Now.ToString("O")}", + $"##日志等级## {logLevel}", + $"##日志内容## {logMsg.Message}", + }; + if (!string.IsNullOrEmpty(logMsg.Exception?.ToString())) msg.Add($"##异常信息## {logMsg.Exception}"); + + // 生成模板字符串 + var template = TP.Wrapper($"{logMsg.LogName}", "", msg.ToArray()); + return template; + }; + } }