我开发.net核心应用程序并使用NLog作为日志框架。如何配置NLog获取IP地址.NET核心
如何设置NLog布局来获取远程IP地址?
不幸的是,${aspnet-request.serverVariable=remote_addr}
不支持NLog.Web.AspNetCore。
可能我可以以某种方式访问httpContext.Connection.RemoteIpAddress
。
我开发.net核心应用程序并使用NLog作为日志框架。如何配置NLog获取IP地址.NET核心
如何设置NLog布局来获取远程IP地址?
不幸的是,${aspnet-request.serverVariable=remote_addr}
不支持NLog.Web.AspNetCore。
可能我可以以某种方式访问httpContext.Connection.RemoteIpAddress
。
目前,这是不支持,但你可以把它注射在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));
使用
${aspnet-request-ip}
还包括NLog.Web.AspNetCore!
更简单的解决方案可能是使用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}" />
如果你同时有多个用户,你的全局上下文会发生什么?那么你是否确定你正在记录正确的IP地址。也许考虑将IP地址保存到HttpContext.Current.Items中,然后使用NLog $ {aspnet-item} –
现在更容易: 在NLOG介绍Web.AspNetCore 4.4.0 & NLog.Web 4.5.0
渲染客户端的IP地址
在ASP.NET中受支持& ASP.NET Core。
配置语法
$ {ASPNET请求-IP}
闲来无事需要
非常有帮助!有一些重要的TIB位在第一个答案[这个问题](http://stackoverflow.com/questions/34679727/use-nlog-in-asp-net-core-application/34888186)应在看着,太。特别是如果你的'HttpContextAccessor'继续出现'null' –