当前位置:网站首页>asp.net Using serilog in core and customizing enrich

asp.net Using serilog in core and customizing enrich

2020-11-09 22:37:29 Irving the procedural ape

Serilog brief introduction

With many others .NET Like the library ,Serilog Also provided are the documents , Basic diagnostic logging of console, etc . It's easy to set up , Have a simple API, And can be in the latest .NET Porting between platforms .

Use and configure 、 Customize Enricher

because serilog There is a lot of configuration information , Avoid hard coding , We are appsetting.jgon Create a new one in the peer directory serilogsetting.json Log profile for , The simple content is as follows :

{	"Serilog": {		"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.Seq" ],		"MinimumLevel": {			"Default": "Information",			"Override": {				"System": "Error",				"Microsoft": "Error"			}		},		"WriteTo": [			{				"Name": "Console"			},			{				"Name": "Seq",				"Args": {					"serverUrl": "http://localhost:5341/",					"apiKey": "L2on8gpgjose5uldhdch"				}			}		]	}}

Please refer to :serilog wiki file

Next , stay Program.cs Add a method to , Initialize these configurations , And then rewrite the code that builds the host :

public class Program{ public static int Main(string[] args) {  var logConfig = GetLogConfig();  Log.Logger = new LoggerConfiguration()      .ReadFrom.Configuration(logConfig)      .Enrich.FormLogContext()      .CreateLogger();   try  {   // web host  initialization    var host = BuildWebHost(args);   host.Run();   return 0;  }  catch(Exception e)  {   Log.Fatal(ex, "{ApplicationContext}  There is an error :{messsage} !", AppName, ex.Message);   return 1;  }  finally  {   Log.CloseAndFlush();  } }  /// <summary> ///  Read log configuration  /// </summary> /// <returns></returns> private static IConfiguration GetLogConfig() {  var builder = new ConfigurationBuilder()      .AddJsonFile("serilogsetting.json", optional: false, reloadOnChange: true);  return builder.Build();  }}

then , Add a custom Enircher, Used to record HttpContext, The data of ._enrichAction Then you can customize , Default record ip, Request path , Request method , And return response code :

public class HttpContextEnricher:ILogEventEnricher{ private readonly IServiceProvider _serviceProvider; private readonly Action<LogEvent, ILogEventPropertyFactory, HttpContext> _enrichAction;  public HttpContextEnricher(IServiceProvider serviceProvider) : this(serviceProvider, null) {}   public HttpContextEnricher(IServiceProvider serviceProvider, Action<LogEvent, ILogEventPropertyFactory, HttpContext> enrichAction) {  _serviceProvider = serviceProvider;  if (enrichAction == null)  {   _enrichAction = (logEvent, pr.........

版权声明
本文为[Irving the procedural ape]所创,转载请带上原文链接,感谢