using DispenserCommon.LogUtils; using DispenserCore.Service; using Serilog; using Serilog.Core; using Serilog.Events; using Serilog.Exceptions; namespace DispenserCommon.LogConfig; /// /// 日志配置类 /// public class LogConfiguration { private static LogParamsService _logParamsService = new(); /// /// 获取日志配置对象 /// /// public static Logger GetLogger() { var logParams = _logParamsService.GetLogParams(); // 日志输出目录 var basePath = logParams!.Path ?? AppDomain.CurrentDomain.BaseDirectory; // 适配最小日志级别 Enum.TryParse(logParams.Level, true, out LogEventLevel miniLevel); return new LoggerConfiguration() #if DEBUG // 测试环境的话,输出debug级别 .MinimumLevel.Debug() #else // 其他环境输出info 级别 .MinimumLevel.Information() #endif .MinimumLevel.Override("Microsoft", miniLevel) .Enrich.FromLogContext() .Enrich.WithExceptionDetails() .WriteTo.Logger( l => l.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Debug) .WriteTo.File( Path.Combine(basePath, "logs", "debug", "debug-.log"), rollingInterval: RollingInterval.Hour, retainedFileCountLimit: 24 ) ) .WriteTo.Logger( l => l.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Information) .WriteTo.File( Path.Combine(basePath, "logs", "info", "info-.log"), rollingInterval: RollingInterval.Hour, retainedFileCountLimit: 72 ) ) .WriteTo.Logger( l => l.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Warning) .WriteTo.File( Path.Combine(basePath, "logs", "warning", "warning-.log"), rollingInterval: RollingInterval.Day, retainedFileCountLimit: 30 ) ) .WriteTo.Logger( l => l.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Error) .WriteTo.File( Path.Combine(basePath, "logs", "error", "error-.log"), rollingInterval: RollingInterval.Day, retainedFileCountLimit: 90 ) ) // 测试环境同步输出到控制台 .WriteTo.Console() .WriteTo.Sink(new DispenserLogSink()) .CreateLogger(); } }