如何在 ASP.NET Core 中使用 Serilog 禁用自动日志记录

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

我想知道是否有办法使用 Serilog 禁用 auto-logging。

我安装了它和 sink 以使用 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
}

那么这是我在 Progam.cs 中的配置:

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

Startup.cs 中(现在评论因为我认为这是自动登录的原因但也评论它 auto-writes 数据库上的记录):

// 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

记录操作:

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}");
}

它有效,但是当我检查 table 时,除了我的记录外,我还看到了很多记录:

有没有办法让 Serilog 只记录我处理过的日志? 谢谢!

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

是的,有。您可以使用 MinimumLevel 配置 属性.

控制哪些日志将进入接收器

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

单个值:

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

每个命名空间覆盖的对象:

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

YOUR.PROJECT.NAMESPACE 替换为您的项目名称空间的名称,从现在开始,只有来自上述名称空间的警告才会转到您的项目的 SQL 服务器接收器和调试级别日志。

将接收器限制为最低级别日志

还有可能将接收器(例如您的 SQL 服务器)限制为最低日志级别。为此使用 restrictedToMinimumLevel 属性 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"
          }
        }
      }
    ]
  }
}

上面的配置会将警告级别的日志记录到 SQL 服务器。

最后一点,如果您切换到 Serilog 并且没有使用内置的 ASP.NET 核心日志记录,您可以安全地从 appsettings.json 中删除之前的 Logging 部分file/s。这些对 Serilog 日志记录没有影响:

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