Click here to Skip to main content
15,896,557 members
Articles / Programming Languages / C#

Logging with NLog

Rate me:
Please Sign up or sign in to vote.
1.68/5 (13 votes)
6 Jan 20073 min read 52.3K   69   20  
The article describes how to configure nlog to log reports as per your requirement
<html><head><META http-equiv="Content-Type" content="text/html; charset=utf-8"><link rel="stylesheet" href="style.css" type="text/css"><meta name="generator" content="NAnt 0.85 style task"><meta name="keywords" content="NLog logging tracing debugging library easy simple C# .NET log4net log4j Logger C/C++ COM"><title>NLog - How To...</title></head><body width="100%"><div class="titleimage" style="overflow: hidden"><img src="NLog.jpg"></div><table class="page" cellpadding="0" cellspacing="0"><tr><td valign="top" class="controls" rowspan="2"><table border="0" cellpadding="0" cellspacing="0"><tr><td class="nav"><a class="nav" href="index.html">Introduction</a></td></tr><tr><td class="nav"><a class="nav" href="news.html">News</a></td></tr><tr><td class="nav"><a class="nav" href="tutorial.html">Tutorial</a></td></tr><tr><td class="nav"><a class="nav" href="benchmark.html">Benchmark</a></td></tr><tr><td class="nav_selected"><a class="nav_selected" href="howto.html">How To...</a><table class="submenu" width="100%"><tr><td><a class="subnav" href="howto_write_target.html">Write a log target</a></td></tr><tr><td><a class="subnav_selected">Write a layout renderer</a></td></tr><tr><td><a class="subnav" href="howto_write_filter.html">Write a filter</a></td></tr><tr><td><a class="subnav" href="howto_optimize_performance.html">Optimize logging performance</a></td></tr><tr><td><a class="subnav" href="howto_troubleshoot.html">Troubleshoot logging problems</a></td></tr></table></td></tr><tr><td class="nav"><a class="nav" href="api.html">Logging API</a></td></tr><tr><td class="nav"><a class="nav" href="reference.html">Reference</a></td></tr><tr><td class="nav"><a class="nav" href="download.html">Download</a></td></tr><tr><td class="nav"><a class="nav" href="technical.html">Technical Information</a></td></tr><tr><td class="nav"><a class="nav" href="mailinglists.html">Mailing Lists</a></td></tr><tr><td class="nav"><a class="nav" href="faq.html">FAQ</a></td></tr><tr><td class="nav"><a class="nav" href="blog.html">Blog</a></td></tr><tr><td class="nav"><a class="nav" href="links.html">Links</a></td></tr></table><p></p><p style="border: 1px solid #c0c0c0; background-color: white; padding: 4px; font-size: 13px; color: red; font-weight: bold">Important information for users of NLog versions 0.2 and 0.5! Click <a href="releasenotes.html">here</a>.</p><a href="http://www.cenqua.com/clover.net"><img src="http://www.cenqua.com/images/cloverednet1.gif" width="89" height="33" border="0" alt="Code Coverage by Clover.NET"></a><p></p><script type="text/javascript" language="javascript">
var sc_project=575077; 
var sc_partition=4; 
var sc_security="6fe22c9a"; 
</script><script type="text/javascript" language="javascript" src="http://www.statcounter.com/counter/counter.js"></script><noscript><a href="http://www.statcounter.com/" target="_blank"><img src="http://c5.statcounter.com/counter.php?sc_project=575077&amp;java=0&amp;security=6fe22c9a" alt="website tracking" border="0"></a></noscript><br><a href="http://sourceforge.net"><img src="http://sourceforge.net/sflogo.php?group_id=116456&amp;type=1" width="88" height="31" border="0" alt="SourceForge.net Logo"></a></td><td valign="top" align="left" class="content"><h1>How to write your own Layout Renderer</h1><h5>Why would I want to write a Layout Renderer?</h5><p>Layout renderers are a way to enrich your debugging output by outputting 
        environmental properties of your applications. NLog comes with Layout Renderers for most common tasks (like
        outputting environment variables, registry keys, thread ids, base directory, etc.), 
        but you may want to develop your own Layout Renderer to provide information about your
        application or framework.
    </p><h5>How to write a layout renderer?</h5><p>
        It's really easy. Create a class that inherits from <code>NLog.LayoutRenderer</code> 
        and override the <code>Append()</code> method. In the body of the method use the
        <code>ApplyPadding()</code> to get the output text formatted according to the
        common Layout Renderer parameters then send the text to the destination <code>StringBuilder</code>.
    </p><h5>Example</h5><p>This is a skeleton layout renderer that outputs current hour. Compile using:</p><p><code>csc.exe /t:library /out:MyAssembly.dll /r:NLog.dll MyFirstLayoutRenderer.cs</code></p><pre class="csharp-example"><pre xml:space="preserve"><span class="csharp"><span class="k">using</span> System;
<span class="k">using</span> System.Text;

<span class="k">using</span> NLog;

