zoukankan      html  css  js  c++  java
  • .net core中的那些常用的日志框架(Serilog篇)

    前言

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

    一、什么是Serilog?

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

    二、如何安装Serilog?

    Install-Package Serilog.AspNetCore
    

    三、如何配置Serilog?

    3.1Program的配置如下

    • Configuration:构建对象,读取appsettings.json的配置文件
    • Log.Logger:读取Configuration中的日志配置信息,然后设置输出的级别、内容、位置等。
    • UseSerilog(dispose:true):引入Serilog框架,dispose:true=>系统退出时,释放日志对象
       public class Program
        {
            public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())//设置基础路径
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)//添加配置文件
                .AddEnvironmentVariables()//添加环境变量
                .Build();
    
            public static void Main(string[] args)
            {
                Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(Configuration)
                    .MinimumLevel.Debug()
                    .Enrich.FromLogContext()//使用Serilog.Context.LogContext中的属性丰富日志事件。
                    .WriteTo.Console(new RenderedCompactJsonFormatter())//输出到控制台
                    .WriteTo.File(formatter:new CompactJsonFormatter(),"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();
                }
            }
            public static IHostBuilder CreateHostBuilder(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日志框架一样使用,如下图所示

            private readonly ILogger<WeatherForecastController> _logger;
    
            public WeatherForecastController(ILogger<WeatherForecastController> logger)
            {
                _logger = logger;
            }
    
            [HttpGet]
            public void Get()
            {
                _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分级别显示

      //存储日志文件的路径
      string LogFilePath(string LogEvent) => $@"{AppContext.BaseDirectory}00_Logs{LogEvent}log.log";
      //存储日志文件的格式
      string SerilogOutputTemplate = "{NewLine}{NewLine}Date:{Timestamp:yyyy-MM-dd HH:mm:ss.fff}{NewLine}LogLevel:{Level}{NewLine}Message:{Message}{NewLine}{Exception}" + new string('-', 50);
    
       Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(Configuration)
                    .MinimumLevel.Debug()
                    .Enrich.FromLogContext()//使用Serilog.Context.LogContext中的属性丰富日志事件。
                    .WriteTo.Console(new RenderedCompactJsonFormatter())
                    .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-Package Serilog.Sinks.MSSqlServer
    

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

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

    效果如下:

    6.2.1数据库中表字段

    新增
    第一步:创建列

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

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

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

    第三步:运行即可

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

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

    第二步:配置属性

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

    第三步:运行即可

    注意事项:

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

    6.3发送到邮箱

    添加安装包:

    Install-Package Serilog.Sinks.Email
    

    配置如下:

     Log.Logger = new LoggerConfiguration()
                    .MinimumLevel.Information()
                    .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                    .ReadFrom.Configuration(new ConfigurationBuilder()
                    .AddJsonFile("appsettings.json")
                    .Build())
                    .WriteTo.Email(new EmailConnectionInfo() { 
                        Port= 465,//端口
                        EmailSubject="邮件日志测试",//邮件主题
                        FromEmail= "123**@163.com",//发件箱
                        ToEmail="********@qq.com",//收件箱
                        MailServer= "smtp.163.com",//发件箱的邮箱服务
                        NetworkCredentials = new NetworkCredential("123**@163.com", "*****"),//发件人的邮箱和密码
                        IsBodyHtml =true,//邮件是否是HTML格式
                        EnableSsl=true//使用启用SSL端口
                    })
                    .CreateLogger();
    

    效果如下

    总结

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

  • 相关阅读:
    网页制作
    线性表
    学习进度表
    我是一只IT小小鸟读后感
    Git分支管理(一)
    家庭因你而不同
    Mysql循环insert数据
    IDEA,右边栏不显示maven解决方案
    Linux定时清理日志脚本
    JAVA的夸平台特性的优势——工厂在线生产信息采集项目
  • 原文地址:https://www.cnblogs.com/2828sea/p/13812869.html
Copyright © 2011-2022 走看看