NLog for MVC - How to Log the Machine Name and the Client IP Address in NLog

In a preveious post, I went throught the steps to configure NLog for MVC web application. In the following tip I will show you the steps to log the client IP address and the machine name:

Step 1: Installing NLog.Web

NLog.Web is an extension that extend NLog with targets and layout renderers for websites and web applications. It can be downloaded from NuGet

You can use the GUI or the following command in the Package Manager Console:

PM> Install-Package NLog.Web -Version 4.7.0

Step 2: Configuration

In your web.config file you must modify the target schema under the <nlog> section which should be under main section <configuration>:

You need to use ${machinename} to log the machine name and ${aspnet-request-ip} to log the IP address, example:

<target name="file" xsi:type="File" fileName="${basedir}/ErrorLog/log-${shortdate}.log" layout="--------------------- ${level}(${longdate})- Machine Name: ${machinename} - IP: ${aspnet-request-ip} -------------------- ${newline}    ${newline}    Exception Type:${exception:format=Type}${newline}    Exception Message:${exception:format=Message}${newline}    Stack Trace:${exception:format=Stack Trace}${newline}    Additional Info:${message}${newline}" />

The final nlog configuration should look like the following:

<?xml version="1.0"?>
<configuration>
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
<nlog autoReload="true" throwExceptions="false" xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<extensions>
<!-- load NLog.Extended to enable ASP.NET-specific functionality -->
<add assembly="NLog.Extended" />
</extensions>
<!--Define Various Log Targets like files, database or asp.net trace files-->
<targets>
<!--Write logs to File where we want to write error logs-->
<target name="file" xsi:type="File" fileName="${basedir}/Logs/log-${shortdate}.log" layout="--------------------- ${level}(${longdate})- Machine Name: ${machinename} - IP: ${aspnet-request-ip} -------------------- ${newline} ${newline} Exception Type:${exception:format=Type}${newline} Exception Message:${exception:format=Message}${newline} Stack Trace:${exception:format=Stack Trace}${newline} Additional Info:${message}${newline}" />
</targets>
<rules>
<logger name="*" minlevel="trace" writeTo="file" />
</rules>
</nlog>
</configuration>

No Comments

Add a Comment

As it will appear on the website

Not displayed

Your website