上文说到Nlog日志框架,感觉它功能已经很强大,今天给大家介绍一个很不错的日志框架Serilog,根据我的了解,感觉它最大的优势是,结构化日志,它输出的日志是Json的格式,如果你使用的是Mongodb进行存储日志,那就是完美的结合,MongoDB也是文档式数据库,存储的格式很像JSON,也可以它是一个JSON文件,查询数据库快。不扯远了,还是讲讲Serilog的使用吧!

Serilog 是 ASP.NET Core 的一个插件,可以简化日志记录。Serilog 有各种可用的接收器,例如,有纯文本、SQL 和 ElasticSearch 接收器等等。

  1. Install-Package Serilog.AspNetCore
  • Configuration:构建对象,读取appsettings.json的配置文件
  • Log.Logger:读取Configuration中的日志配置信息,然后设置输出的级别、内容、位置等。
  • UseSerilog(dispose:true):引入Serilog框架,dispose:true=>系统退出时,释放日志对象
  1. public class Program
  2. {
  3. public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
  4. .SetBasePath(Directory.GetCurrentDirectory())//设置基础路径
  5. .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)//添加配置文件
  6. .AddEnvironmentVariables()//添加环境变量
  7. .Build();
  8. public static void Main(string[] args)
  9. {
  10. Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(Configuration)
  11. .MinimumLevel.Debug()
  12. .Enrich.FromLogContext()//使用Serilog.Context.LogContext中的属性丰富日志事件。
  13. .WriteTo.Console(new RenderedCompactJsonFormatter())//输出到控制台
  14. .WriteTo.File(formatter:new CompactJsonFormatter(),"logs\\test.txt",rollingInterval:RollingInterval.Day)//输出到文件
  15. .CreateLogger();//清除内置日志框架
  16. try
  17. {
  18. Log.Information("Starting web host");
  19. CreateHostBuilder(args).Build().Run();
  20. }
  21. catch (Exception ex)
  22. {
  23. Log.Fatal(ex,"Host terminated unexpectedly");
  24. }
  25. finally
  26. {
  27. Log.CloseAndFlush();
  28. }
  29. }
  30. public static IHostBuilder CreateHostBuilder(string[] args) =>
  31. Host.CreateDefaultBuilder(args).
  32. .ConfigureWebHostDefaults(webBuilder =>{
  33. webBuilder.UseStartup<Startup>();
  34. }).UseSerilog(dispose:true);//引入第三方日志框架
  1. {
  2. "Logging": {
  3. "LogLevel": {
  4. "Default": "Information",
  5. "Microsoft": "Warning",
  6. "Microsoft.Hosting.Lifetime": "Information"
  7. }
  8. },
  9. "AllowedHosts": "*",
  10. "Serilog": {
  11. "MinimumLevel": {
  12. "Default": "Information",
  13. "Override": {
  14. "Microsoft": "Warning",
  15. "System": "Information"
  16. }
  17. }
  18. }
  19. }

因为是替换了.net core中的内部日志框架,所有在使用的时候,和Logging日志框架一样使用,如下图所示

  1. private readonly ILogger<WeatherForecastController> _logger;
  2. public WeatherForecastController(ILogger<WeatherForecastController> logger)
  3. {
  4. _logger = logger;
  5. }
  6. [HttpGet]
  7. public void Get()
  8. {
  9. _logger.LogInformation("LogInformation" + Guid.NewGuid().ToString("N"));
  10. _logger.LogDebug("LogDebug" + Guid.NewGuid().ToString("N"));
  11. _logger.LogWarning("LogWarning" + Guid.NewGuid().ToString("N"));
  12. _logger.LogError("LogError" + Guid.NewGuid().ToString("N"));
  13. }

控制台显示