<span class="k">namespace</span> MyNamespace
{
    [LayoutRenderer(<span class="s">"hour"</span>)]
    <span class="k">public</span> <span class="k">sealed</span> <span class="k">class</span> HourLayoutRenderer: LayoutRenderer
    {
        <span class="k">private</span> <span class="k">bool</span> _showMinutes = <span class="k">false</span>;
        
        <span class="c">// this is an example of a configurable parameter</span>
        <span class="k">public</span> <span class="k">bool</span> ShowMinutes
        {
            get { <span class="k">return</span> _showMinutes; }
            set { _showMinutes = value; }
            
        }
        <span class="k">protected</span> <span class="k">override</span> <span class="k">int</span> GetEstimatedBufferSize(LogEventInfo ev)
        {
            <span class="c">// since hour is expressed by 2 digits we need at most 2-character</span>
            <span class="c">// buffer for it</span>
            <span class="k">return</span> 2;
        }

        <span class="k">protected</span> <span class="k">override</span> <span class="k">void</span> Append(StringBuilder builder, LogEventInfo ev)
        {
            <span class="c">// get current hour or minute, convert it to string, apply padding</span>
            <span class="c">// and append to the specified StringBuilder</span>
            <span class="k">if</span> (ShowMinutes)
            {
                builder.Append(ApplyPadding(DateTime.Now.Minute.ToString()));
            }
            <span class="k">else</span>
            {
                builder.Append(ApplyPadding(DateTime.Now.Hour.ToString()));
            }
        }
    }
}
</span>
</pre></pre><h5>How to use the newly created layout renderer?</h5><p>
    It's easy. Just put the renderer in a DLL and reference it from the the config file using the <span class="xmlbracket">&lt;</span><span class="xmlelement">extensions</span><span class="xmlbracket"> /&gt;</span>
    clause as described <a href="config.html#extensions">here</a>.
</p><h5>Configuration file example</h5><p>
    This example causes all messages written to the console to be prepended with current hour. Simple isn't it?
</p><pre class="xml-example"><span class="xmlbracket">&lt;</span><span class="xmlelement">nlog</span><span class="xmlbracket">&gt;</span>
    <span class="xmlbracket">&lt;</span><span class="xmlelement">extensions</span><span class="xmlbracket">&gt;</span>
        <span class="xmlbracket">&lt;</span><span class="xmlelement">add</span><span class="xmlattribute"> assembly</span><span class="xmlpunct">=</span><span class="xmlattribtext">"MyAssembly"</span><span class="xmlbracket"> /&gt;</span>
    <span class="xmlbracket">&lt;/</span><span class="xmlelement">extensions</span><span class="xmlbracket">&gt;</span>

    <span class="xmlbracket">&lt;</span><span class="xmlelement">targets</span><span class="xmlbracket">&gt;</span>
        <span class="xmlbracket">&lt;</span><span class="xmlelement">target</span><span class="xmlattribute"> name</span><span class="xmlpunct">=</span><span class="xmlattribtext">"console"</span><span class="xmlattribute"> type</span><span class="xmlpunct">=</span><span class="xmlattribtext">"Console"</span><span class="xmlattribute"> layout</span><span class="xmlpunct">=</span><span class="xmlattribtext">"${hour:showminutes=false} ${message}"</span><span class="xmlbracket"> /&gt;</span>
    <span class="xmlbracket">&lt;/</span><span class="xmlelement">targets</span><span class="xmlbracket">&gt;</span>

    <span class="xmlbracket">&lt;</span><span class="xmlelement">rules</span><span class="xmlbracket">&gt;</span>
        <span class="xmlbracket">&lt;</span><span class="xmlelement">logger</span><span class="xmlattribute"> name</span><span class="xmlpunct">=</span><span class="xmlattribtext">"*"</span><span class="xmlattribute"> minLevel</span><span class="xmlpunct">=</span><span class="xmlattribtext">"Info"</span><span class="xmlattribute"> appendTo</span><span class="xmlpunct">=</span><span class="xmlattribtext">"console"</span><span class="xmlbracket"> /&gt;</span>
    <span class="xmlbracket">&lt;/</span><span class="xmlelement">rules</span><span class="xmlbracket">&gt;</span>
<span class="xmlbracket">&lt;/</span><span class="xmlelement">nlog</span><span class="xmlbracket">&gt;</span></pre><h5>How to pass configuration options to the renderer?</h5><p>
Consider the above example. There's a property called "ShowMinutes" that does just that. 
Having a public property that sets the required configuration parameters is enough for NLog to use it. 
Parameters can be passed by separating them with colons. For example:
</p><code>${hour:showminutes=true}</code><p>sets the ShowMinutes property to True during configuration. To pass more parameters, just use more colons:</p><code>${layoutrenderername:par1=value1:par2=value2:par3=value3:...:parN=valueN}</code><p>
NLog takes care of the appropriate conversions necessary so that
you can use integer, string, datetime, boolean parameters.
</p><h5>Do I really need to create a separate DLL?</h5><p>
    Not really. You can use LayoutRendererFactory.AddLayoutRenderer() to register your layout renderer programmatically. 
    Just be sure to to it at the very beginning of your program before any log messages are written.
    It should be possible to reference your EXE using the <span class="xmlbracket">&lt;</span><span class="xmlelement">extensions</span><span class="xmlbracket"> /&gt;</span> clause.
</p><pre class="csharp-example"><pre xml:space="preserve"><span class="csharp"><span class="k">static</span> <span class="k">void</span> Main(<span class="k">string</span>[] args)
{
    LayoutRendererFactory.AddLayoutRenderer(<span class="s">"hour"</span>, <span class="k">typeof</span>(MyNamespace.MyFirstLayoutRenderer));

    <span class="c">// start logging here</span>
}
</span>
</pre></pre></td></tr><tr><td class="copyright">Copyright © 2003-2005 by Jarosław Kowalski</td></tr></table></body></html>

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions