Understanding Nlog .Net Package with Examples

|
| By Webner

Record Logs with Nlog .Net Package – Explanation and Examples

Nlog is a free .Net platform based framework designed for generating logs to record the history of events that help to troubleshoot errors and exceptions. Logging is one of the major important area for developers that helps to debug the general steps of code data values, information of errors and exception especially in the production environment where you are not able to directly use debugging tools which are provided by the Visual studio inbuilt debug tool using breakpoints.

Nlog comes with various capabilities of logging operations. You can create logs for you console applications and web-based application inside different targets which could be a database, a text file on the disk, through email alerts, another machine on the network, console screen etc.

Nlog provides different levels of logging to represent the different type of log information in order sequence Trace, Debug, Info, Warn, Error and Fatal.

To work with the Nlog package, you will need to install the Nlog.config package (which includes Nlog.dll in the references, Nlog.xsd and Nlog.config file) from the Nuget Package Manager.

Perform Logging using “File” as a target :

We can write the logs inside a single file, inside a file that can be generated per day etc. Writing the logs inside the single file is generally not desirable.

To generate the log files, configuration settings for log files are set in the Nlog.config file in XML format.

To configure the Nlog.config file, you must have knowledge of basic Nlog standard elements:

– Layout Renders
– Variables
– Targets
– Rules

Layout Renderers are the macro elements used for designing the layout of the Log file. Some of the renderers have the predefined value assigned and for som, we need to pass the custom value:

for eg :

${date}: writing current date and time. 
${message}: indicate the formatted custom message passed from the Logging statement which could be any level of message error, warning, fatal message etc.

${longdate}: The long, sortable format yyyy-MM-dd HH:mm: ss.ffff of date and time.

${newline}: for adding a new line. 

${level}: for writing the level name of message i.e “DEBUG”, “INFO”, “WARNING”, “TRACE” etc.

You can find the variously available layout renderers at the link – https://github.com/nlog/nlog/wiki/Layout-Renderers

Variables are the expressions used for defining the elements that could be used repetitively or for the purpose of writing the complex expressions. We can simply define the variable in Nlog as follows:

<variable name="myvar" value="myvalue"/>

Targets
Target node in the configuration file is used to specify the type of target logging mechanism to use.

One of the simple format for creating a target in the log file is :

<targets>
……….
     <target xsi:type="File" name="<unique_name_for_accessing_this_element>" 
                  fileName="<log_file_path>"
                  layout="<log_message_format>" 
       />
</targets>

As in our case, we are using the text file as a logging mechanism so we will specify the value of type attribute as “File”.

“name” attribute is required to specify unique access name for the target attribute with which rules can be specified for that target

“fileName” attribute is used to specify either the relative or absolute path of the log file.

“layout” attribute is used to specify the design format of a message in the log file.

We can generate the log File with file extension .txt or .log

Simple example of setting targets to create logs in the file using absolute Path with the help of layout renderers:

<target xsi:type="File" name="myname" fileName="D:/logs/$application.log" />

To generate the log file in some specific location such as Logs folder of the application directory path we can write the configuration using the ${basedir} layout landerer as follows :

<target xsi:type="File" name="myname" fileName="${basedir}/logs/debug.log" />

Rules: are the imposed restricted conditions that can be applied to the targets such as specifying the logging level to use by using the minLevel and maxLevel attributes in the logger under the Rules tag. For example, at the log level we have the sequence “Trace, Debug, Info, Warn, Error and Fatal”. If we don’t want the “Trace” level of logging then we can simply add the starting minimum level of logging with “Debug” for the specific target file as follows

 
<rules>
      <!-- By specifying the minimal level of Debug for the target named as "myname" means, Logger will not write the “Trace” level message in the Log file path specified in the target “myname” . Similarly we can apply the max level  -->
    <logger name="*" minlevel="Debug" maxlevel="Error" writeTo="myname" />
  </rules>

Per Day Logging with “File” as a target :

We can create the log files per day in 2 ways:

(1.) Using target attribute “archiveEvery” and static filename
(2.) Using your own custom designed filename with layout renderers

(1.) Using target attribute “archiveEvery” and static filename:
Nlog provides the attribute “archiveEvery” which gives the flexibility to generate the new log file separately with options of “minutes, hour, day month, week” and gives the flexibility to generate a new log file on specific days like ‘Sunday, Monday….etc.’

To generate the Log file per day we will write the target configuration as follows :

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="c:tempnlog-internal.log">

<variable name="builtinlogstructure" value="${basedir}/builtInlogs/application.log" />
   <targets>
       <target xsi:type="File" 
             name="builtinlogstructure"    
             fileName="${builtinlogstructure}"
             archiveEvery="Day" 
      />
   </targets>
   <rules>
     <logger name="*" minlevel="Trace" writeTo="builtinlogstructure" />
    </rules>
</nlog>

Log file application.log file will be generated each day with incremental number each day as its default settings as shown in the screenshot below.

.Dot Net Package with Examples

(2.) Using your own custom designed filename with layout renderers:

We can create the Log files with custom names. Suppose we want the log files to be generated with a date as the filename for more clear representation of the log file associated date, then for this, we will generate the log file using the {shortdate} layout renderer by setting the fileName attribute of the target as “fileName=” ${basedir}/logs/${shortdate}.log”

To generate the Log file per day using dynamic filename we can write the target configuration as follows :

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="c:tempnlog-internal.log">

    <variable name="logpath" value="${basedir}/logs/${shortdate}.log" />

    <targets>
           <target xsi:type="File" name="debuglog" fileName="${logpath}" />
     </targets>

      <rules>
         <logger name="*" minlevel="Trace" maxlevel="Fatal" writeTo="debuglog" />
     </rules>

</nlog>

Log files will be then generated as follows:

Dot Net Package with Examples

Nlog can be customized in many ways to generate log files based on your requirements. We can also Create Log file inside custom date folder name instead of date filename generated each day. We can also create separate log files based on log levels. In other words, we can set multiple targets in the Nlog to record the Log statements.

Suppose we want the messages from the Level trace, debug and warn level want to appear in the filename “info.log” and error, fatal messages in the separate log file “error.log” inside a folder that is created each day, then we can use the following configuration to generate “info” and “error” log file each day in new folder using multiple target nodes as follows:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="c:tempnlog-internal.log">
  <variable name="infologpath" value="${basedir}/logs/${shortdate}/info.log" />
  <variable name="errorlogpath" value="${basedir}/logs/${shortdate}/error.log" />
 <targets>
    <target xsi:type="File" name="informationlog" fileName="${infologpath}"/>
    <target xsi:type="File" name="errorlog" fileName="${errorlogpath}"
           layout="DateTime: ${longdate} Type- ${uppercase:${level}} Message: ${message}"
              />
  </targets>

  <rules>
    <!--    Rules applied on logger for different target log files     →
     <logger name="*" minlevel="Trace" maxlevel="Warn" writeTo="informationlog" />
     <logger name="*" minlevel="Error" writeTo="errorlog" />
      </rules>
</nlog>

For creating logs in the Log folder without creating the dynamic date folder, we can simply write the path as follows:

  <variable name="infologpath" value="${basedir}/logs/${shortdate}_info.log" />
  <variable name="errorlogpath" value="${basedir}/logs/${shortdate}_error.log" />

In this case files will generated in the format as shown below:

Dot Net Package with Examples

Important attributes associated with Logging :

Layout attribute : Layout attribute of the target is used for designing the custom log message format that will be printed in the log file. If this attribute is not specified, then default format will appear as follows –
Dot Net Package with Examples

One of the example of creating the your custom log message is as follows:

DateTime: ${longdate} Type- ${uppercase:${level}} Message:\n ${message}

Above layout of a log file message will appear as shown in the screenshot below:

Dot Net Package with Examples

Specify the Limit of log files:
We can also control the number of log files that can be retained in the Log folder. Suppose we want only the 10-day log files to stay in the Logs folder, and older files before 10 days should be deleted, then, in that case, we will specify the value 10 of the attribute “maxArchiveFiles” in the target node

  <target xsi:type="File" name="debuglog" fileName="${logpath}" maxArchiveFiles="10"  />

One comment

  1. Hello,
    Nice tutorial exactly same i did in my application.
    I’ve application which runs on production environment and the application is on linux server.also i’ve specific log folder in linux which look like var/log/api and i want to store my application logs on that folder in production environmet.
    so how can i do that? please post some like that which is useful.
    Thank You !!

Leave a Reply

Your email address will not be published. Required fields are marked *