Click here to Skip to main content
15,886,798 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
<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'>&quot;hour&quot;</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>

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