项目作者: mo-esmp

项目描述 :
Enrich logs with client IP and UserAgent.
高级语言: C#
项目地址: git://github.com/mo-esmp/serilog-enrichers-clientinfo.git
创建时间: 2019-12-05T19:58:44Z
项目社区:https://github.com/mo-esmp/serilog-enrichers-clientinfo

开源协议:MIT License

下载


serilog-enrichers-clientinfo NuGet

Enrich logs with client IP, Correlation Id and HTTP request headers.

Install the Serilog.Enrichers.ClientInfo NuGet package

  1. Install-Package Serilog.Enrichers.ClientInfo

or

  1. dotnet add package Serilog.Enrichers.ClientInfo

Apply the enricher to your LoggerConfiguration in code:

  1. Log.Logger = new LoggerConfiguration()
  2. .Enrich.WithClientIp()
  3. .Enrich.WithCorrelationId()
  4. .Enrich.WithRequestHeader("Header-Name1")
  5. // ...other configuration...
  6. .CreateLogger();

or in appsettings.json file:

  1. {
  2. "Serilog": {
  3. "MinimumLevel": "Debug",
  4. "Using": [ "Serilog.Enrichers.ClientInfo" ],
  5. "Enrich": [
  6. "WithClientIp",
  7. "WithCorrelationId",
  8. {
  9. "Name": "WithRequestHeader",
  10. "Args": { "headerName": "User-Agent"}
  11. }
  12. ],
  13. "WriteTo": [
  14. { "Name": "Console" }
  15. ]
  16. }
  17. }

ClientIp

ClientIp enricher reads client IP from HttpContext.Connection.RemoteIpAddress. Since version 2.1, for security reasons, it no longer reads the x-forwarded-for header. To handle forwarded headers, configure ForwardedHeadersOptions. If you still want to log x-forwarded-for, you can use the RequestHeader enricher.

  1. Log.Logger = new LoggerConfiguration()
  2. .Enrich.WithClientIp()
  3. ...

or

  1. {
  2. "Serilog": {
  3. "MinimumLevel": "Debug",
  4. "Using": [ "Serilog.Enrichers.ClientInfo" ],
  5. "Enrich": [
  6. {
  7. "Name": "WithClientIp"
  8. }
  9. ],
  10. }
  11. }

CorrelationId

For CorrelationId enricher you can:

  • Configure the header name and default header name is x-correlation-id
  • Set value for correlation id when the header is not available in request header collection and the default value is false
    1. Log.Logger = new LoggerConfiguration()
    2. .Enrich.WithCorrelationId(headerName: "correlation-id", addValueIfHeaderAbsence: true)
    3. ...
    or
    1. {
    2. "Serilog": {
    3. "MinimumLevel": "Debug",
    4. "Using": [ "Serilog.Enrichers.ClientInfo" ],
    5. "Enrich": [
    6. {
    7. "Name": "WithCorrelationId",
    8. "Args": {
    9. "headerName": "correlation-id"
    10. "addValueIfHeaderAbsence": true
    11. }
    12. }
    13. ],
    14. }
    15. }

    RequestHeader

    You can use multiple WithRequestHeader to log different request headers. WithRequestHeader accepts two parameters; The first parameter headerName is the header name to log
    and the second parameter is propertyName which is the log property name.
    1. Log.Logger = new LoggerConfiguration()
    2. .Enrich.WithRequestHeader(headerName: "header-name-1")
    3. .Enrich.WithRequestHeader(headerName: "header-name-2", propertyName: "SomeHeaderName")
    4. ...
    or
    1. {
    2. "Serilog": {
    3. "MinimumLevel": "Debug",
    4. "Using": [ "Serilog.Enrichers.ClientInfo" ],
    5. "Enrich": [
    6. {
    7. "Name": "WithRequestHeader",
    8. "Args": {
    9. "headerName": "User-Agent"
    10. }
    11. },
    12. {
    13. "Name": "WithRequestHeader",
    14. "Args": {
    15. "headerName": "Connection"
    16. }
    17. },
    18. {
    19. "Name": "WithRequestHeader",
    20. "Args": {
    21. "headerName": "Content-Length",
    22. "propertyName": "RequestLength"
    23. }
    24. }
    25. ],
    26. }
    27. }

Note

To include logged headers in OutputTemplate, the header name without - should be used if you haven’t set the log property name. For example, if the header name is User-Agent, you should use UserAgent.

  1. Log.Logger = new LoggerConfiguration()
  2. .MinimumLevel.Debug()
  3. .Enrich.WithRequestHeader("User-Agent")
  4. .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] {Level:u3} {UserAgent} {Message:lj}{NewLine}{Exception}")

Installing into an ASP.NET Core Web Application

You need to register the IHttpContextAccessor singleton so the enrichers have access to the requests HttpContext to extract client IP and client agent.
This is what your Startup class should contain in order for this enricher to work as expected:

  1. using Microsoft.AspNetCore.Builder;
  2. using Microsoft.AspNetCore.Hosting;
  3. using Microsoft.AspNetCore.Http;
  4. using Microsoft.Extensions.DependencyInjection;
  5. using Microsoft.Extensions.Logging;
  6. using Serilog;
  7. namespace MyWebApp
  8. {
  9. public class Startup
  10. {
  11. public Startup()
  12. {
  13. Log.Logger = new LoggerConfiguration()
  14. .MinimumLevel.Debug()
  15. .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] {Level:u3} CLient IP: {ClientIp} Correlation Id: {CorrelationId} header-name: {headername} {Message:lj}{NewLine}{Exception}")
  16. .Enrich.WithClientIp()
  17. .Enrich.WithCorrelationId()
  18. .Enrich.WithRequestHeader("header-name")
  19. .Enrich.WithRequestHeader("another-header-name", "SomePropertyName")
  20. .CreateLogger();
  21. }
  22. // This method gets called by the runtime. Use this method to add services to the container.
  23. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
  24. public void ConfigureServices(IServiceCollection services)
  25. {
  26. // ...
  27. services.AddHttpContextAccessor();
  28. // ...
  29. }
  30. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  31. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  32. {
  33. // ...
  34. loggerFactory.AddSerilog();
  35. // ...
  36. }
  37. }
  38. }