在 .NET 中使用 Serilog 进行结构化日志记录的最佳方法

作者:微信公众号:【架构师老卢】
9-17 18:3
233

Serilog 是一个功能强大、灵活的 .NET 日志记录框架,它支持结构化日志记录,从而可以轻松地在日志中记录丰富的数据。与仅写入纯文本的传统日志记录方法不同,结构化日志记录以 JSON 等结构化格式捕获上下文信息(例如,变量值),以便轻松查询和分析。

在 .NET 中为 Structured Logging 设置 Serilog 的步骤

1. 安装 Serilog 和所需的软件包

首先,安装 Serilog 和必要的接收器(将存储日志的位置)。最常见的接收器是控制台接收器,但 Serilog 支持许多其他接收器,例如文件、数据库和云日志记录平台。

Visual Studio 中,在 NuGet 包管理器dotnet CLI 中运行以下命令:

Install-Package Serilog  
Install-Package Serilog.AspNetCore  
Install-Package Serilog.Sinks.Console

对于文件日志记录:

Install-Package Serilog.Sinks.File

2. 配置 Serilog

您可以在应用程序启动时配置 Serilog,通常在 ASP.NET Core 或 Console 应用程序的文件中。以下是基本配置的示例,包括控制台和文件接收器。Program.cs

示例:基本配置Program.cs

using Serilog;  
  
public class Program  
{  
    public static void Main(string[] args)  
    {  
        // Configure Serilog  
        Log.Logger = new LoggerConfiguration()  
            .MinimumLevel.Debug()  // Set the minimum log level  
            .WriteTo.Console()     // Log to console  
            .WriteTo.File("logs/log.txt", rollingInterval: RollingInterval.Day)  // Log to file with daily rolling  
            .CreateLogger();  
  
        try  
        {  
            Log.Information("Starting the application...");  
            CreateHostBuilder(args).Build().Run();  
        }  
        catch (Exception ex)  
        {  
            Log.Fatal(ex, "Application startup failed");  
        }  
        finally  
        {  
            Log.CloseAndFlush();  // Ensure any pending logs are written before the app shuts down  
        }  
    }  
  
    public static IHostBuilder CreateHostBuilder(string[] args) =>  
        Host.CreateDefaultBuilder(args)  
            .UseSerilog()  // Tell the app to use Serilog for logging  
            .ConfigureWebHostDefaults(webBuilder =>  
            {  
                webBuilder.UseStartup<Startup>();  
            });  
}

在此示例中:

  • 控制台日志记录配置为将日志输出到控制台。
  • 文件日志记录配置为通过每日日志文件轮换将日志写入。logs/log.txt

3. 使用 Serilog 进行结构化日志记录

Serilog 擅长结构化日志记录。您可以使用以结构化方式捕获的参数进行记录,而不是记录普通消息,从而更轻松地在 SeqElasticsearchSplunk 等日志记录平台中进行查询。

示例:结构化日志记录

Log.Information("Processing order {@Order} for customer {CustomerId}", order, customerId);
  • 该语法在日志中序列化对象,包括其所有属性。{@Order}order
  • {CustomerId}捕获 作为结构化属性。customerId

然后,可以在外部日志记录平台中搜索、筛选和分析这些结构化数据。

4. 使用上下文信息丰富日志条目

您可以使用其他上下文(如计算机名称、应用程序版本或自定义属性)来丰富日志事件。

示例:使用上下文数据扩充日志

Log.Logger = new LoggerConfiguration()  
    .Enrich.WithMachineName()  // Add machine name to all log events  
    .Enrich.WithProperty("Application", "MyApp")  // Add a custom property to all logs  
    .WriteTo.Console()  
    .WriteTo.File("logs/log.txt", rollingInterval: RollingInterval.Day)  
    .CreateLogger();

在这里,每个日志条目都将包括计算机名称和一个名为 的自定义属性,其值为 .Application"MyApp"

5. 登录 ASP.NET Core 中间件

