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"?>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
<nlog autoReload="true" throwExceptions="false" xmlns="" xmlns:xsi="">
<!-- load NLog.Extended to enable ASP.NET-specific functionality -->
<add assembly="NLog.Extended" />
<!--Define Various Log Targets like files, database or trace files-->
<!--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}" />
<logger name="*" minlevel="trace" writeTo="file" />


Zender helps you automate marketing emails throughout the customer journey using a powerful API. Create and Send html based emails, Sign Up Confirmation Emails, Change Password Emails, Campaigns, Advertising and Media News Emails

Check out the API and let us know how can we support you.

1 Comment

Add a Comment

As it will appear on the website

Not displayed

Your website