将Feature/XP.Common和Feature/XP.Hardware分支合并至Develop/XP.forHardwareAndCommon,完善XPapp注册和相关硬件类库通用类库功能。
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
using System;
|
||||
using Serilog;
|
||||
using Serilog.Events;
|
||||
using XP.Common.Configs;
|
||||
using XP.Common.Logging.ViewModels;
|
||||
|
||||
namespace XP.Common.Logging
|
||||
{
|
||||
/// <summary>
|
||||
/// Serilog全局初始化工具(应用启动时调用一次)
|
||||
/// </summary>
|
||||
public static class SerilogInitializer
|
||||
{
|
||||
/// <summary>
|
||||
/// 初始化Serilog日志
|
||||
/// </summary>
|
||||
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<LogEventLevel>(config.MinimumLevel, true, out var minLevel))
|
||||
minLevel = LogEventLevel.Information;
|
||||
|
||||
// 解析文件分割规则
|
||||
if (!Enum.TryParse<RollingInterval>(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();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user