Serilog 是 .net 裏面很是不錯的記錄日誌的庫,結構化日誌記錄,並且配置起來很方便,自定義擴展也很方便html
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.git
Serilog是.NET應用程序的診斷日誌庫。 它易於設置,具備乾淨的API,並可在全部最新的.NET平臺上運行。 雖然它在最簡單的應用程序中也頗有用,但Serilog對結構化日誌記錄的支持在處理複雜,分佈式和異步應用程序和系統時仍然頗有用。github
以前一直使用 log4net 來記錄日誌,使用 serilog 以後以爲 serilog 比 log4net 好用不少,很靈活,配置方式多種多樣,支持許多不一樣的輸出,詳細參考 https://github.com/serilog/serilog/wiki/Provided-Sinksapp
最近打算把以前基於 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 很簡單很方便,來看示例:async
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 寫入到日誌中,這樣能夠方便咱們的請求統計分佈式
爲了方便使用咱們能夠再定義一個擴展方法:ide
public static class EnricherExtensions { public static LoggerConfiguration WithRequestInfo(this LoggerEnrichmentConfiguration enrich) { if (enrich == null) throw new ArgumentNullException(nameof(enrich)); return enrich.With<RequestInfoEnricher>(); } }
配置 Serilog :this
loggingConfig .WriteTo.Elasticsearch(Configuration.GetConnectionString("ElasticSearch"), $"logstash-{ApplicationHelper.ApplicationName.ToLower()}") .Enrich.FromLogContext() .Enrich.WithRequestInfo()
來看一下咱們使用了咱們自定義的 RequestInfoEnricher
以後的日誌效果
能夠看到咱們自定義的 Enricher 中添加的請求信息已經寫到日誌裏了,並且咱們能夠根據 RequestIP 去篩選,爲了方便查詢 IP 統計,在 kibana 中加了一個可視化面板,效果以下圖所示:
原文出處:https://www.cnblogs.com/weihanli/p/custom-serilog-enricher-to-record-more-info.html