SeriLog Setting's Tips 2022

目錄
Installation
-
Use NuGet to search for and install the
Serilog.AspNetCore
package -
Add configuration in
Program.cs
1 2 3 4 5 6 7
Log.Logger = new LoggerConfiguration() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .MinimumLevel.Override("System", LogEventLevel.Warning)//Use MinimumLevel to set the LogLevel. If the source is from Microsoft or system messages, then the LogLevel is set to Warning .WriteTo.Console(new RenderedCompactJsonFormatter()) .WriteTo.File(new CompactJsonFormatter().ToString())//Output templates, output to Console and File .Enrich.FromLogContext() .CreateLogger();
CompactJsonFormatter
will preserve message templates, properties, and formatting information so that rendered messages can be created later. When JSON is intended to be used in environments without message template rendering,RenderedCompactJsonFormatter
can be used instead.loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration)
: Loading currentConfiguration
-
Add configuration in
appsettings.json
Microsoft.Hosting.Lifetime
: Notifications for application lifecycle eventsMicrosoft.EntityFrameworkCore.Database.Command
: Logging of automatically generated SQL commands by EF Core
-
Startup.cs
setting1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
app.UseSerilogRequestLogging(options => { // Customize the message template options.MessageTemplate = "Handled {RequestPath}"; // Emit debug-level events instead of the defaults options.GetLevel = (httpContext, elapsed, ex) => LogEventLevel.Debug; // Attach additional properties to the request completion event options.EnrichDiagnosticContext = (diagnosticContext, httpContext) => { diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value); diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme); }; });
Usage
-
Add logging where needed
- First, use
Microsoft.Extensions.Logging
- Add a constructor
- Add log entries where logging is needed
Customize the log message level
- First, use
-
Since configurations are added in
Program.cs
andappsettings.json
, all system operations and database reads will be logged.
Reference materials
- Github - serilog-aspnetcore
- Github - Serilog.Formatting.Compact
- Microsoft - .NET Core 與 ASP.NET Core 中的記錄
- WilL Blog - ASP.NET Core 如何紀錄 Entity Framework Core 5.0 自動產生的 SQL 命令
- m@rcus 學習筆記 - [NETCore] 結構化日誌 Serilog - 配置設定
- C# Corner - How To Implement Logging Using Serilog In ASP.NET Core 5.0 Application With Database