Nlog article series-how to write a custom Layout generator (layout Renderer)

Source: Internet
Author: User

Author: Jaros aw Kowalski <jaak@jkowalski.net>

Translation: crazycoder (Thank you !!)

Original article: http://www.nlog-project.org/howto_write_layout_renderer.html

For more Chinese nlog documents, see nlog document series.

 

Why do I need to write a custom Layout generator?

The layout generator can output the environment information of the program, so it can record more abundant debugging information. Nlog designs layout generators for some of the most common tasks (such as output environment variables, registries, thread IDs, and program root directories. However, because the applications and frameworks are different, it is necessary to develop custom Layout generators.

How to Write

Only one inherited fromNLog.LayoutRendererAnd loadAppend()Method, called in this methodApplyPadding()In this way, you can get the formatted text generated according to the existing layout generator and send it toStringBuilder.

Example

The following is a framework code that outputs the layout generator for the current hour. The compilation command is:

csc.exe /t:library /out:MyAssembly.dll /r:NLog.dll MyFirstLayoutRenderer.cs

 

using System; 
using System.Text; 
 
using NLog; 
 
namespace MyNamespace 
{ 
    [LayoutRenderer("hour")] 
    public sealed class HourLayoutRenderer: LayoutRenderer 
    { 
        private bool _showMinutes = false; 
         
// Example of a Configuration Parameter
        public bool ShowMinutes 
        { 
            get { return _showMinutes; } 
            set { _showMinutes = value; } 
             
        } 
        protected override int GetEstimatedBufferSize(LogEventInfo ev) 
        { 
// A maximum of two characters are required to indicate the hours
// Return the number of buffers required by the layout generator.
            return 2; 
        } 
 
        protected override void Append(StringBuilder builder, LogEventInfo ev) 
        { 
// Get the current hour or minute and convert it into a string. format it.
// Finally add it to the specified stringbuilder
            if (ShowMinutes) 
            { 
                builder.Append(ApplyPadding(DateTime.Now.Minute.ToString())); 
            } 
            else 
            { 
                builder.Append(ApplyPadding(DateTime.Now.Hour.ToString())); 
            } 
        } 
    } 
}

 

 

How to use a custom Layout Generator

Compile the generator to a dynamic link library and reference it in the <extensions/> area of the configuration file. For detailed usage, see here.

 

Configuration File example

The following example adds the current system hour information before all logs. Is it really easy?

 

<nlog> 
  <extensions> 
    <add assembly="MyAssembly"/> 
  </extensions> 
  <targets> 
    <target name="console" type="Console" 
            layout="${hour:showminutes=false} ${message}"/> 
  </targets> 
  <rules> 
    <logger name="*" minLevel="Info" appendTo="console"/> 
  </rules> 
</nlog> 

 

How to pass configuration parameters

Let's take a look at the example above. The "showminutes" attribute is a configuration parameter. You only need to declare the public attribute in the class to save the configuration parameters. Parameters are separated by colons, for example:

${hour:showminutes=true}

In this way, the value of the showminutes attribute is set to true when the configuration information is loaded. Multiple parameter values must be separated by colons:

${layoutrenderername:par1=value1:par2=value2:par3=value3:...:parN=valueN}

Nlog supports parameters of the integer, String, datetime, and Boolean types and automatically converts the types.

 

Must it be stored in the new dynamic link library?

No. You can call the layoutrendererfactory. addlayoutrenderer () method in the program to register your layout builder. However, you must ensure that no log information is recorded before the registration is complete. In the <extensions/> area, you can refer to the EXE executable file.

static void Main(string[] args) 
{ 
    LayoutRendererFactory.AddLayoutRenderer("hour", typeof(MyNamespace.MyFirstLayoutRenderer)); 
 
    // start logging here 
}

 

Last Updated: 2006-07-10 11:32:55

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.