using Senparc.CO2NET; using Serilog; using Serilog.Events; using System.Text; var builder = WebApplication.CreateBuilder(args).Inject(); var Configuration = builder.Configuration; var env = builder.Environment; var services = builder.Services; #region 日志注入,将serilog设置为日志记录提供程序 builder.Host.UseSerilog((context, configuration) => { var seqpath = Configuration.GetSection("CustomSetting:LogUrl").Value; var filepath = builder.Configuration.GetSection("CustomSetting:logfile").Value; string date = DateTime.Now.ToString("yyyy-MM-dd");//按时间创建文件夹 string outputTemplate = "{NewLine}【{Level:u3}】{Timestamp:yyyy-MM-dd HH:mm:ss.fff}" + "{NewLine}#Msg#{Message:lj}" + "{NewLine}#Pro #{Properties:j}" + "{NewLine}#Exc#{Exception}" + new string('-', 50);//输出模板 var config = configuration.ReadFrom.Configuration(context.Configuration).Enrich.FromLogContext(); if (env.IsDevelopment()) { config .WriteTo.Console(outputTemplate: outputTemplate) //2.1仅输出 LogEventLevel.Debug 类型 .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(evt => evt.Level == LogEventLevel.Debug)//筛选过滤 .WriteTo.File($"{filepath}/{date}/{LogEventLevel.Debug}.log", outputTemplate: outputTemplate, rollingInterval: RollingInterval.Day,//日志按日保存,这样会在文件名称后自动加上日期后缀 encoding: Encoding.UTF8 // 文件字符编码 ) ) //2.2仅输出 LogEventLevel.Error 类型 .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(evt => evt.Level == LogEventLevel.Error)//筛选过滤 .WriteTo.File($"{filepath}/{date}/{LogEventLevel.Error}.log", outputTemplate: outputTemplate, rollingInterval: RollingInterval.Day,//日志按日保存,这样会在文件名称后自动加上日期后缀 encoding: Encoding.UTF8 // 文件字符编码 ) ) .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(evt => evt.Level == LogEventLevel.Information)//筛选过滤 .WriteTo.File($"{filepath}/{date}/{LogEventLevel.Information}.log", outputTemplate: outputTemplate, rollingInterval: RollingInterval.Day,//日志按日保存,这样会在文件名称后自动加上日期后缀 encoding: Encoding.UTF8 // 文件字符编码 ) ) .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(evt => evt.Level == LogEventLevel.Fatal)//筛选过滤 .WriteTo.File($"{filepath}/{date}/{LogEventLevel.Fatal}.log", outputTemplate: outputTemplate, rollingInterval: RollingInterval.Day,//日志按日保存,这样会在文件名称后自动加上日期后缀 encoding: Encoding.UTF8 // 文件字符编码 ) ) .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(evt => evt.Level == LogEventLevel.Warning)//筛选过滤 .WriteTo.File($"{filepath}/{date}/{LogEventLevel.Warning}.log", outputTemplate: outputTemplate, rollingInterval: RollingInterval.Day,//日志按日保存,这样会在文件名称后自动加上日期后缀 encoding: Encoding.UTF8 // 文件字符编码 ) ); } else { config.WriteTo.Seq(seqpath); } }); #endregion //引入微信服务 builder.Host.UseServiceProviderFactory(new SenparcServiceProviderFactory()); var app = builder.Build(); app.Run();