c# - 如何强制 Serilog 只记录我的自定义日志消息

标签 c# asp.net-core serilog

我在 appsettings.json 中配置了 Serilog,以便在我的 asp net core web api 应用程序中通过 tcp 将条目记录到 Logstash,方法如下:

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.Network" ],
    "MinimumLevel": {
      "Default": "Information"
    },
    "WriteTo:0": {
      "Name": "TCPSink",
      "Args": {
        "uri": "tcp://172.26.48.39:5066"
      }
    },
    "Properties": {
      "app_id": "my-service-api",
      "index": "my-app-"
    }
  },
  ...
}

但是它记录了太多消息。例如,我在 token Controller 中有一个 CreateToken 操作方法:

[HttpPost]
public ActionResult<string> CreateToken([FromBody] CredentialsModel credentials)
{
    var user = _authentication.Authenticate(credentials);

    if (user == null)
    {
        Log.Warning("Unable to authenticate an user: {Login}, {Password}",
        credentials.Username, credentials.Password);

        return Unauthorized();
    }

    return BuildToken();
}

我只需要记录一条消息:

Unable to authenticate an user Login Password

但 Serilog 记录以下内容:

Request starting HTTP/1.1 POST http://localhost:5000/api/token application/json 57

Route matched with "{action = \"CreateToken\", controller = \"Token\"}". Executing action "Deal.WebApi.Controllers.TokenController.CreateToken (Deal.WebApi)"

Executing action method "Deal.WebApi.Controllers.TokenController.CreateToken (Deal.WebApi)" with arguments (["Deal.BL.Models.Auth.CredentialsModel"]) - Validation state: Valid

Unable to authenticate an user: Login Password

Executed action method "Deal.WebApi.Controllers.TokenController.CreateToken (Deal.WebApi)", returned result "Microsoft.AspNetCore.Mvc.UnauthorizedResult" in 11.0935ms.

Executing HttpStatusCodeResult, setting HTTP status code 401

Executed action "Deal.WebApi.Controllers.TokenController.CreateToken (Deal.WebApi)" in 95.272ms

Request finished in 123.9485ms 401

我怎样才能摆脱不需要的消息?

这是我的 Program.cs 文件:

public class Program
{
    public static void Main(string[] args)
    {
        var currentEnv = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

        var config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .AddJsonFile($"appsettings.{currentEnv}.json", true)
            .AddEnvironmentVariables()
            .Build();

        Log.Logger = new LoggerConfiguration()
            .ReadFrom.Configuration(config)
            .CreateLogger();

        try
        {
            Log.Information("Start web host");

            CreateWebHostBuilder(args).Build().Run();                
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Host terminated unexpectedly");
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseSerilog()
            .UseStartup<Startup>();
}

最佳答案

您可以在 appsettings.json 中覆盖类别级别的日志消息。例如,以下 appsettings.jsonMicrosoft 日志消息设置为仅注销那些被认为是 Error 的消息:

"Serilog": {
    "MinimumLevel": {
        "Default": "Information",
        "Override": {
            "Microsoft": "Error"
        }
    },
    ...
}

此处感兴趣的属性是Override,它代表一个对象,其中属性是类别前缀,值为Serilog log level。使用。

因为您自己的自定义日志消息不会记录在 Microsoft 类别下,您仍会在输出中看到 that

关于c# - 如何强制 Serilog 只记录我的自定义日志消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52887406/

相关文章:

asp.net - web.config asp.net mvc 5 中的 serilog AppSetting

c# - 使用 MVVM 实现搜索功能

C# 无法读取数据集中的 xml

c# - 打印按钮在报告查看器条件下在 Firefox 中不显示

java - 改造具有空字段的获取对象

dependency-injection - 缺少方法异常 : No parameterless constructor defined for type

c# - GPS 中间驱动程序未返回有效结果

asp.net-core - 无法在 Visual Studio 2015 update 3 中通过右键单击添加 View

c# - 为什么我不能在需要相同上下文的 Controller 中注入(inject)需要 httpclient 和 EF 上下文的服务

c# - 默认情况下阻止 Serilog 写入 HTTP 事件