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

Mat*_*eru 2 sql-server serilog asp.net-core

我想知道是否有办法禁用自动日志记录Serilog

我安装了它并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
}
Run Code Online (Sandbox Code Playgroud)

那么这是我的配置Progam.cs

{
  "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
}
Run Code Online (Sandbox Code Playgroud)

Startup.cs(现在评论,因为我认为这是自动登录的原因,但也评论它它会自动在数据库上写入记录):

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

记录操作:

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}");
}
Run Code Online (Sandbox Code Playgroud)

它有效,但是当我检查表时,除了我的记录之外,我还看到很多记录: 数据库结果

有没有办法告诉 Serilog 仅记录我处理的日志?谢谢你!

Pro*_*log 7

有没有办法告诉 Serilog 仅记录我处理的日志?谢谢你!

就在这里。您可以使用配置属性控制哪些日志将进入接收器MinimumLevel

配置MinimumLevel属性可以设置为单个值,或者可以覆盖每个日志记录源的级别。~ Serilog 配置自述文件

单一值:

{
  "Serilog: {
    "MinimumLevel": "Debug"
  }
}
Run Code Online (Sandbox Code Playgroud)

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

{
  "Serilog":{
    "MinimumLevel":{
      "Default":"Information",
      "Override":{
        "YOUR.PROJECT.NAMESPACE":"Debug",
        "Microsoft":"Information",
        "Microsoft.AspNetCore":"Warning",
        "MongoDB.Driver":"Warning",
        "System":"Warning"
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

替换YOUR.PROJECT.NAMESPACE为您的项目命名空间的名称,从现在开始,只有来自上述命名空间的警告才会进入您的 SQL Server 接收器,并从您的项目中获取调试级别日志。

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

还可以将接收器(例如 SQL 服务器)限制为最低日志级别。对于该使用restrictedToMinimumLevel属性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"
          }
        }
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

上面的配置将把警告级别的日志记录到 SQL Server。

最后一点,如果您切换到 Serilog 并且不使用内置的 ASP.NET Core 日志记录,您可以安全地Loggingappsettings.json文件中删除前一部分。这些对 Serilog 日志记录没有影响:

  "Logging": {
    "LogLevel": {
      "Default": "Trace",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
Run Code Online (Sandbox Code Playgroud)