.Net Core项目中整合Serilog
引入Serilog.AspNetCore
Serilog.Settings.Configuration
Serilog.Sinks.MSSqlServer 日志写入数据库需要引入
1.创建Serilog.json配置文件
{ "Serilog": { // 日志输出级别 "MinimumLevel": { "Default": "Debug", "Override": { // 日志调用类命名空间如果以 Microsoft 开头,覆盖日志输出最小级别为 Information "Microsoft": "Information", "System": "Warning", //简化日志 "Microsoft.AspNetCore": "Warning" } }, "WriteTo": [ { "Name": "Console", "Args": { "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console", "outputTemplate": "时间:{Timestamp: HH:mm:ss.fff} 事件等级:{Level} 详细信息:{Message}{NewLine}{Exception}" } }, { "Name": "File", "Args": { "path": "logs/log.txt", "rollingInterval": "Day", // "创建文件的类别,可以是分钟,小时,天,月,年": null, "retainedFileCountLimit": 60, // "--设置日志文件个数最大值,默认31,意思就是只保留最近的31个日志文件", "等于null时永远保留文件": null, //"outputTemplate": "{Timestamp:HH:mm:ss} [{Level:u3}] ({Application}/{MachineName}/{ThreadId}) {Message}{NewLine}{Exception}", "fileSizeLimitBytes": 3145728, //设置单个文件大小为3M 默认1G "rollOnFileSizeLimit": true //超过文件大小后创建新的 } }, { "Name": "MSSqlServer", "Args": { "connectionString": "data Source=.;Initial Catalog=I-KeyBox;User ID=sa;Password=123", //表名 "tableName": "Logs", //自动创建表 "autoCreateSqlTable": true, //记录日志级别 "restrictedToMinimumLevel": "Information" } } ] } }
2.
public static int Main(string[] args) { Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .WriteTo.Console() .ReadFrom.Configuration(new ConfigurationBuilder() .AddJsonFile("Serilog.json") .Build()) .CreateLogger(); try { Log.Information("Starting web host"); CreateHostBuilder(args).Build().Run(); return 0; } catch (Exception ex) { Log.Fatal(ex, "Host terminated unexpectedly"); return 1; } finally { Log.CloseAndFlush(); } }
3.
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }) .UseSerilog(); // <-- Add this line;将UseSerilog()添加到CreateHostBuilder()中的通用主机。
4.
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseSerilogRequestLogging(); // <-- Add this line 添加中间件
输出日志