# SerilogSimple **Repository Path**: EarenLee/SerilogSimple ## Basic Information - **Project Name**: SerilogSimple - **Description**: .net6 集成 Serilog 的简单应用 - **Primary Language**: C# - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2023-01-11 - **Last Updated**: 2025-09-18 ## Categories & Tags **Categories**: Uncategorized **Tags**: Serilog, Net6, 日志 ## README # SerilogSimple #### 介绍 .net6 集成 Serilog 的简单应用 #### 技术栈 - `net6` - `Serilog.AspNetCore` `6.1.0` - `Newtonsoft.Json` `13.0.2` - `Swashbuckle.AspNetCore` `6.2.3` #### 重点代码 1. Program.cs 类 ``` c var builder = WebApplication.CreateBuilder(args); Environment.SetEnvironmentVariable("BASEDIR", AppContext.BaseDirectory); // Serilog builder.Host.UseSerilog((context, services, configuration) => { configuration.ReadFrom.Configuration(context.Configuration) .ReadFrom.Services(services) .Enrich.FromLogContext() .WriteTo.Console(); }); app.UseSerilogRequestLogging(options=> { // 自定义消息模板 options.MessageTemplate= "Handled {RequestPath}"; // 发出调试级别事件而不是默认值 options.GetLevel = (httpContext, elapsed, ex) => Serilog.Events.LogEventLevel.Debug; // 将其他属性附加到请求完成事件 options.EnrichDiagnosticContext = (diagnosticContext, httpContext) => { diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value); diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme); }; }); ``` 2. 在需要记录日志的类中注入 Logger ``` // 示例代码中采用在 WeatherForecastController 中注入 private readonly ILogger _logger; public WeatherForecastController(ILogger logger) { _logger = logger; } // 在需要记录日志的地方写入如下代码 _logger.LogInformation("这是日志信息...."); ``` 3. 配置信息 appsettings.json ```json /* 示例中配置信息在 appsettings.Development.json 中 */ "Serilog": { "MinimumLevel": { "Default": "Information", "Override": { "Microsoft": "Information", "Microsoft.Hosting.Lifetime": "Information", "Microsoft.EntityFrameworkCore.Database.Command": "Information" } }, "Enrich": ["FromLogContext", "WithThreadId" ], "WriteTo": [ { "Name": "Console", "Args": { "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {SourceContext} {ThreadId} [{Level:u3}] {Message:lj}{NewLine}{Exception}" } }, { "Name": "Debug", "Args": { "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {SourceContext} {ThreadId} [{Level:u3}] {Message:lj}{NewLine}{Exception}" } }, { "Name": "File", "Args": { "path": "%BASEDIR%/logs/log-.log", /*"path": "./logs/log-.log",*/ "rollingInterval": "Day" } } ] } ```