如何防止Serilog自动记录每一个小步骤的信息?

问题描述 投票:0回答:3

我想为我的 .Net 5 Web Api 项目使用 Serilog。我安装了软件包

  • Serilog.AspNetCore v4.1.0
  • Serilog.Sinks.Console v4.0.0

并将 Program.cs 文件更改为

public sealed class Program
{
    public static void Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .WriteTo.Console()
            .CreateLogger();
        
        CreateHostBuilder(args)
            .Build()
            .Run();
    }

    private static IHostBuilder CreateHostBuilder(string[] args) 
        => Host
            .CreateDefaultBuilder(args)
            .UseSerilog()
            .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
}

我创建了一个控制器用于测试目的

[ApiController]
[Route("[controller]")]
public sealed class TodosController : ControllerBase
{
    [HttpGet("{todoId:Guid}")]
    public IActionResult GetTodoById(Guid todoId) => Ok(todoId);
}

消费这个端点后,我可以在控制台中看到以下内容

[22:30:11 INF] Now listening on: https://localhost:5001
[22:30:11 INF] Now listening on: http://localhost:5000
[22:30:11 INF] Application started. Press Ctrl+C to shut down.
[22:30:11 INF] Hosting environment: Development
[22:30:11 INF] Content root path: /home/.../Server
[22:30:12 INF] Request starting HTTP/2 GET https://localhost:5001/swagger - -
[22:30:12 INF] Request finished HTTP/2 GET https://localhost:5001/swagger - - - 301 0 - 78.0119ms
[22:30:12 INF] Request starting HTTP/2 GET https://localhost:5001/swagger/index.html - -
[22:30:12 INF] Request finished HTTP/2 GET https://localhost:5001/swagger/index.html - - - 200 - text/html;charset=utf-8 64.9042ms
[22:30:12 INF] Request starting HTTP/2 GET https://localhost:5001/swagger/swagger-ui.css - -
[22:30:12 INF] Request starting HTTP/2 GET https://localhost:5001/swagger/swagger-ui-bundle.js - -
[22:30:12 INF] Request starting HTTP/2 GET https://localhost:5001/swagger/swagger-ui-standalone-preset.js - -
[22:30:12 INF] Sending file. Request path: '/swagger-ui-standalone-preset.js'. Physical path: 'N/A'
[22:30:12 INF] Sending file. Request path: '/swagger-ui.css'. Physical path: 'N/A'
[22:30:12 INF] Sending file. Request path: '/swagger-ui-bundle.js'. Physical path: 'N/A'
[22:30:12 INF] Request finished HTTP/2 GET https://localhost:5001/swagger/swagger-ui-bundle.js - - - 200 986342 application/javascript 191.4506ms
[22:30:12 INF] Request finished HTTP/2 GET https://localhost:5001/swagger/swagger-ui-standalone-preset.js - - - 200 311804 application/javascript 191.4478ms
[22:30:12 INF] Request finished HTTP/2 GET https://localhost:5001/swagger/swagger-ui.css - - - 200 142933 text/css 192.6142ms
[22:30:13 INF] Request starting HTTP/2 GET https://localhost:5001/swagger/v1/swagger.json - -
[22:30:13 INF] Request finished HTTP/2 GET https://localhost:5001/swagger/v1/swagger.json - - - 200 - application/json;charset=utf-8 83.3874ms
[22:30:41 INF] Request starting HTTP/2 GET https://localhost:5001/Todos/00119201-3fed-4741-8295-48d697790729 - -
[22:30:41 INF] Executing endpoint 'Server.Controllers.TodosController.GetTodoById (Server)'
[22:30:41 INF] Route matched with {action = "GetTodoById", controller = "Todos"}. Executing controller action with signature System.Threading.Tasks.Task`1[Microsoft.AspNetCore.Mvc.IActionResult] GetTodoById(System.Guid) on controller Server.Controllers.TodosController (Server).
[22:30:41 INF] Executing OkObjectResult, writing value of type 'System.Guid'.
[22:30:41 INF] Executed action Server.Controllers.TodosController.GetTodoById (Server) in 34.6663ms
[22:30:41 INF] Executed endpoint 'Server.Controllers.TodosController.GetTodoById (Server)'
[22:30:41 INF] Request finished HTTP/2 GET https://localhost:5001/Todos/00119201-3fed-4741-8295-48d697790729 - - - 200 - application/json;+charset=utf-8 121.1434ms

我不认为这是期望的行为(如果日志级别是信息而不是跟踪)。我错过了什么?如何防止 Serilog 在没有被要求的情况下进行日志记录?

我已经检查过这个问题Serilog - MinimumLoggingLevel Information shows every request in log - is that normal? but that didn't help.未安装 Serilog.Web.Classic 包。

c# serilog
3个回答
15
投票

这些日志由 ASP .NET 主机以

Information
级别写入,因此 Serilog 也将它们接收为
Information

你能做的,就是覆盖不同来源的

MinimumLevel
,这样你就可以继续接收一些来源写的
Information
级日志,同时忽略主机写的
Information
级日志。

举个例子:

  • 将整体
    MinimumLevel
    设置为
    Information
  • 仅对来自
    MinimumLevel
     的日志覆盖 
    Warning
    Microsoft
  • 仅对来自
    MinimumLevel
     的日志覆盖 
    Information
    Microsoft.Hosting.Lifetime

例如

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Information()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
    .MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information)
    .WriteTo.Console()
    .CreateLogger();

您还可以通过

appSettings.json
配置这些源覆盖:

{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    }
  },
  "AllowedHosts": "*"
}

4
投票

您需要为

"Microsoft.Hosting.Lifetime"
"Microsoft"
设置日志级别。我个人使用
Serilog.Settings.Configuration
包,将
.ReadFrom.Configuration(configuration)
添加到设置中,并将默认模板提供的值复制到配置中的
Serilog.MinimumLevel.Override
json 属性:

  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    }
  },

0
投票

我最终像这样配置 Serilog 以隐藏不相关的信息:

"Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Information",
        "Microsoft.Hosting.Lifetime": "Information",
        "Microsoft.AspNetCore.Hosting.Diagnostics": "Warning",
        "Microsoft.AspNetCore.Mvc.RazorPages": "Warning",
        "Microsoft.AspNetCore.Mvc.ViewFeatures": "Warning",
        "Microsoft.AspNetCore.StaticFiles": "Warning",
        // The migration is not applied, so what?
        "Microsoft.EntityFrameworkCore.Migrations": "Warning",
        // DbCommand executed, so what?
        "Microsoft.EntityFrameworkCore.Database": "Warning",
        "Microsoft.AspNetCore.Mvc.Infrastructure": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "Console"
      },
      {
        "Name": "File",
        "Args": {
          "path": "C:/Logs/DEBUG-{Date}.txt",
          "rollingInterval": "Day"
        },
        "When": "Environment = 'Development'"
      },
      {
        "Name": "File",
        "Args": {
          "path": "C:/Logs/RELEASE-{Date}.txt",
          "rollingInterval": "Day"
        },
        "When": "Environment = 'Production'"
      }
    ]
  }

Program.cs:

using Serilog;
        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            return Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                    if (IsDevelopment())
                    {
                        webBuilder.UseUrls("http://0.0.0.0:5000", "https://0.0.0.0:5001");
                    }
                }).UseSerilog((hostingContext, loggerConfiguration) =>
                {
                    loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration);
                });
        }

执行“Home/Index”时的输出:

[16:03:19 INF] Now listening on: http://0.0.0.0:5000
[16:03:19 INF] Now listening on: https://0.0.0.0:5001
[16:03:19 INF] Application started. Press Ctrl+C to shut down.
[16:03:19 INF] Hosting environment: Development
[16:03:19 INF] Content root path: O:\VCSharp\MVCSolution\MVCApplication
[16:03:22 INF] Executing endpoint 'MVCApplication.Controllers.HomeController.Index (MVCApplication)'
[16:03:26 INF] Executed endpoint 'MVCApplication.Controllers.HomeController.Index (MVCApplication)'
© www.soinside.com 2019 - 2024. All rights reserved.