如何配置 NLog 获取 IP 地址 .NET Core

How to configure NLog to get IP address .NET Core

我开发 .net 核心应用程序并使用 NLog 作为日志框架。

如何设置 NLog 布局以获取远程 IP 地址?

很遗憾,NLog.Web.AspNetCore 不支持 ${aspnet-request.serverVariable=remote_addr}

也许我可以通过某种方式访问​​ httpContext.Connection.RemoteIpAddress

从 NLog.Web.AspNetCore 4.4.0.

开始支持
  1. 安装包 NLog.Web.AspNetCore
  2. 在你的配置中设置

    <!-- enable asp.net core layout renderers -->
    <extensions>
      <add assembly="NLog.Web.AspNetCore"/>
    </extensions>
    
  3. 您现在可以在您的配置中使用 ${aspnet-request-ip}

PS:在 NLog.Web 4.5.0

中也支持 ASP.NET

旧答案

目前不支持,但您可以像这样将其注入到 NLog 中:

using System;
using System.Text;
using Microsoft.AspNetCore.Http;
using NLog.Config;
using NLog.LayoutRenderers;
using NLog.Web.Internal;

namespace NLog.Web.LayoutRenderers
{
    /// <summary>
    /// Render the request IP for ASP.NET Core
    /// </summary>
    /// <example>
    /// <code lang="NLog Layout Renderer">
    /// ${aspnet-request-ip}
    /// </code>
    /// </example>
    [LayoutRenderer("aspnet-request-ip")]
    public class AspNetRequestIpLayoutRenderer : AspNetLayoutRendererBase
    {

        protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent)
        {
            var httpContext = HttpContextAccessor.HttpContext;
            if (httpContext == null)
            {
                return;
            }
            builder.Append(httpContext.Connection.RemoteIpAddress);
        }
    }
}

注册 (startup.cs)

ConfigurationItemFactory.Default.LayoutRenderers
    .RegisterDefinition("aspnet-request-ip", typeof(AspNetRequestIpLayoutRenderer));

另见 Extending NLog

用法

${aspnet-request-ip}

还包括NLog.Web.AspNetCore!

一个更简单的解决方案可能是使用 NLog 的 Global Diagnostics Context 选项。

例如,在记录事件之前设置一个名为 "IpAddress" 的自定义值:

 public IActionResult AnAction()
 {
     NLog.GlobalDiagnosticsContext.Set("IpAddress", HttpContext.Connection.RemoteIpAddress);
     _logger.LogInformation("Something happened");
     return View();
 }

并且在您的 nlog.config 文件中,您可以像这样在布局中使用该值:

<target xsi:type="File" name="allfile" fileName="c:\nlog.log" 
    layout="${longdate} | ${message} | ${gdc:item=IpAddress}" />

现在更容易了: 在 NLog Web.AspNetCore 4.4.0 & NLog.Web 4.5.0

中引入

渲染客户端IP地址

ASP.NET & ASP.NET 核心支持。

配置语法

${aspnet-request-ip}

不需要别的

还需要在.Build()之前调用.NLog()

像这样:

public static void Main(string[] args)
{
  CreateWebHostBuilder(args).UseNLog().Build().Run();
}