2016-11-24 267 views
6

我開發.net核心應用程序並使用NLog作爲日誌框架。如何配置NLog獲取IP地址.NET核心

如何設置NLog佈局來獲取遠程IP地址?

不幸的是,${aspnet-request.serverVariable=remote_addr}不支持NLog.Web.AspNetCore

可能我可以以某種方式訪問​​httpContext.Connection.RemoteIpAddress

回答

6

目前,這是不支持,但你可以把它注射在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!

+1

非常有幫助!有一些重要的TIB位在第一個答案[這個問題](http://stackoverflow.com/questions/34679727/use-nlog-in-asp-net-core-application/34888186)應在看着,太。特別是如果你的'HttpContextAccessor'繼續出現'null' –

1

更簡單的解決方案可能是使用NLog的Global Diagnostics Context選項。

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

而在你nlog.config文件,您可以利用該值在像這樣的佈局:

例如,記錄事件之前設置一個名爲「Ip地址」的自定義值

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

如果你同時有多個用戶,你的全局上下文會發生什麼?那麼你是否確定你正在記錄正確的IP地址。也許考慮將IP地址保存到HttpContext.Current.Items中,然後使用NLog $ {aspnet-item} –

0

現在更容易: 在NLOG介紹Web.AspNetCore 4.4.0 & NLog.Web 4.5.0

渲染客戶端的IP地址

在ASP.NET中受支持& ASP.NET Core。

配置語法

$ {ASPNET請求-IP}

閒來無事需要