7

如何在 ASP.Net Core 中使用 Serilog

 3 years ago
source link: http://developer.51cto.com/art/202102/644267.htm
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

ZBnIjiI.jpg!mobile

本文转载自微信公众号「码农读书」,作者码农读书 。转载本文请联系码农读书公众号。

记录日志的一个作用就是方便对应用程序进行跟踪和排错调查,在实际应用上都是引入 日志框架,但如果你的 日志文件 包含非结构化的数据,那么查询起来将是一个噩梦,所以需要在记录日志的时候采用结构化方式。

将日志结构化可以更容易的查询和分析,做法就是在写入的时候定义好数据的格式,这种格式包括:xml,json,或者你希望转成的任何结构。

Serilog 是一个第三方,开源的结构化日志框架,它的高层封装可以让开发者更容易的将日志记录到 console,file 和你能想到的各种 存储系统,这篇文章我们将会讨论如何在 ASP.Net Core 中使用 Serilog。

安装 Serilog

使用 Visual Studio 新建 ASP.Net Core 项目,接下来从 NuGet 上拉几个包,具体如下:

  • Serilog

这个包提供了对基本的结构化日志的功能支持。

  • Serilog.AspNetCore

这个包提供了 Serilog 对 AspNetCore 的支持。

  • Serilog.Settings.Configuration

这个包打通了 Serilog 和 Configuration ,这样你就可以直接从 appsettings.json 中读取配置。

  • Serilog.Sinks.Console

Console接收器顾名思义就是将 Serilog 的日志输出到 Console。

  • Serilog.Sinks.RollingFile

实现了对 滚动文件 的支持。

使用 Serilog Sink

Serilog 利用 sink 特性将日志送到不同的地方,比如:text文件,数据库,甚至是 ElasticSearch 中,换句话说,sink 特性可以把日志送到它该去的地方,当所有的 nuget 包都安装好了之后,下面的代码片段展示了如何将日志送到 console 中。

public HomeController(ILogger<HomeController> logger) 
        { 
            using (var logConfig = new LoggerConfiguration().WriteTo.Console().CreateLogger()) 
            { 
                logConfig.Information("This is a test data."); 
            }; 
 
            _logger = logger; 
        } 

eiaMRb2.png!mobile

值得注意的是,Serilog 支持多个日志级别,如:verbose, debug, information, warning, error 和 fatal。

有时候为了调试目的,将日志送到 Console 是一个好办法,但将程序部署到生产之后,更通用的做法就是将日志记录到文件中,这样方便在生产上实时查看并做一定程度的日志分析,刚好这里的 Serilog.Sink.RollingFile 支持对滚动文件的支持,下面的代码片段展示了如何通过编程的方式将日志送到文件中。

public HomeController() 
        { 
            var logger = new LoggerConfiguration().MinimumLevel.Debug().WriteTo 
                                                  .RollingFile(@"e:\log.txt", retainedFileCountLimit: 7) 
                                                  .CreateLogger(); 
 
            for (int i = 0; i < byte.MaxValue; i++) 
            { 
                logger.Information($"log {i}"); 
            } 
        } 

UfEnMrb.png!mobile

使用 Serilog 替换原生的 Logger

在 ASP.NET Core 中内置了 Logger 组件,这一节中我们一起看看如何使用 Serilog 将其进行替换,在 Program.Main 方法中使用如下代码:

public class Program 
   { 
       public static void Main(string[] args) 
       { 
           Log.Logger = new LoggerConfiguration() 
            .MinimumLevel.Debug() 
            .MinimumLevel.Override("Microsoft", LogEventLevel.Information) 
            .Enrich.FromLogContext() 
            .WriteTo.Console() 
            .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) 
             .UseSerilog() 
               .ConfigureWebHostDefaults(webBuilder => 
               { 
                   webBuilder.UseStartup<Startup>(); 
               }); 
   } 

从上面的代码中可以看到,我在 CreateHostBuilder 中使用了 UseSerilog() 扩展方法来启动 Serilog,这样就做好了 Serilog 的替换工作,接下来可以在 Controller 中通过依赖注入的方式获取 logger 实例,如下代码所示:

public IActionResult Index() 
        { 
            logger.LogInformation("hello world"); 
 
            return View(); 
        } 

m2IFJjz.png!mobile

日志是一个应用程序不可或缺的一部分,所以选择一款 灵活 + 简单 的日志框架就显得特别重要了,Serilog 提供了低配置和易使用的特性让我们方便的将日志送到各个地方。

译文链接:https://www.infoworld.com/article/3314985/how-to-use-serilog-in-aspnet-core.html


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK