Search code examples
c#asp.netasp.net-coreloggingserilog

Turning off auto-logging by .Net while using Serilog


I'm using .Net Core 6 project and want to turn on only the logs that I'm explicitly logging with Serilog. I tried some approaches mentioned here How to turn off the logging done by the ASP.NET core framework but none of them seem to work, still I can see automatically generated logs by the .Net framework viz:

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

Below are my 2 application files:

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();

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
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();

What am I doing wrong here?


Solution

  • This is Serilog logging. To turn it off, you need to override where you set up your Serilog configuration, which you're doing in Program.cs:

            new LoggerConfiguration()
               .MinimumLevel.Information()
               .MinimumLevel.Override("Default", LogEventLevel.Fatal)
               .MinimumLevel.Override("Microsoft", LogEventLevel.Fatal)
               .MinimumLevel.Override("System", LogEventLevel.Fatal)
    

    There isn't a LogEventLevel.None, but 'Fatal' should cut out most. You can do:

               .MinimumLevel.Override("Default", LogEventLevel.Fatal + 1)
    

    which apparently works to suppress all log messages including fatal, but I can't confirm if this works.