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.
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.
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.
This is supported since NLog.Web.AspNetCore 4.4.0.
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
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With