C# 使用Serilog日志框架
Serilog是一款配置方便,使用靈活的日志框架,使用方法如下:
1、日志輸出到控制臺(tái),需要使用Nuget安裝Serilog和Serilog.Sinks.Console兩個(gè)包
// 初始化日志的共享實(shí)例 Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .Enrich.FromLogContext() .WriteTo.Console() .CreateLogger(); // 寫(xiě)入日志 Log.Information("Info");
2、日志輸出到文件,需要安裝Serilog.Sinks.File包
// 初始化日志的共享實(shí)例 Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .Enrich.FromLogContext() .WriteTo.File("logs/app.log", rollingInterval: RollingInterval.Day, // 每天一個(gè)日志文件 shared: true // 允許其他進(jìn)程共享日志文件 ).CreateLogger(); // 寫(xiě)入日志 Log.Information("Info");
3、可以通過(guò)配置,讓不同日志級(jí)別輸出到不同的日志文件
// 初始化日志的共享實(shí)例 Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .Enrich.FromLogContext() // 調(diào)試日志 .WriteTo.Logger(x => x .Filter.ByIncludingOnly(e => e.Level == Serilog.Events.LogEventLevel.Debug) .WriteTo.File("logs/debug.log", rollingInterval: RollingInterval.Day, shared: true) // 錯(cuò)誤日志 ).WriteTo.Logger(x => x .Filter.ByIncludingOnly(e => e.Level == Serilog.Events.LogEventLevel.Error) .WriteTo.File("logs/error.log", rollingInterval: RollingInterval.Day, shared: true) // 應(yīng)用日志 ).WriteTo.Logger(x => x .Filter.ByIncludingOnly(e => e.Level != Serilog.Events.LogEventLevel.Debug && e.Level != Serilog.Events.LogEventLevel.Error) .WriteTo.File("logs/app.log", rollingInterval: RollingInterval.Day, shared: true) ).CreateLogger(); // 寫(xiě)入日志到 app.log Log.Information("Info"); // 寫(xiě)入日志到 debug.log Log.Debug("Debug"); // 寫(xiě)入日志到 error.log Log.Error("Error");
4、寫(xiě)入日志到SqlServer
// 寫(xiě)入數(shù)據(jù)庫(kù)的配置 var sinkOpts = new MSSqlServerSinkOptions(); sinkOpts.TableName = "logs"; // 日志表名 sinkOpts.AutoCreateSqlTable = true; // 自動(dòng)創(chuàng)建表 // 列配置 var columnOpts = new ColumnOptions(); columnOpts.Store.Remove(StandardColumn.Exception); // 去掉異常列 columnOpts.Store.Remove(StandardColumn.Properties); // 去掉屬性列 columnOpts.Exception.DataLength = 2048; // 指定列的長(zhǎng)度 columnOpts.TimeStamp.NonClusteredIndex = true; // 去掉時(shí)間戳的聚集索引 // 初始化日志的共享實(shí)例 Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .Enrich.FromLogContext() .WriteTo.MSSqlServer( connectionString: ConfigurationManager.ConnectionStrings["Default"].ConnectionString, sinkOptions: sinkOpts, columnOptions: columnOpts ).CreateLogger(); // 寫(xiě)入日志 Log.Information("Info");
執(zhí)行代碼后,發(fā)現(xiàn)日志表并沒(méi)有添加到數(shù)據(jù)庫(kù),也沒(méi)有任何異常信息,我們可以添加以下代碼調(diào)試Serilog
Serilog.Debugging.SelfLog.Enable(msg =>
{
Debug.Print(msg);
Debugger.Break();
});
獲取到如下的錯(cuò)誤信息:
2022-11-26T09:34:53.6107406Z Unable to write 1 log events to the database due to following error: A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - 證書(shū)鏈?zhǔn)怯刹皇苄湃蔚念C發(fā)機(jī)構(gòu)頒發(fā)的。)
需要在連接字符串添加信任服務(wù)器證書(shū)的配置:TrustServerCertificate=True;
就能在SqlServer中創(chuàng)建日志表并寫(xiě)入日志。

浙公網(wǎng)安備 33010602011771號(hào)