C# 使用Serilog日志框架
Serilog是一款配置方便,使用灵活的日志框架,使用方法如下:
1、日志输出到控制台,需要使用Nuget安装Serilog和Serilog.Sinks.Console两个包
// 初始化日志的共享实例 Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .Enrich.FromLogContext() .WriteTo.Console() .CreateLogger(); // 写入日志 Log.Information("Info");
2、日志输出到文件,需要安装Serilog.Sinks.File包
// 初始化日志的共享实例 Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .Enrich.FromLogContext() .WriteTo.File("logs/app.log", rollingInterval: RollingInterval.Day, // 每天一个日志文件 shared: true // 允许其他进程共享日志文件 ).CreateLogger(); // 写入日志 Log.Information("Info");
3、可以通过配置,让不同日志级别输出到不同的日志文件
// 初始化日志的共享实例 Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .Enrich.FromLogContext() // 调试日志 .WriteTo.Logger(x => x .Filter.ByIncludingOnly(e => e.Level == Serilog.Events.LogEventLevel.Debug) .WriteTo.File("logs/debug.log", rollingInterval: RollingInterval.Day, shared: true) // 错误日志 ).WriteTo.Logger(x => x .Filter.ByIncludingOnly(e => e.Level == Serilog.Events.LogEventLevel.Error) .WriteTo.File("logs/error.log", rollingInterval: RollingInterval.Day, shared: true) // 应用日志 ).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(); // 写入日志到 app.log Log.Information("Info"); // 写入日志到 debug.log Log.Debug("Debug"); // 写入日志到 error.log Log.Error("Error");
4、写入日志到SqlServer
// 写入数据库的配置 var sinkOpts = new MSSqlServerSinkOptions(); sinkOpts.TableName = "logs"; // 日志表名 sinkOpts.AutoCreateSqlTable = true; // 自动创建表 // 列配置 var columnOpts = new ColumnOptions(); columnOpts.Store.Remove(StandardColumn.Exception); // 去掉异常列 columnOpts.Store.Remove(StandardColumn.Properties); // 去掉属性列 columnOpts.Exception.DataLength = 2048; // 指定列的长度 columnOpts.TimeStamp.NonClusteredIndex = true; // 去掉时间戳的聚集索引 // 初始化日志的共享实例 Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .Enrich.FromLogContext() .WriteTo.MSSqlServer( connectionString: ConfigurationManager.ConnectionStrings["Default"].ConnectionString, sinkOptions: sinkOpts, columnOptions: columnOpts ).CreateLogger(); // 写入日志 Log.Information("Info");
执行代码后,发现日志表并没有添加到数据库,也没有任何异常信息,我们可以添加以下代码调试Serilog
Serilog.Debugging.SelfLog.Enable(msg =>
{
Debug.Print(msg);
Debugger.Break();
});
获取到如下的错误信息:
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 - 证书链是由不受信任的颁发机构颁发的。)
需要在连接字符串添加信任服务器证书的配置:TrustServerCertificate=True;
就能在SqlServer中创建日志表并写入日志。