张炳连 發表於 2020-10-15 10:45:00

.net core中的那些常用的日志框架(Serilog篇)

<h3 id="前言">前言</h3>
<blockquote>
<p>上文说到Nlog日志框架,感觉它功能已经很强大,今天给大家介绍一个很不错的日志框架Serilog,根据我的了解,感觉它最大的优势是,结构化日志,它输出的日志是Json的格式,如果你使用的是Mongodb进行存储日志,那就是完美的结合,MongoDB也是文档式数据库,存储的格式很像JSON,也可以它是一个JSON文件,查询数据库快。不扯远了,还是讲讲Serilog的使用吧!</p>
</blockquote>
<h3 id="一什么是serilog">一、什么是Serilog?</h3>
<blockquote>
<p>Serilog 是 ASP.NET Core 的一个插件,可以简化日志记录。Serilog 有各种可用的接收器,例如,有纯文本、SQL 和 ElasticSearch 接收器等等。</p>
</blockquote>
<h3 id="二如何安装serilog">二、如何安装Serilog?</h3>
<pre><code>Install-Package Serilog.AspNetCore
</code></pre>
<h3 id="三如何配置serilog">三、如何配置Serilog?</h3>
<h4 id="31program的配置如下">3.1Program的配置如下</h4>
<ul>
<li>Configuration:构建对象,读取appsettings.json的配置文件</li>
<li>Log.Logger:读取Configuration中的日志配置信息,然后设置输出的级别、内容、位置等。</li>
<li>UseSerilog(dispose:true):引入Serilog框架,dispose:true=&gt;系统退出时,释放日志对象</li>
</ul>
<pre><code>   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) =&gt;
            Host.CreateDefaultBuilder(args).
                .ConfigureWebHostDefaults(webBuilder =&gt;{
                  webBuilder.UseStartup&lt;Startup&gt;();
                }).UseSerilog(dispose:true);//引入第三方日志框架
   
</code></pre>
<h4 id="32-appsettingsjson配置">3.2 appsettings.json配置</h4>
<pre><code>{
"Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
},
"AllowedHosts": "*",
"Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
      "Microsoft": "Warning",
      "System": "Information"
      }
    }
}
}

</code></pre>
<h3 id="四如何使用serilog">四、如何使用Serilog?</h3>
<blockquote>
<p>因为是替换了.net core中的内部日志框架,所有在使用的时候,和Logging日志框架一样使用,如下图所示</p>
</blockquote>
<pre><code>      private readonly ILogger&lt;WeatherForecastController&gt; _logger;

      public WeatherForecastController(ILogger&lt;WeatherForecastController&gt; logger)
      {
            _logger = logger;
      }

      
      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"));
      }
