How to configure NLog to get the .NET Core IP address

I am developing a .net application and using NLog as a registration framework.

How to configure NLog layout to get remote IP address?

Unfortunately, ${aspnet-request.serverVariable=remote_addr} not supported by NLog.Web.AspNetCore .

Perhaps I am somehow accessing httpContext.Connection.RemoteIpAddress .

+6
source share
3 answers

This is not currently supported, but you can enter it in NLog as follows:

 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 NLog Extension

Using

 ${aspnet-request-ip} 

Also enable NLog.Web.AspNetCore!

+6
source

A simpler solution would be to use the NLog Global Diagnostics Context option.

For example, before recording an event, set a custom value named "IpAddress":

  public IActionResult AnAction() { NLog.GlobalDiagnosticsContext.Set("IpAddress", HttpContext.Connection.RemoteIpAddress); _logger.LogInformation("Something happened"); return View(); } 

And in your nlog.config file, you can use this value in the layout, for example:

 <target xsi:type="File" name="allfile" fileName="c:\nlog.log" layout="${longdate} | ${message} | ${gdc:item=IpAddress}" /> 
+1
source

Now it’s easier: Introduced in NLog Web.AspNetCore 4.4.0 and NLog.Web 4.5.0

Render Client IP Address

Supported in ASP.NET and the ASP.NET kernel.

Configuration syntax

$ {SAS request f}

Nothing more is required

0
source

Source: https://habr.com/ru/post/1012630/


All Articles