Search code examples
sql-serverasp.net-coreserilog

How to disable auto logging using Serilog in ASP.NET Core


I would know if there's a way to disable auto-logging using Serilog.

I installed it and the sink to handle logging using MSSqlServer.

appsettings.json:

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.MSSqlServer" ],
    "MinimumLevel": "Information",
    "WriteTo": [
      {
        "Name": "MSSqlServer",
        "Args": {
          "connectionString": "Server=tcp:{ServerAddress};Initial Catalog={DBName};Persist Security Info=False;User ID={Username};Password={Password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;",
          "sinkOptionsSection": {
            "tableName": "App_Logs",
            "autoCreateSqlTable": true
          }
        }
      }
    ]
  },
  "Logging": {
    "LogLevel": {
      "Default": "Trace",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  // ...other configs
}

then this is my config in Progam.cs:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>())
        .UseSerilog((hostingContext, loggerConfiguration) =>
        {
            loggerConfiguration
                .ReadFrom.Configuration(hostingContext.Configuration);
        });

In Startup.cs (now commented because i thought it was the cause of the auto loggin but also commenting it it auto-writes records on db):

// enables Serilog's HTTP request logging. 
// IMPORTANT: it won't log anything that appears *before* it in the pipeline, 
// so be sure to add it *before* UseEndpoints(), UseMvc(), UseSpa() and so on.
// app.UseSerilogRequestLogging();  <------ i thought it was the cause of the auto loggin but also commenting it it auto-writes records on db

The logging action:

public MVCBaseController(
    ILogger<TController> logger,
    ...)
{
    Logger = logger;
    // ...
}

public ILogger<TController> Logger { get; }
// ...

protected void LogInformation(string message)
{
    string controllerName = ControllerContext?.ActionDescriptor?.ControllerName ?? string.Empty;
    string actionName = ControllerContext?.ActionDescriptor?.ActionName ?? string.Empty;
    string names = 
        $"[{(!string.IsNullOrEmpty(controllerName) ? $"{controllerName}" : "Controller name not found")}" 
        + $"{(!string.IsNullOrEmpty(actionName) ? $".{actionName}]" : "]")}";

    Logger.LogInformation($"{names}\n{message}");
}

It works but when i check the table i see a lot of records in addition to mine: db_result

is there a way to tell Serilog to log only my handled logs? Thank you!


Solution

  • is there a way to tell Serilog to log only my handled logs? Thank you!

    Yes, there is. You can control which logs will go to the sinks with MinimumLevel configuration property.

    The MinimumLevel configuration property can be set to a single value or, levels can be overridden per logging source. ~ Serilog Configuration Readme

    Single value:

    {
      "Serilog: {
        "MinimumLevel": "Debug"
      }
    }
    

    Object with overrides per namespace:

    {
      "Serilog":{
        "MinimumLevel":{
          "Default":"Information",
          "Override":{
            "YOUR.PROJECT.NAMESPACE":"Debug",
            "Microsoft":"Information",
            "Microsoft.AspNetCore":"Warning",
            "MongoDB.Driver":"Warning",
            "System":"Warning"
          }
        }
      }
    }
    

    Replace YOUR.PROJECT.NAMESPACE with the name of your project namespace and from now on only warnings from namespaces above will go to your SQL Server sink and debug level logs from your project.

    Restrict sink to minimum level log

    There is also a possibility to restrict a sink, such as your SQL server, to a minimum level of logs. For that use restrictedToMinimumLevel property of Args:

    {
      "Serilog":{
        "Using":[
          "Serilog.Sinks.MSSqlServer"
        ],
        "MinimumLevel":"Information",
        "WriteTo":[
          {
            "Name":"MSSqlServer",
            "Args":{
              "connectionString":"Server=tcp:{ServerAddress};Initial Catalog={DBName};Persist Security Info=False;User ID={Username};Password={Password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;",
              "sinkOptionsSection":{
                "tableName":"App_Logs",
                "autoCreateSqlTable":true,
                "restrictedToMinimumLevel":"Warning"
              }
            }
          }
        ]
      }
    }
    

    Configuration above will log Warning level logs to SQL Server.

    And one last note, if you switched to Serilog and are not using the built-in ASP.NET Core logging, you can safely remove the previous Logging section from your appsettings.json file/s. These will have no effect on Serilog logging:

      "Logging": {
        "LogLevel": {
          "Default": "Trace",
          "System": "Information",
          "Microsoft": "Information"
        }
      }