You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core 6中使用Serilog时如何关闭框架自动日志?

问题描述

我正在使用.NET Core 6项目,希望仅启用通过Serilog显式记录的日志。尝试过关闭ASP.NET Core框架日志的方法,但均无效,仍能看到.NET框架自动生成的日志:

2023-06-29 19:45:05.866 +05:30 [INF] Now listening on: https://localhost:7164
2023-06-29 19:45:05.916 +05:30 [INF] Now listening on: http://localhost:5111
2023-06-29 19:45:05.925 +05:30 [INF] Application started. Press Ctrl+C to shut down.
2023-06-29 19:45:05.929 +05:30 [INF] Hosting environment: Development

以下是我的配置文件:

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "None",
      "System": "None",
      "Microsoft": "None"
    }
  },
  "AllowedHosts": "*"
}

Program.cs

using Serilog;

var builder = WebApplication.CreateBuilder(args);

// Add Serilog logger
Log.Logger = new LoggerConfiguration()
               .MinimumLevel.Information()
               .WriteTo.Console()
               .WriteTo.File($"Logs/log_{DateTime.Now:yyyyMMdd_HHmmss}.txt",outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
               .CreateLogger();

// Add services to the container
builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

请问我哪里配置出错了?


解决方案

问题出在两个核心配置缺失:

  1. Serilog未明确过滤Microsoft/System命名空间的框架日志,默认会包含该类日志
  2. 未将Serilog设为.NET的主日志提供器,框架启动阶段的日志仍会绕过现有配置输出

按以下步骤修改即可解决:

步骤1:添加框架日志过滤规则

在LoggerConfiguration中新增对Microsoft和System命名空间的日志级别覆盖,直接设为None:

Log.Logger = new LoggerConfiguration()
               .MinimumLevel.Information()
               // 完全排除Microsoft和System命名空间的所有日志
               .MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.None)
               .MinimumLevel.Override("System", Serilog.Events.LogEventLevel.None)
               .WriteTo.Console()
               .WriteTo.File($"Logs/log_{DateTime.Now:yyyyMMdd_HHmmss}.txt",outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
               .CreateLogger();

步骤2:替换默认日志提供器

将原来的builder.Services.AddLogging(...)替换为builder.Host.UseSerilog(),确保Serilog完全接管.NET的整个日志管道(包括启动阶段的日志):

// 移除这一行:
// builder.Services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));

// 替换为:
builder.Host.UseSerilog();

完整修改后的Program.cs

using Serilog;

var builder = WebApplication.CreateBuilder(args);

// Add Serilog logger
Log.Logger = new LoggerConfiguration()
               .MinimumLevel.Information()
               .MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.None)
               .MinimumLevel.Override("System", Serilog.Events.LogEventLevel.None)
               .WriteTo.Console()
               .WriteTo.File($"Logs/log_{DateTime.Now:yyyyMMdd_HHmmss}.txt",outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
               .CreateLogger();

// 替换默认日志提供器
builder.Host.UseSerilog();

// Add services to the container
builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

额外说明

  • 现有appsettings.json的配置可以保留,但Serilog的代码配置优先级更高,只要代码中设置了Override规则,就会覆盖配置文件的对应项
  • 如果偏好通过配置文件管理Serilog规则,可以改用ReadFrom.Configuration(builder.Configuration)读取配置,当前场景下代码直接配置更高效

内容的提问来源于stack exchange,提问作者The Inquisitive Coder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 12:20:39