问题
I develop .net core app and use NLog as logging framework.
How can I setup NLog layout to get remote IP address?
Unfortunately, ${aspnet-request.serverVariable=remote_addr} isn't supported by NLog.Web.AspNetCore. 
May be I can get access to httpContext.Connection.RemoteIpAddress somehow.
回答1:
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!
回答2:
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
回答3:
A simpler solution might be to use NLog's Global Diagnostics Context option.
For example, set a custom value named "IpAddress" before logging an event:
 public IActionResult AnAction()
 {
     NLog.GlobalDiagnosticsContext.Set("IpAddress", HttpContext.Connection.RemoteIpAddress);
     _logger.LogInformation("Something happened");
     return View();
 }
And in your nlog.config file, you can make use of that value in the layout like this:
<target xsi:type="File" name="allfile" fileName="c:\nlog.log" 
    layout="${longdate} | ${message} | ${gdc:item=IpAddress}" />
来源:https://stackoverflow.com/questions/40786220/how-to-configure-nlog-to-get-ip-address-net-core