日志组件SeriLog
前言
上文说到Nlog日志框架,感觉它功能已经很强大,今天给大家介绍一个很不错的日志框架Serilog,根据我的了解,感觉它最大的优势是,结构化日志,它输出的日志是Json的格式,如果你使用的是Mongodb进行存储日志,那就是完美的结合,MongoDB也是文档式数据库,存储的格式很像JSON,也可以它是一个JSON文件,查询数据库快。不扯远了,还是讲讲Serilog的使用吧!
一、什么是Serilog?
Serilog 是 ASP.NET Core 的一个插件,可以简化日志记录。Serilog 有各种可用的接收器,例如,有纯文本、SQL 和 ElasticSearch 接收器等等。
二、如何安装Serilog?
Install-PackageSerilog.AspNetCore
三、如何配置Serilog?
3.1Program的配置如下
- Configuration:构建对象,读取appsettings.json的配置文件
- Log.Logger:读取Configuration中的日志配置信息,然后设置输出的级别、内容、位置等。
- UseSerilog(dispose:true):引入Serilog框架,dispose:true=>系统退出时,释放日志对象
publicclassProgram{publicstaticIConfigurationConfiguration{get;}=newConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())//设置基础路径.AddJsonFile("appsettings.json", optional:false, reloadOnChange:true)//添加配置文件.AddEnvironmentVariables()//添加环境变量.Build();publicstaticvoidMain(string[] args){Log.Logger=newLoggerConfiguration().ReadFrom.Configuration(Configuration).MinimumLevel.Debug().Enrich.FromLogContext()//使用Serilog.Context.LogContext中的属性丰富日志事件。.WriteTo.Console(newRenderedCompactJsonFormatter())//输出到控制台.WriteTo.File(formatter:newCompactJsonFormatter(),"logs\\test.txt",rollingInterval:RollingInterval.Day)//输出到文件.CreateLogger();//清除内置日志框架try{Log.Information("Starting web host");CreateHostBuilder(args).Build().Run();}catch(Exception ex){Log.Fatal(ex,"Host terminated unexpectedly");}finally{Log.CloseAndFlush();}}publicstaticIHostBuilderCreateHostBuilder(string[] args)=>Host.CreateDefaultBuilder(args)..ConfigureWebHostDefaults(webBuilder =>{
webBuilder.UseStartup<Startup>();}).UseSerilog(dispose:true);//引入第三方日志框架
3.2 appsettings.json配置
{"Logging":{"LogLevel":{"Default":"Information","Microsoft":"Warning","Microsoft.Hosting.Lifetime":"Information"}},"AllowedHosts":"*","Serilog":{"MinimumLevel":{"Default":"Information","Override":{"Microsoft":"Warning","System":"Information"}}}}
四、如何使用Serilog?
因为是替换了.net core中的内部日志框架,所有在使用的时候,和Logging日志框架一样使用,如下图所示
privatereadonlyILogger<WeatherForecastController> _logger;publicWeatherForecastController(ILogger<WeatherForecastController> logger){
_logger = logger;}[HttpGet]publicvoidGet(){
_logger.LogInformation("LogInformation"+Guid.NewGuid().ToString("N"));
_logger.LogDebug("LogDebug"+Guid.NewGuid().ToString("N"));
_logger.LogWarning("LogWarning"+Guid.NewGuid().ToString("N"));
_logger.LogError("LogError"+Guid.NewGuid().ToString("N"));}
五、展示效果
控制台显示

文件显示
六、扩展
6.1分级别显示
//存储日志文件的路径stringLogFilePath(stringLogEvent)=> $@"{AppContext.BaseDirectory}00_Logs\{LogEvent}\log.log";//存储日志文件的格式stringSerilogOutputTemplate="{NewLine}{NewLine}Date:{Timestamp:yyyy-MM-dd HH:mm:ss.fff}{NewLine}LogLevel:{Level}{NewLine}Message:{Message}{NewLine}{Exception}"+newstring('-',50);Log.Logger=newLoggerConfiguration().ReadFrom.Configuration(Configuration).MinimumLevel.Debug().Enrich.FromLogContext()//使用Serilog.Context.LogContext中的属性丰富日志事件。.WriteTo.Console(newRenderedCompactJsonFormatter()).WriteTo.Logger(lg=> lg.Filter.ByIncludingOnly(p=> p.Level==LogEventLevel.Debug).WriteTo.File(LogFilePath("Debug"),rollingInterval:RollingInterval.Day,outputTemplate:SerilogOutputTemplate)).WriteTo.Logger(lg=> lg.Filter.ByIncludingOnly(p=> p.Level==LogEventLevel.Information).WriteTo.File(LogFilePath("Information"),rollingInterval:RollingInterval.Day,outputTemplate:SerilogOutputTemplate)).WriteTo.Logger(lg=> lg.Filter.ByIncludingOnly(p=> p.Level==LogEventLevel.Warning).WriteTo.File(LogFilePath("Warning"),rollingInterval:RollingInterval.Day,outputTemplate:SerilogOutputTemplate)).WriteTo.Logger(lg=> lg.Filter.ByIncludingOnly(p=> p.Level==LogEventLevel.Error).WriteTo.File(LogFilePath("Error"),rollingInterval:RollingInterval.Day,outputTemplate:SerilogOutputTemplate)).WriteTo.Logger(lg=> lg.Filter.ByIncludingOnly(p=> p.Level==LogEventLevel.Fatal).WriteTo.File(LogFilePath("Fatal"),rollingInterval:RollingInterval.Day,outputTemplate:SerilogOutputTemplate)).CreateLogger();
效果如下:
文件级别分类:

日志格式输出:
6.2存储到数据库
Install-PackageSerilog.Sinks.MSSqlServer
修改配置
MSSqlServer(参数一,参数二,参数三,参数四)
- 数据库的地址
- 数据库中记录日志表的名称
- 是否自动创建表(Nlog是没有这个功能的)
- 记录日志最小级别
Log.Logger=newLoggerConfiguration().ReadFrom.Configuration(Configuration).MinimumLevel.Information().MinimumLevel.Override("Microsoft",LogEventLevel.Information).ReadFrom.Configuration(newConfigurationBuilder().AddJsonFile("appsettings.json").Build()).WriteTo.MSSqlServer(connecting,"logs", autoCreateSqlTable:true, restrictedToMinimumLevel:LogEventLevel.Information).CreateLogger();
效果如下:
6.2.1数据库中表字段
新增
第一步:创建列
var options =newColumnOptions();
options.AdditionalColumns=newCollection<SqlColumn>{newSqlColumn{DataType=SqlDbType.NVarChar,DataLength=-1,ColumnName="IP"},};
第二步:添加列
Enrich.WithProperty:添加属性
columnOptions: options:配置数据库的列
Log.Logger=newLoggerConfiguration().ReadFrom.Configuration(Configuration).MinimumLevel.Information().Enrich.WithProperty("IP","2.2.2.2").MinimumLevel.Override("Microsoft",LogEventLevel.Information).ReadFrom.Configuration(newConfigurationBuilder().AddJsonFile("appsettings.json").Build()).WriteTo.MSSqlServer(connecting,"logs", autoCreateSqlTable:true, columnOptions: options, restrictedToMinimumLevel:LogEventLevel.Information).CreateLogger();
第三步:运行即可
移除
第一步:记录移除列
StandardColumn:是框架默认提供数据库默认表,它的属性就是映射数据库的字段
var options =newColumnOptions();options.Store.Remove(StandardColumn.Properties);options.Store.Remove(StandardColumn.TimeStamp);
第二步:配置属性
Log.Logger=newLoggerConfiguration().ReadFrom.Configuration(Configuration).MinimumLevel.Information().MinimumLevel.Override("Microsoft",LogEventLevel.Information).ReadFrom.Configuration(newConfigurationBuilder().AddJsonFile("appsettings.json").Build()).WriteTo.MSSqlServer(connecting,"logs", autoCreateSqlTable:true, columnOptions: options, restrictedToMinimumLevel:LogEventLevel.Information).CreateLogger();
第三步:运行即可
注意事项:
当你创建了数据库的表之后,如果修改添加字段或修改字段,数据库存在的表是不会更新的,只能重新创建
6.3发送到邮箱
添加安装包:
Install-PackageSerilog.Sinks.Email
配置如下:
Log.Logger=newLoggerConfiguration().MinimumLevel.Information().MinimumLevel.Override("Microsoft",LogEventLevel.Information).ReadFrom.Configuration(newConfigurationBuilder().AddJsonFile("appsettings.json").Build()).WriteTo.Email(newEmailConnectionInfo(){Port=465,//端口EmailSubject="邮件日志测试",//邮件主题FromEmail="18827664385@163.com",//发件箱ToEmail="282840325@qq.com",//收件箱MailServer="smtp.163.com",//发件箱的邮箱服务NetworkCredentials=newNetworkCredential("18827664385@163.com","zc960810"),//发件人的邮箱和密码IsBodyHtml=true,//邮件是否是HTML格式EnableSsl=true//使用启用SSL端口}).CreateLogger();
效果如下
总结
Serilog的扩展插件还有很多,我在这只是简单的介绍Serilog输出到控制台、输出到数据库、输出到邮件,其实它还有其他,我就不一一介绍,感兴趣的可以自己的去尝试。到此我已经讲了三篇.net core中的日志框架了,分别是:
- .net core中的那些常用的日志框架(Logging篇)
- .net core中的那些常用的日志框架(NLog篇)
- .net core中的那些常用的日志框架(Serilog篇)
从其中,我学习了很多,了解了结构化日志,了解日志输出的多种方式,控制台、文件、数据库、邮箱,比以前只会写txt要进步不少。
三篇博客的源码地址

浙公网安备 33010602011771号