Nlog article series-Getting Started tutorial (I)

Source: Internet
Author: User

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

Dflying Chen: http://dflying.cnblogs.com/

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

This is the second article in The nlog article series. We will use an instance program to demonstrate how to use the nlog book to write logs.

 

Application Tracking

A long time ago, when no debugger was available and software was mostly based on the console, developers were used to outputting tracing debugging information using printf () statements. Now, the world has undergone earth-shaking changes -- printf () is replaced by console. writeline ......

We have all written code similar to the following:

static void Main() 
{ 
    Console.WriteLine("SuperApp started."); 
    DoSomething();          
    Console.WriteLine("SuperApp finished."); 
}

The console. writeline () in the above Code is the so-called "trace" statement, because this statement has no other use besides the execution status of the current program. The output by console. writeline () is also called application tracing. In the preceding example, these two trace statements are used to tell us whether the dosomething () method has been executed.

After the development and testing are complete, we may want to delete these trace codes to improve the efficiency of sequential execution (because the execution efficiency of tracing and debugging statements is low ). We usually comment out these trace statements so that they can be easily enabled again when needed in the future. Unfortunately, after the tracing statement is commented out, we need to re-compile the program.

Maybe one day, after the n times of comments and uncomments of countless debugging statements, you will vaguely feel that this is not a good solution, and look forward to such features:

  1. You can use a simple method to control the levels of trace information displayed (for example, only warning and error levels of trace information are displayed, or all levels of trace information are displayed ).
  2. The logic for controlling the display of tracing information is separated from the line-of-sight code of the application. You do not need to re-compile the application to display tracing information.
  3. Write tracking information to files, system logs, and message queues ......
  4. It can send important information to a specified recipient by email or store it in a database.
  5. More ......

Some may think that, in today's software development environment where the graphical debugger is widely used, such log-writing tracking and debugging methods seem to be very useful. However, when your program is accessed by thousands of people at the same time every second, even if your program is shut down for one minute, you will know what this debugging information means for locating bugs (the so-called "Live Site debugging ").

 

What is nlog?

Nlog (http://www.nlog-project.org) is a class library written based on the. NET platform, we can use nlog to add very well-developed tracing debugging code in the application. Nlog has fully achieved our above expectations, and far more ......

Nlog allows us to customizeSource)To record the tracking informationTarget)OfRule (Rules). Target can be recorded in the following forms:

  1. File
  2. Text Console
  3. Email
  4. Database
  5. Other computers in the network (through TCP or UDP)
  6. MSMQ-based message queue
  7. Windows system logs
  8. For other forms, see http://www.nlog-project.org/targets.html

In addition, each trace message can automatically containContextual Information)And send it to the target that records the tracking information. The context information can contain the following content:

  1. Current date and time (in multiple formats)
  2. Record level
  3. Source Name
  4. Stack information of the method for outputting message Tracing
  5. Environment variable value
  6. Exception details
  7. Computer, process, and thread name
  8. Others, see: http://www.nlog-project.org/layoutrenderers.html

Each trace information contains a log level information to describe the importance of this information. Nlog supports the following record levels:

  1. Trace-The most common record information, generally used for normal output
  2. Debug-The same information is recorded, but the frequency is less than that of Trace, which is generally used to debug programs.
  3. Info-Message of information type
  4. Warn-Warning information, which is generally used in important scenarios
  5. Error-Error message
  6. Fatal-Fatal exception information. Generally, the program cannot be executed after a fatal exception occurs.

Nlog is a free open-source Class Library released based on BSD license. Even if it is applied to commercial use, there are basically no restrictions. Nlog binary executable files and original files can be downloaded at http://www.nlog-project.org/download.html. We also provide a graphical installation program for nlog. You can select the nlog installation path, you can add the following content to the integrated development environment of Visual Studio during installation (the Express version is also supported ):

  1. Configuration file template
  2. Nlog configuration file smart sensing support
  3. Code snippet (code snippet)
  4. Integrated into the "add reference..." dialog box

 

Our first nlog Application

Next, we will use Visual Studio 2005 to create the first application using nlog. This example program will start from outputting logs to the console and add new features to demonstrate how to configure logs in nlog.

