Nlog article series-Getting Started tutorial (medium)

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 third article in The nlog article series. We will continue to describe how to use nlog to write logs. I wanted to fix the entire getting started tutorial today, but it was too late ...... I can only separate one article ...... In a hurry, we have many bad words. Please forgive me ......

 

Log Configuration

Next, let's take a look at the nlog configuration principles. Different from other tools, nlog will try to perform automatic configuration when the program starts. In other words, nlog will automatically search for its configuration file in some default locations. When nlog and standard EXE files are used together, the following paths are automatically searched in order to obtain the configuration file:

  1. Application standard configuration file (usually applicationname.exe. config)
  2. Applicationname.exe. nlog file in the application catalog
  3. Nlog. config file in the application directory
  4. Nlog. dll. nlog file in the directory where nlog. dll is located
  5. The file to which the environment variable nlog_global_config_file points

For ASP. NET applications, nlog automatically searches for the following paths in sequence:

  1. Standard configuration file for Web applications-web. config
  2. Web. nlog file in the directory where web. config is located
  3. Nlog. config file in the application directory
  4. Nlog. dll. nlog file in the directory where nlog. dll is located
  5. The file to which the environment variable nlog_global_config_file points

. NET Compact framework does not support application configuration files (*. EXE. config) and environment variables. Therefore, nlog automatically searches for the following paths in sequence:

  1. Applicationname.exe. nlog file in the application catalog
  2. Nlog. config file in the application directory
  3. Nlog. dll. nlog file in the directory where nlog. dll is located

 

Configuration File Format

Nlog supports two types of configuration files:

  1. Embedded in standard configuration files such as *. EXE. config or web. config.
  2. Separate configuration file

For the first form, we use the standardized configsection mechanism. The configuration file is as follows:

<configuration> 
  <configSections> 
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/> 
  </configSections> 
  <nlog> 
  </nlog> 
</configuration> 

In the second form, the xml configuration file uses <nlog/> as its root node. The namespace of XML is optional, but if the namespace is specified as follows, it will be intelligently supported by Visual Studio.

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

If the XML namespace is not specified, the nlog configuration file is case insensitive. If an XML namespace is specified, it is case sensitive. Smart sensing can only work normally when an XML namespace is specified.

 

Configuration File Element

In the <nlog/> root element of the configuration file, we can specify the following sub-elements. The first two must be set, and the other three are optional.

  1. <Targets/>-Define the log output target
  2. <Rules/>-Define rules for routing log information
  3. <Extensions/>-Define the nlog extension module loaded from other DLL files
  4. <Include/>-Introduce external configuration files
  5. <Variable/>-Define variables used in the configuration file

 

Target)

<Targets/> the configuration section defines the output location of log information. Each output position is represented by a <target/> element. <Target/> the element has two attributes that must be set:

  1. Name-Name of the output target
  2. Type-Type of the output target, such as "file", "Database", and "mail. If we specify a namespace for the configuration file, the property name isXsi: Type.

In addition to the two attributes that must be set, the <target/> element also supports some other attributes, which can also affect the way diagnostic information is recorded. We can set different attribute parameters for each output target. These attributes are described in detail on the nlog homepage, and Visual Studio also provides intelligent sensing support for them.

For example:"File"The output target acceptsFilenameTo specify the name of the output file.ConsoleThe output target is namedErrorIndicates whether stderr is used to replace stdout ).

Nlog provides many and defined output targets, which are described in detail on the nlog homepage. If you think it is not enough and want to write custom output targets, it is also very simple-15-20 lines of code is enough. Please refer to the nlog documentation (documentation ).

 

Routing Rules (rule)

The routing rules are defined in the <rules/> section of the configuration file. This part is a simple route table used to define different log sources (logger names) and the output target to which the log information of the record level will be sent. The routing rule will be executed from the first entry in the list. If the current routing rule is met, the log information will be sent to the specified output destination, if none of the items in the route table meet the requirements, the log information will not be processed.

Each entry in the route table is defined by a <logger/> element. The <logger/> element supports the following attributes:

  1. Name-Log source (logger name), which can use * wildcard characters
  2. Minlevel-Minimum record level required to match the rule
  3. Maxlevel-The highest record level required to match the rule
  4. Level-A single record level required to match the rule
  5. Levels-List of record levels required to match this rule. Record levels are separated by commas.
  6. Writeto-The log information matching the rule will be sent to the output target list, separated by commas (,).
  7. Final-Make the rule the last matching entry of log information. After the log information meeting The rule is processed, it will no longer try to match the following defined routing rules.

