How to configure NLog to get IP address .NET Core
It is now easier: Introduced in NLog Web.AspNetCore 4.4.0 & NLog.Web 4.5.0
Render Client IP address
Supported in ASP.NET & ASP.NET Core.
Configuration Syntax
${aspnet-request-ip}
Nothing else is needed
This is supported since NLog.Web.AspNetCore 4.4.0.
- Install the package NLog.Web.AspNetCore
Set in your config
<!-- enable asp.net core layout renderers --> <extensions> <add assembly="NLog.Web.AspNetCore"/> </extensions>
You could now use
${aspnet-request-ip}
in your config.
PS: also supported for ASP.NET in NLog.Web 4.5.0
Old answer
Currently this is not supported, but you could inject it in NLog like this:
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);
}
}
}
Register it (startup.cs)
ConfigurationItemFactory.Default.LayoutRenderers
.RegisterDefinition("aspnet-request-ip", typeof(AspNetRequestIpLayoutRenderer));
See also Extending NLog
usage
${aspnet-request-ip}
Also include NLog.Web.AspNetCore!