</code></pre>
<h3 id="五展示效果">五、展示效果</h3>
<p><strong>控制台显示</strong><br>
<img src="https://img2020.cnblogs.com/blog/1400941/202010/1400941-20201014092052857-388318905.png" alt="" loading="lazy"><br>
<strong>文件显示</strong><br>
<img src="https://img2020.cnblogs.com/blog/1400941/202010/1400941-20201014092147785-1709330383.png" alt="" loading="lazy"></p>
<h3 id="六扩展">六、扩展</h3>
<h4 id="61分级别显示">6.1分级别显示</h4>
<pre><code>//存储日志文件的路径
string LogFilePath(string LogEvent) =&gt; $@"{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 =&gt; lg.Filter.ByIncludingOnly(p =&gt; p.Level == LogEventLevel.Debug).WriteTo.File(LogFilePath("Debug"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
                .WriteTo.Logger(lg =&gt; lg.Filter.ByIncludingOnly(p =&gt; p.Level == LogEventLevel.Information).WriteTo.File(LogFilePath("Information"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
                .WriteTo.Logger(lg =&gt; lg.Filter.ByIncludingOnly(p =&gt; p.Level == LogEventLevel.Warning).WriteTo.File(LogFilePath("Warning"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
                .WriteTo.Logger(lg =&gt; lg.Filter.ByIncludingOnly(p =&gt; p.Level == LogEventLevel.Error).WriteTo.File(LogFilePath("Error"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
                .WriteTo.Logger(lg =&gt; lg.Filter.ByIncludingOnly(p =&gt; p.Level == LogEventLevel.Fatal).WriteTo.File(LogFilePath("Fatal"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
                .CreateLogger();
</code></pre>
<p><strong>效果如下:</strong><br>
文件级别分类:<br>
<img src="https://img2020.cnblogs.com/blog/1400941/202010/1400941-20201014093034675-1903623090.png" alt="" loading="lazy"><br>
日志格式输出:<br>
<img src="https://img2020.cnblogs.com/blog/1400941/202010/1400941-20201014093127438-1685482585.png" alt="" loading="lazy"></p>
<h4 id="62存储到数据库">6.2存储到数据库</h4>
<pre><code>Install-Package Serilog.Sinks.MSSqlServer
</code></pre>
<p><strong>修改配置</strong><br>
MSSqlServer(参数一,参数二,参数三,参数四)</p>
<ul>
<li>数据库的地址</li>
<li>数据库中记录日志表的名称</li>
<li>是否自动创建表(Nlog是没有这个功能的)</li>
<li>记录日志最小级别</li>
</ul>
<pre><code>
            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();
</code></pre>
<p><strong>效果如下:</strong><br>
<img src="https://img2020.cnblogs.com/blog/1400941/202010/1400941-20201015093105399-1335401250.png" alt="" loading="lazy"></p>
<h5 id="621数据库中表字段">6.2.1数据库中表字段</h5>
<p><strong>新增</strong><br>
第一步:创建列</p>
<pre><code>var options = new ColumnOptions();
            options.AdditionalColumns = new Collection&lt;SqlColumn&gt;
                {
                  new SqlColumn { DataType = SqlDbType.NVarChar, DataLength =-1, ColumnName = "IP" },
                };
</code></pre>
<p>第二步:添加列<br>
Enrich.WithProperty:添加属性<br>
columnOptions: options:配置数据库的列</p>
<pre><code>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();
</code></pre>
<p>第三步:运行即可<br>
<img src="https://img2020.cnblogs.com/blog/1400941/202010/1400941-20201015094816897-227026538.png" alt="" loading="lazy"></p>
<p><strong>移除</strong><br>
第一步:记录移除列<br>
<strong>StandardColumn:</strong>是框架默认提供数据库默认表,它的属性就是映射数据库的字段</p>
<pre><code>var options = new ColumnOptions();
            options.Store.Remove(StandardColumn.Properties);
            options.Store.Remove(StandardColumn.TimeStamp);
</code></pre>
<p>第二步:配置属性</p>
<pre><code>
            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();
</code></pre>
<p>第三步:运行即可<br>
<img src="https://img2020.cnblogs.com/blog/1400941/202010/1400941-20201015095551076-446794013.png" alt="" loading="lazy"></p>
<p><strong>注意事项:</strong></p>
<blockquote>
<p>当你创建了数据库的表之后,如果修改添加字段或修改字段,数据库存在的表是不会更新的,只能重新创建</p>
</blockquote>
<h4 id="63发送到邮箱">6.3发送到邮箱</h4>
<p><strong>添加安装包:</strong></p>
<pre><code>Install-Package Serilog.Sinks.Email
</code></pre>
<p><strong>配置如下:</strong></p>
<pre><code> 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();
</code></pre>
<p><strong>效果如下</strong><br>
<img src="https://img2020.cnblogs.com/blog/1400941/202010/1400941-20201015103536289-1433705743.png" alt="" loading="lazy"></p>
<h3 id="总结">总结</h3>
<blockquote>
<p>Serilog的扩展插件还有很多,我在这只是简单的介绍Serilog输出到控制台、输出到数据库、输出到邮件,其实它还有其他,我就不一一介绍,感兴趣的可以自己的去尝试。到此我已经讲了三篇.net core中的日志框架了,分别是:</p>
</blockquote>
<ul>
<li>.net core中的那些常用的日志框架(Logging篇)</li>
<li>.net core中的那些常用的日志框架(NLog篇)</li>
<li>.net core中的那些常用的日志框架(Serilog篇)<br>
从其中,我学习了很多,了解了结构化日志,了解日志输出的多种方式,控制台、文件、数据库、邮箱,比以前只会写txt要进步不少。<br>
三篇博客的源码地址</li>
</ul>


</div>
<div id="MySignature" role="contentinfo">
    <h1 style="font-size: 18px;color:black" class="box">如果你觉得本文对你有帮助,请点击“推荐”,谢谢。</h1><br/>
<div>作者:喜欢吃鱼的青年</div>
<div>出处:https://home.cnblogs.com/u/2828sea/</div>
<div>本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。 </div><br><br>
来源:https://www.cnblogs.com/2828sea/p/13812869.html
頁: [1]
查看完整版本: .net core中的那些常用的日志框架(Serilog篇)