Create a new project in Visual Studio 2005 (the C # demo is used in this example), and then add new item... "dialog box to add an nlog configuration file for the program. Here we select "Empty nlog configuration file" and name it "nlog. config "":

 

Note that nlog. dll reference is automatically added to our project. The content of the newly added nlog. config file is as follows, which will be configured in this example:

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
  <targets> 
  </targets> 
  <rules> 
  </rules> 
</nlog> 

Next, an additional step is required: Set the "Copy to output directory" option of the configuration file to "copy always ". In this way, the configuration file will be automatically deployed to the directory where *. EXE is located. In this way, nlog can automatically search for and load the configuration file without any settings.

 

Next, let's configure the log output. In the <targets/> section, add a new entry for log output to the console and add the necessary output layout (layout ):

<targets> 
  <target name="console" xsi:type="Console" 
          layout="${longdate}|${level}|${message}"/> 
</targets> 

When you enter the above code, you can see that Visual Studio's smart sensing function plays a role: EnterXsi:The list of available output targets is displayed:

 

Then, we need to add the necessary rules in the <rules/> section to grade all records equal to or higherDebugTo the console. This xml configuration file has strong syntax and does not need to be repeated:

<rules> 
  <logger name="*" minlevel="Debug" writeTo="console"/> 
</rules> 

To generate and output diagnostic information, we also need to add a logger object. The method name of the logger object is the same as that of the record level (debug (), Info (), fatal ()......). The logger object is created through the logmanager object. It is recommended that the logger object name be the same as the program class name. Call the getcurrentclasslogger () method of logmanager to automatically create a logger object for the current class.

Next, modify the C # file automatically generated by Visual Studio. First, add the "using nlog" statement in the file header to introduce the namespace of the nlog assembly. Then add the code for creating the logger object. Note that here we can use the code snippet of Visual Studio added with nlog installation: Enter "nlogger" and press the tab key twice.

using System; 
using System.Collections.Generic; 
using System.Text; 
using NLog; 
 
namespace NLogExample 
{ 
    class Program 
    { 
        private static Logger logger = LogManager.GetCurrentClassLogger(); 
         
        static void Main(string[] args) 
        { 
            logger.Debug("Hello World!"); 
        } 
    } 
}

Run the program and output a log to the console. The log contains the current time, record level, and "Hello World" message.

Finally, let's summarize the steps for implementing this function:

  1. Use logmanager. getcurrentclasslogger (); To create a logger object. This logger object represents the log message associated with the current classSource.
  2. Call the debug () method of the logger object to generate a debug record-level diagnostic information.
  3. Because the record level and message source comply with the <rules/> declaration in the configuration file, the message will be formatted with the specified layout and output to the console.

 

Slightly more complex scenarios

Next, let's output the log information, including some context information (such as stack information), to the file and command line. To achieve this, we only need to modify the nlog configuration file and add a target type of "File.

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
  <targets> 
    <target name="console" xsi:type="ColoredConsole" 
            layout="${date:format=HH\:mm\:ss}|${level}|${stacktrace}|${message}"/> 
    <target name="file" xsi:type="File" fileName="${basedir}/file.txt" 
            layout="${stacktrace} ${message}"/> 
  </targets> 
  <rules> 
    <logger name="*" minlevel="Trace" writeTo="console,file"/> 
  </rules> 
</nlog> 

Next, this section of C # code generates more log information, and some other methods provided by nlog are used to output stack information.

static void C() 
{ 
    logger.Info("Info CCC"); 
} 
static void B() 
{ 
    logger.Trace("Trace BBB"); 
    logger.Debug("Debug BBB"); 
    logger.Info("Info BBB"); 
    C(); 
    logger.Warn("Warn BBB"); 
    logger.Error("Error BBB"); 
    logger.Fatal("Fatal BBB"); 
} 
static void A() 
{ 
    logger.Trace("Trace AAA"); 
    logger.Debug("Debug AAA"); 
    logger.Info("Info AAA"); 
    B(); 
    logger.Warn("Warn AAA"); 
    logger.Error("Error AAA"); 
    logger.Fatal("Fatal AAA"); 
} 
static void Main(string[] args) 
{ 
    logger.Trace("This is a Trace message"); 
    logger.Debug("This is a Debug message"); 
    logger.Info("This is an Info message"); 
    A(); 
    logger.Warn("This is a Warn message"); 
    logger.Error("This is an Error message"); 
    logger.Fatal("This is a Fatal error message"); 
}

Run the program. For example, the log information will be written into the program file.txt file.

Program.Main This is a Trace message 
Program.Main This is a Debug message 
Program.Main This is an Info message 
Program.Main => Program.A Trace AAA 
Program.Main => Program.A Debug AAA 
Program.Main => Program.A Info AAA 
Program.Main => Program.A => Program.B Trace BBB 
Program.Main => Program.A => Program.B Debug BBB 
Program.Main => Program.A => Program.B Info BBB 
Program.A => Program.B => Program.C Info CCC 
Program.Main => Program.A => Program.B Warn BBB 
Program.Main => Program.A => Program.B Error BBB 
Program.Main => Program.A => Program.B Fatal BBB 
Program.Main => Program.A Warn AAA 
Program.Main => Program.A Error AAA 
Program.Main => Program.A Fatal AAA 
Program.Main This is a Warn message 
Program.Main This is an Error message 
Program.Main This is a Fatal error message

At the same time, the console also outputs the following beautiful log information.

 

Modify the configuration file. A common requirement in development is to output logs of different record levels to different targets. For example, let the record level be equal to or higherInfoAnd store the information of any record level in the file. To achieve this in nlog, you only need to modify the <rules/> section of the configuration file without modifying the application.

<rules> 
  <logger name="*" minlevel="Info" writeTo="console"/> 
  <logger name="*" minlevel="Trace" writeTo="file"/> 
</rules> 

Run the program again.TraceAndDebugThe level information only appears in the file, not in the console.

(To be continued ......)

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.