文件显示

  1. //存储日志文件的路径
  2. string LogFilePath(string LogEvent) => $@"{AppContext.BaseDirectory}00_Logs\{LogEvent}\log.log";
  3. //存储日志文件的格式
  4. string SerilogOutputTemplate = "{NewLine}{NewLine}Date:{Timestamp:yyyy-MM-dd HH:mm:ss.fff}{NewLine}LogLevel:{Level}{NewLine}Message:{Message}{NewLine}{Exception}" + new string('-', 50);
  5. Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(Configuration)
  6. .MinimumLevel.Debug()
  7. .Enrich.FromLogContext()//使用Serilog.Context.LogContext中的属性丰富日志事件。
  8. .WriteTo.Console(new RenderedCompactJsonFormatter())
  9. .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Debug).WriteTo.File(LogFilePath("Debug"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
  10. .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Information).WriteTo.File(LogFilePath("Information"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
  11. .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Warning).WriteTo.File(LogFilePath("Warning"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
  12. .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Error).WriteTo.File(LogFilePath("Error"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
  13. .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Fatal).WriteTo.File(LogFilePath("Fatal"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
  14. .CreateLogger();

效果如下:
文件级别分类:

日志格式输出:

  1. Install-Package Serilog.Sinks.MSSqlServer

修改配置
MSSqlServer(参数一,参数二,参数三,参数四)

  • 数据库的地址
  • 数据库中记录日志表的名称
  • 是否自动创建表(Nlog是没有这个功能的)
  • 记录日志最小级别
  1. Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(Configuration)
  2. .MinimumLevel.Information()
  3. .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
  4. .ReadFrom.Configuration(new ConfigurationBuilder()
  5. .AddJsonFile("appsettings.json")
  6. .Build())
  7. .WriteTo.MSSqlServer(connecting, "logs", autoCreateSqlTable: true, restrictedToMinimumLevel: LogEventLevel.Information)
  8. .CreateLogger();

效果如下:

新增
第一步:创建列

  1. var options = new ColumnOptions();
  2. options.AdditionalColumns = new Collection<SqlColumn>
  3. {
  4. new SqlColumn { DataType = SqlDbType.NVarChar, DataLength =-1, ColumnName = "IP" },
  5. };

第二步:添加列
Enrich.WithProperty:添加属性
columnOptions: options:配置数据库的列

  1. Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(Configuration)
  2. .MinimumLevel.Information()
  3. .Enrich.WithProperty("IP", "2.2.2.2")
  4. .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
  5. .ReadFrom.Configuration(new ConfigurationBuilder()
  6. .AddJsonFile("appsettings.json")
  7. .Build())
  8. .WriteTo.MSSqlServer(connecting, "logs", autoCreateSqlTable: true, columnOptions: options, restrictedToMinimumLevel: LogEventLevel.Information)
  9. .CreateLogger();

第三步:运行即可

移除
第一步:记录移除列
StandardColumn:是框架默认提供数据库默认表,它的属性就是映射数据库的字段

  1. var options = new ColumnOptions();
  2. options.Store.Remove(StandardColumn.Properties);
  3. options.Store.Remove(StandardColumn.TimeStamp);

第二步:配置属性

  1. Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(Configuration)
  2. .MinimumLevel.Information()
  3. .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
  4. .ReadFrom.Configuration(new ConfigurationBuilder()
  5. .AddJsonFile("appsettings.json")
  6. .Build())
  7. .WriteTo.MSSqlServer(connecting, "logs", autoCreateSqlTable: true, columnOptions: options, restrictedToMinimumLevel: LogEventLevel.Information)
  8. .CreateLogger();

第三步:运行即可

注意事项:

当你创建了数据库的表之后,如果修改添加字段或修改字段,数据库存在的表是不会更新的,只能重新创建

添加安装包:

  1. Install-Package Serilog.Sinks.Email

配置如下:

  1. Log.Logger = new LoggerConfiguration()
  2. .MinimumLevel.Information()
  3. .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
  4. .ReadFrom.Configuration(new ConfigurationBuilder()
  5. .AddJsonFile("appsettings.json")
  6. .Build())
  7. .WriteTo.Email(new EmailConnectionInfo() {
  8. Port= 465,//端口
  9. EmailSubject="邮件日志测试",//邮件主题
  10. FromEmail= "18827664385@163.com",//发件箱
  11. ToEmail="282840325@qq.com",//收件箱
  12. MailServer= "smtp.163.com",//发件箱的邮箱服务
  13. NetworkCredentials = new NetworkCredential("18827664385@163.com", "zc960810"),//发件人的邮箱和密码
  14. IsBodyHtml =true,//邮件是否是HTML格式
  15. EnableSsl=true//使用启用SSL端口
  16. })
  17. .CreateLogger();

效果如下

Serilog的扩展插件还有很多,我在这只是简单的介绍Serilog输出到控制台、输出到数据库、输出到邮件,其实它还有其他,我就不一一介绍,感兴趣的可以自己的去尝试。到此我已经讲了三篇.net core中的日志框架了,分别是:

版权声明:本文为2828sea原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/2828sea/p/13812869.html