Serilog 自定义 Enricher 来增加记录的信息
Serilog 自定義 Enricher 來增加記錄的信息
Intro
Serilog 是 .net 里面非常不錯的記錄日志的庫,結(jié)構(gòu)化日志記錄,而且配置起來很方便,自定義擴(kuò)展也很方便
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應(yīng)用程序的診斷日志庫。它易于設(shè)置,具有干凈的API,并可在所有最新的.NET平臺上運行。雖然它在最簡單的應(yīng)用程序中也很有用,但Serilog對結(jié)構(gòu)化日志記錄的支持在處理復(fù)雜,分布式和異步應(yīng)用程序和系統(tǒng)時仍然很有用。
之前一直使用 log4net 來記錄日志,使用 serilog 之后覺得 serilog 比 log4net 好用很多,很靈活,配置方式多種多樣,支持許多不同的輸出,詳細(xì)參考 https://github.com/serilog/serilog/wiki/Provided-Sinks
最近打算把之前基于 log4net 的日志遷移到 serilog, 我自定義的一套 logging 組件也增加了對 Serilog 的支持。https://www.nuget.org/packages/WeihanLi.Common.Logging.Serilog 現(xiàn)在還沒有發(fā)布正式版,不過我已經(jīng)在用了,在等 serilog 發(fā)布 2.9.0 正式版,因為 2.8.x 版本的 netstandard2.0 版本還依賴了一個 System.Collections.NonGeneric,這個依賴只在 netstandard1.3 的時候需要引用,netstandard2.0 已經(jīng)不需要了,詳細(xì)信息可以參考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 寫入到日志中,這樣可以方便我們的請求統(tǒng)計
為了方便使用我們可以再定義一個擴(kuò)展方法:
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 中添加的請求信息已經(jīng)寫到日志里了,而且我們可以根據(jù) RequestIP 去篩選,為了方便查詢 IP 統(tǒng)計,在 kibana 中加了一個可視化面板,效果如下圖所示:
Reference
https://github.com/serilog/serilog
https://github.com/WeihanLi/ActivityReservation/blob/e68ab090f8b7d660f0a043889f4353551c8b3dc2/ActivityReservation
總結(jié)
以上是生活随笔為你收集整理的Serilog 自定义 Enricher 来增加记录的信息的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VS Code 1.37 发布!多达数十
- 下一篇: 做「容量预估」可没有true和false