using System; using Serilog; using Serilog.Events; using XP.Common.Configs; using XP.Common.Logging.ViewModels; namespace XP.Common.Logging { /// /// Serilog全局初始化工具(应用启动时调用一次) /// public static class SerilogInitializer { /// /// 初始化Serilog日志 /// public static void Initialize(SerilogConfig config) { if (config == null) throw new ArgumentNullException(nameof(config)); // 确保日志目录存在 if (!System.IO.Directory.Exists(config.LogPath)) System.IO.Directory.CreateDirectory(config.LogPath); // 解析日志级别 if (!Enum.TryParse(config.MinimumLevel, true, out var minLevel)) minLevel = LogEventLevel.Information; // 解析文件分割规则 if (!Enum.TryParse(config.RollingInterval, true, out var rollingInterval)) rollingInterval = RollingInterval.Day; // 构建Serilog配置 var loggerConfig = new LoggerConfiguration() .MinimumLevel.Is(minLevel) .Enrich.FromLogContext() // 启用上下文(模块标记) .WriteTo.File( path: System.IO.Path.Combine(config.LogPath, "app_.log"), // 最终文件名:app_20260307.log rollingInterval: rollingInterval, fileSizeLimitBytes: config.FileSizeLimitMB * 1024 * 1024, retainedFileCountLimit: config.RetainedFileCountLimit, outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] [{SourceContext}] {Message:lj}{NewLine}{Exception}" ); // 调试环境输出到控制台 if (config.EnableConsole) loggerConfig.WriteTo.Console( outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] [{SourceContext}] {Message:lj}{NewLine}{Exception}"); // 注册实时日志查看器 Sink(接收所有级别日志)| Register real-time log viewer sink (receive all levels) loggerConfig.WriteTo.Sink(RealTimeLogSink.Instance, Serilog.Events.LogEventLevel.Verbose); // 全局初始化 Log.Logger = loggerConfig.CreateLogger(); } } }