Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure NLog to get IP address .NET Core

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.

like image 937
A. Gladkiy Avatar asked Nov 24 '16 12:11

A. Gladkiy


People also ask

How do I find the IP address of my .NET core?

Get server IP address Server or local IP addresses can be retrieved through HttpContext connection feature (IHttpConnectionFeature). Alternatively, server address can be retrieved through DNS. Multiple IP addresses are shown for all the available networks.

What is NLog in .NET core?

NLog is a flexible and free logging platform for various . NET platforms, including . NET standard. NLog makes it easy to write to several targets. (database, file, console) and change the logging configuration on-the-fly.


1 Answers

This is supported since NLog.Web.AspNetCore 4.4.0.

  1. Install the package NLog.Web.AspNetCore
  2. Set in your config

    <!-- enable asp.net core layout renderers -->
    <extensions>
      <add assembly="NLog.Web.AspNetCore"/>
    </extensions>
    
  3. 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!

like image 94
Julian Avatar answered Sep 29 '22 09:09

Julian