如何在.net core中使用Serilog在日志中显示ClientIp?

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

项目正在使用.Net Core 3.1 WebAPI。

我正在尝试将客户端设备的 IP 地址记录到控制台。我已经安装了这个包 Serilog.Enrichers.ClientInfo v1.2.0 并按照他们的步骤操作。 除了控制台之外,还有一个带有 [ClientIp] 列的 ErrorLog 表,我想在其中记录 IP 地址。 正如您在输出中看到的,ClientIp 和 ClientAgent 部分都是空白的。 我错过了什么吗?另请验证语法是否正确。

这是我的来自 appsettings.json 的 Serilog 配置

"Serilog": {
"using": [],
"MinimumLevel": {
  "Default": "Debug",
  "Override": {
    "Microsoft": "Warning",
    "System": "Warning",
    "Microsoft.Hosting.Lifetime": "Information"
  }
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithClientIp", "WithClientAgent" ],
"WriteTo": [
  {
    "Name": "Logger",
    "Args": {
      "configureLogger": {
        "WriteTo": [
          {
            "Name": "Console",
            "Args": {
              "outputTemplate": "[{Level:u3} {Timestamp:o}] {ClientIp} {ClientAgent} ({SourceContext}) {Message} {NewLine}"
            }
          }
        ]
      }
    }
  },
  {
    "Name": "Logger",
    "Args": {
      "configureLogger": {
        "Filter": [
          {
            "Name": "ByIncludingOnly",
            "Args": {
              "expression": "@l in ['Error', 'Fatal']"
            }
          }
        ],
        "WriteTo": [
          {
            "Name": "MSSqlServer",
            "Args": {
              "connectionString": "TestDbContext",
              "tableName": "ErrorLogs",
              "batchPostingLimit": 50,
              "autoCreateSqlTable": true,
               "columnOptionsSection": {
                "removeStandardColumns": [ "MessageTemplate" ],
                "customColumns": [
                  {
                    "ColumnName": "ClientIp",
                    "DataType": "VARCHAR",
                    "AllowNull": true,
                    "DataLength": 50
                    //"NonClusteredIndex": true
                  }
                ]
              }
            }
          }
        ]
      }
    }
  }
]

}

输出:

[INF 2022-07-11T20:13:49.0041535+05:30]   () APP:API service has 
started
[INF 2022-07-11T20:13:49.5737570+05:30]   
(Microsoft.Hosting.Lifetime) Now listening on: 
"https://localhost:7017"
[INF 2022-07-11T20:13:49.5987755+05:30]   
(Microsoft.Hosting.Lifetime) Now listening on: 
"http://localhost:5017"
[INF 2022-07-11T20:13:49.6185554+05:30]   
(Microsoft.Hosting.Lifetime) Application started. Press Ctrl+C to 
shut down.
[INF 2022-07-11T20:13:49.6255005+05:30]   
(Microsoft.Hosting.Lifetime) Hosting environment: "Development"
[INF 2022-07-11T20:13:49.6305270+05:30]   
(Microsoft.Hosting.Lifetime) Content root path: "****"
[ERR 2022-07-11T20:14:29.2967601+05:30]   () Testing exception
[ERR 2022-07-11T20:14:29.3735005+05:30]   
(Serilog.AspNetCore.RequestLoggingMiddleware) HTTP "GET" 
"/api/Hospitals" responded 500 in 970.4728 ms
c# asp.net-core-webapi .net-6.0 serilog
3个回答
7
投票

尝试这个包serilog-aspnetcore

app.UseSerilogRequestLogging(options =>
{
    // Customize the message template
    options.MessageTemplate = "{RemoteIpAddress} {RequestScheme} {RequestHost} {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.0000} ms";

    // Emit debug-level events instead of the defaults
    options.GetLevel = (httpContext, elapsed, ex) => LogEventLevel.Debug;

    // Attach additional properties to the request completion event
    options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
    {
        diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
        diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme);
        diagnosticContext.Set("RemoteIpAddress", httpContext.Connection.RemoteIpAddress);
    };
});

查看此链接,可能会有所帮助。

添加 IP 日志记录#38


0
投票

您的 using 语句(appsettings.json ln 2)中缺少

"Serilog.Enrichers.ClientInfo"


0
投票

对于任何看到这篇文章的人,项目的自述文件中简要提到了正确的答案。

Serilog.Enrichers.ClientInfo依赖于

IHttpContextAccessor
来获取当前的HttpContext。该接口的行为在 .NET Core 2.1 中已更改,默认情况下不再注入到服务管道中。

要使库正常工作,您必须将以下调用添加到您的配置服务中:

public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddHttpContextAccessor();
    // ...
}

或者在最近的 .NET 项目中使用顶级语句时:

builder.Services.AddHttpContextAccessor();
© www.soinside.com 2019 - 2024. All rights reserved.