using Serilog; using Serilog.Events; using System.Text; IHost host = Host.CreateDefaultBuilder(args) .UseWindowsService() .Inject() //日志注入,将serilog设置为日志记录提供程序 .UseSerilog((context, config) => { var env = context.HostingEnvironment; var configuration = context.Configuration; var filepath = configuration["logfile"]; 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);//输出模板 if (env.IsDevelopment()) { //2.1仅输出 LogEventLevel.Debug 类型 config.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("http://localhost:5341/"); } }) .ConfigureServices((hostContext, services) => { var configuration = hostContext.Configuration; //添加CAP支持 services.AddCap(x => { x.DefaultGroupName = "cap.queue.ybdevice.napi"; //配置rabbitmq支持 string port = configuration["RabbitmqSetting:Port"]; int p = Convert.ToInt32(port); x.UseRabbitMQ(opt => { opt.HostName = configuration["RabbitmqSetting:HostName"]; //配置ip地址 opt.Port = p;//配置端口 opt.UserName = configuration["RabbitmqSetting:UserName"];//配置用户名 opt.Password = configuration["RabbitmqSetting:Password"];//配置Miami }); //配置sqlserver支持 x.UseSqlServer(configuration["RabbitmqSetting:DBConnection"]); }); }) .Build(); await host.RunAsync();