Serilog 自定義 Enricher 來增加記錄的信息

Serilog 自定義 Enricher 來增加記錄的信息

Intro

Serilog 是 .net 裏面非常不錯的記錄日誌的庫,結構化日誌記錄,而且配置起來很方便,自定義擴展也很方便

Serilog is a diagnostic logging library for .NET applications. It is easy to set up, has a clean API, and runs on all recent .NET platforms. While it's useful even in the simplest applications, Serilog's support for structured logging shines when instrumenting complex, distributed, and asynchronous applications and systems.

Serilog是.NET應用程序的診斷日誌庫。 它易於設置,具有乾淨的API,並可在所有最新的.NET平臺上運行。 雖然它在最簡單的應用程序中也很有用,但Serilog對結構化日誌記錄的支持在處理複雜,分佈式和異步應用程序和系統時仍然很有用。

之前一直使用 log4net 來記錄日誌,使用 serilog 之後覺得 serilog 比 log4net 好用很多,很靈活,配置方式多種多樣,支持許多不同的輸出,詳細參考 https://github.com/serilog/serilog/wiki/Provided-Sinks

最近打算把之前基於 log4net 的日誌遷移到 serilog, 我自定義的一套 logging 組件也增加了對 Serilog 的支持。 https://www.nuget.org/packages/WeihanLi.Common.Logging.Serilog 現在還沒有發佈正式版,不過我已經在用了,在等 serilog 發佈 2.9.0 正式版,因爲 2.8.x 版本的 netstandard2.0 版本還依賴了一個 System.Collections.NonGeneric,這個依賴只在 netstandard1.3 的時候需要引用,netstandard2.0 已經不需要了,詳細信息可以參考PR: https://github.com/serilog/serilog/pull/1342

自定義 Enricher

自定義 Enricher 很簡單很方便,來看示例:

public class RequestInfoEnricher : ILogEventEnricher
{
    public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
    {
        var httpContext = DependencyResolver.Current.GetService<IHttpContextAccessor>()?.HttpContext;
        if (null != httpContext)
        {
            logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("RequestIP", httpContext.GetUserIP()));
            logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("RequestPath", httpContext.Request.Path));

            logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("Referer", httpContext.Request.Headers["Referer"]));
        }
    }
}

這個示例會嘗試獲取請求的 RequestIP/RequestPath/Referer 寫入到日誌中,這樣可以方便我們的請求統計

爲了方便使用我們可以再定義一個擴展方法:

public static class EnricherExtensions
{
    public static LoggerConfiguration WithRequestInfo(this LoggerEnrichmentConfiguration enrich)
    {
        if (enrich == null)
            throw new ArgumentNullException(nameof(enrich));

        return enrich.With<RequestInfoEnricher>();
    }
}

配置 Serilog :

loggingConfig
    .WriteTo.Elasticsearch(Configuration.GetConnectionString("ElasticSearch"), $"logstash-{ApplicationHelper.ApplicationName.ToLower()}")
    .Enrich.FromLogContext()
    .Enrich.WithRequestInfo()

完整代碼示例參考:https://github.com/WeihanLi/ActivityReservation/blob/e68ab090f8b7d660f0a043889f4353551c8b3dc2/ActivityReservation/SerilogEnrichers/RequestInfoEnricher.cs

驗證

來看一下我們使用了我們自定義的 RequestInfoEnricher 之後的日誌效果

可以看到我們自定義的 Enricher 中添加的請求信息已經寫到日誌裏了,而且我們可以根據 RequestIP 去篩選,爲了方便查詢 IP 統計,在 kibana 中加了一個可視化面板,效果如下圖所示:

Reference

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章