在 ASP.NET Core 中,您可以将 Serilog 注入请求管道,并记录 HTTP 请求/响应、用户信息和其他上下文数据。

示例:在 ASP.NET Core 中添加 Serilog 请求日志记录

在 中,配置请求日志记录中间件:Program.cs

public static IHostBuilder CreateHostBuilder(string[] args) =>  
    Host.CreateDefaultBuilder(args)  
        .UseSerilog((context, services, configuration) => configuration  
            .ReadFrom.Configuration(context.Configuration)  
            .Enrich.FromLogContext()  
            .WriteTo.Console())  
        .ConfigureWebHostDefaults(webBuilder =>  
        {  
            webBuilder.UseStartup<Startup>();  
        });

在文件中,添加 Serilog 的请求日志记录中间件:Startup.cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
{  
    app.UseSerilogRequestLogging();  // Logs HTTP requests and responses  
    // Other middleware like app.UseRouting(), etc.  
}

现在,Serilog 将自动记录有关每个 HTTP 请求和响应的详细信息,包括状态代码、持续时间和终端节点。

6. 记录到外部服务(Seq、Elasticsearch 等)

Serilog 支持通过专用接收器记录到 SeqElasticsearchSplunkAzure 等外部服务。

示例:Log to Seq

Seq 是一种流行的结构化日志查看器。安装 Seq sink:

Install-Package Serilog.Sinks.Seq

将日志记录配置为 Seq:

Log.Logger = new LoggerConfiguration()  
    .WriteTo.Seq("https://localhost:5341")  // Use the Seq server's address  
 .CreateLogger();

7. 控制日志级别

Serilog 提供对日志记录级别(例如,DebugInformationWarningErrorFatal)的精细控制。您可以全局设置最小级别,也可以按接收器设置最小级别。

示例:设置日志级别

Log.Logger = new LoggerConfiguration()  
    .MinimumLevel.Debug()  // Set the global minimum level to Debug  
    .WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Information)  // Only log Information and above to the console  
    .WriteTo.File("logs/log.txt", rollingInterval: RollingInterval.Day)  
    .CreateLogger();

在此示例中:

  • 全局最小日志级别设置为 Debug,但控制台接收器仅记录 Information 及以上版本。

8. 使用 Serilog 过滤器

您还可以根据条件筛选日志条目,确保仅记录相关信息。

示例:按条件筛选日志

Log.Logger = new LoggerConfiguration()  
    .MinimumLevel.Debug()  
    .WriteTo.Console()  
    .WriteTo.File("logs/log.txt", rollingInterval: RollingInterval.Day)  
    .Filter.ByExcluding(logEvent => logEvent.Properties.ContainsKey("Ignore"))  // Exclude logs with "Ignore" property  
    .CreateLogger();

9. 使用 Serilog 处理异常

Serilog 可以结构化地捕获异常详细信息,从而更轻松地调试问题。

示例:使用 Serilog 记录异常

try  
{  
    throw new InvalidOperationException("Something went wrong!");  
}  
catch (Exception ex)  
{  
    Log.Error(ex, "An error occurred while processing the request");  
}

Serilog 将记录异常详细信息,包括堆栈跟踪和您提供的任何其他上下文。

10. 关闭和刷新日志

当应用程序关闭时,请始终通过调用以下命令确保正确刷新日志:Log.CloseAndFlush()

try  
{  
    // Application logic  
}  
finally  
{  
    Log.CloseAndFlush();  
}

这可确保在应用程序退出之前将所有日志写入其目标。

Serilog 提供了一种灵活、强大的 .NET 日志记录方法,尤其是它对结构化日志记录的支持,它允许您在日志中捕获更有意义、可查询的数据。通过配置不同的接收器、筛选日志级别以及使用上下文信息丰富日志,您可以确保您的 .NET 应用程序生成全面且有用的日志,以帮助监控、调试和分析应用程序行为。

相关留言评论
昵称:
邮箱:
阅读排行