MOST USEFUL NLOG CONFIGURATIONS

ezra heywood

Total Post:145

Points:1019
Posted by  ezra heywood
.NET 
 4090  View(s)
Ratings:
Rate this:

Hi Everyone!

What are the best or most useful configurations for logging with NLog? (These can be simple or complex, as long as they're useful.)

I'm thinking of examples like automatically rolling over log files at a certain size, changing the layout (log message) whether or not there is an exception, escalating the log level once an error has occurred, etc.

Here are some links:

Thanks in advance!
  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: Most useful NLog configurations

    Hi Ezra!

    Treating exceptions differently

    We often want to get more information when there is an exception. The following configuration has two targets, a file and the console, which filter on whether or not 

    there is any exception info. (EDIT: Jarek has posted about a new method of doing this in vNext.)

    The key is to have a wrapper target with xsi:type="FilteringWrapper" condition="length('${exception}')>0"

    <nlog xmlns="http://www.nlog-project.org/schemas/NLog.mono2.xsd"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          autoReload="true"
          internalLogLevel="Warn"
          internalLogFile="nlog log.log"
          >
        <variable name="VerboseLayout" value="${longdate} ${level:upperCase=true} ${message} (${callsite:includSourcePath=true})" />
        <variable name="ExceptionVerboseLayout" value="${VerboseLayout} (${stacktrace:topFrames=10}) ${exception:format=ToString}" />

        <targets async="true">
            <target name="file" xsi:type="File" fileName="log.log"
                    layout="${VerboseLayout}">
            </target>

            <target name="fileAsException" xsi:type="FilteringWrapper" condition="length('${exception}')>0">
                <target xsi:type="File" fileName="log.log" layout="${ExceptionVerboseLayout}" />
            </target>

            <target xsi:type="ColoredConsole" name="console"
                    layout="${NormalLayout}"/>

            <target xsi:type="FilteringWrapper" condition="length('${exception}')>0" name="consoleException">
                <target xsi:type="ColoredConsole"
                        layout="${ExceptionVerboseLayout}" />
            </target>
        </targets>

        <rules>
            <logger name="*" minlevel="Trace" writeTo="console,consoleException" />
            <logger name="*" minlevel="Warn" writeTo="file,fileAsException" />
        </rules>

    </nlog>

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!