Some examples:

Logs from class1 in namespace name. Space with a record level equal to or higher than debug will be sent to the output target F1.

<logger name="Name.Space.Class1" minlevel="Debug" writeTo="f1" />

Logs from class1 in namespace name. space with the record level equal to debug or error will be sent to the output target F1.

<logger name="Name.Space.Class1" levels="Debug,Error" writeTo="f1" />

Any log information from any class in namespace name. Space will be sent to the output destination F3 and F4.

<logger name="Name.Space.*" writeTo="f3,f4" />

From namespace name. logs of any class in space with a record level between debug and error (including debug, info, warn, and error) will be ignored (no writeto attribute ), and will not be processed by the following routing rules (because final = "true" is set ").

<logger name="Name.Space.*" minlevel="Debug" maxlevel="Error" final="true" /> 

In the preceding example, the configuration file contains only one <target/> element and one <logger/> element. As the demand for programs continues to expand, adding new output targets and routing rules will also be very simple.

 

Context information

One of the most advantageous features of nlog is itsLayout)Concept. The "$ {}" symbol is used to represent"Layout Renderer)", That is, insert a piece of context information along with the current log. We can use layout in many places, such as controlling the format of log information written to the screen and file, or even controlling the name of the log output file. This feature is very powerful. Let's take a look at it:

Suppose we need to add the following additional information for each piece of information output to the console:

  1. Current time and date
  2. Class Name and method name for sending the message
  3. Log Level
  4. Log Content

Implementation is very simple:

<target name="c" xsi:type="Console" 
        layout="${longdate} ${callsite} ${level} ${message}"/> 

You can also output log information from different types to different files:

<target name="f" xsi:type="File" fileName="${logger}.txt"/> 

We can see that the $ {logger} layout Renderer is used in the filename attribute above. In this way, logs of different classes are output to different files with different class names, that is, the following log files are output:

  • Name.space.class1.txt
  • Name.space.class2.txt
  • Name.space.class3.txt
  • Other.name.space.class1.txt
  • Other.name.space.class2.txt
  • Other.name.space.class3.txt
  • ...

A very common requirement is to separate the daily log files. Use the $ {latest date} layout Renderer. This requirement is a piece of cake:

<target name="f" xsi:type="File" filename="${shortdate}.txt"/> 

Want to generate different log files for each employee? The layout Renderer of $ {windows-identity} can be easily implemented:

<target name="f" xsi:type="File" filename="${windows-identity:domain=false}.txt"/> 

In this way, nlog will output the log to a separate file based on the login information of each employee:

  1. Administrator.txt
  2. Marymanager.txt
  3. Edwardemployee.txt
  4. ...

Of course there are more complicated cases. The following configuration file generates a separate log file for each person every day and stores it in a time-sensitive directory:

<target name="f" xsi:type="File" 
        filename="${shortdate}/${windows-identity:domain=false}.txt"/> 

This configuration will generate some log files similar to the following:

  1. 2006-01-01/administrator.txt
  2. 2006-01-01/marymanager.txt
  3. 2006-01-01/edwardemployee.txt
  4. 2006-01-02/administrator.txt
  5. 2006-01-02/marymanager.txt
  6. 2006-01-02/edwardemployee.txt
  7. ...

Nlog provides a lot of la s with definitions, as detailed on the http://www.nlog-project.org/layoutrenderers.html page. Creating your own layout Renderer is also simple. It is still 15-20 lines of code. Please refer to the nlog documentation (documentation ).

 

Include files

Sometimes we need to split the nlog configuration file into several storage files. Nlog also supports reference and inclusion of other configuration files in a configuration file and processing them together at runtime. Like other parts of the nlog configuration file, we can use the familiar $ {var} tag. In this way, the corresponding configuration files can be intelligently loaded according to different environments. For example, the following example downloads the configuration files based on the computer name:

<nlog> 
  ... 
  <include file="${basedir}/${machinename}.config"/> 
  ... 
</nlog> 

Using variables can easily process complex expressions, or reference repeated expressions in a unified manner. We can use the <variable name = "Var" value = "XXX"/> expression to define a variable, after being defined, the variable can be used in various layout pasters. The syntax is also $ {var. For example:

<nlog> 
  <variable name="logDirectory" value="${basedir}/logs/${shortdate}"/> 
  <targets> 
    <target name="file1" xsi:type="File" filename="${logDirectory}/file1.txt"/> 
    <target name="file2" xsi:type="File" filename="${logDirectory}/file2.txt"/> 
  </targets> 
</nlog> 

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.