Nlog class library usage-detailed configuration

Source: Internet
Author: User
1. configuration file locations)

By scanning common directories at startup, nlog will try to use the found configuration information for automatic self-configuration.

1.1 separate *. EXE Client

For a separate client, nlog searches for configuration information in the following directory:

  1. Standard Program configuration file (usuallyProgram name. EXE. config)
  2. Under the Program directoryProgram name. EXE. nlogFile
  3. Under the Program directoryNlog. configFile
  4. Under the directory where nlog. dll is locatedNlog. dll. nlogFile (if nlog does not import GAC)
1.2 ASP. NET Program

The directories searched in the ASP. NET project include:

  1. Standard Web program configuration fileWeb. config
  2. AndWeb. configIn the same directoryWeb. nlogFile
  3. Under the Program directoryNlog. configFile
  4. Under the directory where nlog. dll is locatedNlog. dll. nlogFile (if nlog does not import GAC)
  5. If the nlog_global_config_file environment variable is defined, the file to which the variable points
1.2 hardware equipment Library (. NET Compact framework)

. NET Compact framework does not support program configuration files (*. EXE. config) and environment variables, so nlog will only scan these places:

  1. Under the Program directoryNlog. configFile
  2. Under the directory where nlog. dll is locatedNlog. dll. nlogFile (if nlog does not import GAC)
Conclusion 1.4

From the above, no matter which configuration file we name it nlog. config and put it in the application directory, we can certainly scan it, haha.

2. Configuration File Format 2.1 nlog supports two configuration file formats
  1. The configuration information is embedded in the *. EXE. config or web. config file of the. NET application standard.
  2. Stored in an independent File

First, we are familiar with the general configuration, using configsections

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

If the second type is a separate XML file, you need to configure it as follows:

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

It should be noted that the root node is <nlong> </nlong> and the two namespaces are optional. But for intelligent sensing, write it down.

2.1 configure sub-elements
  • <Targets/>-Defines log targets/outputs: declare the target
  • <Rules/>-Defines log routing rules: declares a rule.
  • <Extensions/>-loads nlog extensions from the *. dll file to load the dll extension (in fact, I don't understand it, I never used it)
  • <Include/>-includes external configuration file contains an external configuration file
  • <Variable/>-sets the value of a configuration variable assigns a value to the configuration variable.

It must be noted that the first two elements, targets and rules, must be configured. The remaining elements are optional and should be used for more complex configurations. I have never used them again.

3. Targets)

The first article has been introduced, should no longer explain, specific output to the detailed configuration of the target, see the document: https://github.com/nlog/NLog/wiki/Targets

4. Routing rules (Rules)

<Rules/> the region defines the log routing rules. Each route table item is a <logger/> element. <Logger/> has the following attributes:

  1. Name-log source/Recorder name (wildcard * is allowed *)
  2. Minlevel-minimum level of the log range matched by this rule
  3. Maxlevel-the highest level of the log range that the rule matches
  4. Level-the single log level matched by this rule
  5. Levels-a series of log levels matched by this rule, separated by commas.
  6. Writeto-a series of targets that logs should be written for rule matching, separated by commas.
  7. Final-mark the current rule as the last rule. The subsequent rules will not be instantly matched.

For example:

  1. <Logger name = "name. space. class1 "minlevel =" debug "writeto =" f1 "/>-namespace name. all log information of the class1 class under space equal to or higher than debug is written to the "f1" target.
  2. <Logger name = "name. space. class1 "levels =" debug, error "writeto =" f1 "/>-namespace name. all log information of the class1 class under space equal to debug or error is written to the "f1" target.
  3. <Logger name = "name. space. * "writeto =" F3, F4 "/>-namespace name. all levels of log information of all classes in space are written to the "F3" and "F4" targets.
  4. <Logger name = "name. space. * "minlevel =" debug "maxlevel =" error "final =" true "/>-namespace name. the log information of all classes in space between debug and error (including debug, info, warn, and error) is not recorded (because this rule does not define writeto ), other subsequent rules will also be ignored (because final = "true" is set here ").
5. layouts and layout renderers)

One of the most powerful nlog functions is to use layouts. Syntax: "$ {attribute}" is composed of text surrounded by tags. This tag is also called layout renderers. We can use it to insert context-related information into the log information. La s can be applied in many places. For example, they can be used to control the format of output to screen or write file information, or to control file names.

Assume that we want each information output to the console to contain the following information:

  • Current date and time
  • Name of the class and method that generates log information
  • Log Level
  • Log Content

Layout is easy to implement: As mentioned above:

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

Use layout to control the output file name:

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

Use date to differentiate log files. If you use the layout generator $ {1_date:

<target name="f" xsi:type="File" fileName="${shortdate}.txt"/>
For more layout generators, refer to the official documentation:

Https://github.com/nlog/NLog/wiki/Layout%20Renderers

6 include files)

We have such a requirement that we do not want to make the nlog. cofige file too large, too large, and too tired to read. We can split it. How can we split the config into several small ones? Using include is simple.

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

Specify the location of the config file to be included.

7 Variables)

Variables can also be defined in the configuration file. The example above is very clear:

// Declaration syntax
<variable name="var" value="xxx" /><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>
8. Automatic Reconfiguration)

It sounds really hard to understand. But there is nothing. In other words, once the program is started, after the nlog. config file is read, the configuration file will no longer be read after the program is started. If we don't want to stop the program, for example, how can we say that the server stops. This configuration is used. The configuration function is that once you modify the configuration file, the program will re-read the configuration file, that is, automatically re-configure. Directly run the Code:

<nlog autoReload="true">   ...</nlog>
9. troubleshooting Logging)

The program is okay, but the log is faulty. What should I do? What is wrong? What should I do if the log itself exists in addition to bugs? This requires log troubleshooting. Write the error information of the log into the log.

  • <Nlog throwexceptions = "true"/>
  • <Nlog internallogfile = "file.txt"/>-Setting the internallogfile attribute allows nlog to write internal debugging and exception information to the specified file.
  • <Nlog internalloglevel = "trace | debug | info | warn | error | fatal"/>-determines the level of internal logs. The higher the level, the simpler the output log information.
  • <Nlog internallogtoconsole = "false | true"/>-whether to output internal logs to the standard console.
  • <Nlog internallogtoconsoleerror = "false | true"/>-whether to output internal logs to the stderr console ).

Setting the throwexceptions attribute to "true" can prevent nlog from blocking such exceptions, but throw them to the caller. This can help us quickly locate problems during deployment. Once the application has been correctly configured, we recommend that you set the throwexceptions value to "false" so that the application will not crash due to log issues.

10. asynchronous Processing)

The principle is not to mention. directly add the Code to make it capable of asynchronous processing.

<nlog>  <targets async="true">    <!-- all targets in this section will automatically be asynchronous -->  </targets></nlog>
11 default encapsulation (default wrappers)

We want to use the same encapsulation to process all the targets, such as adding buffering and/or automatic retry functions.

For this reason, nlog provides a special Syntax: <default-wrapper/>. You only need to put this element in the <targets/> area, and then all the targets will automatically load the same encapsulated target. Note that <default-wrapper/> is only valid for the current <targets/> region, and you can use multiple <targets/> regions, in this way, you can group the target and process it with different encapsulation targets.

<nlog>    <targets>      <default-wrapper xsi:type="BufferingWrapper" bufferSize="100"/>      <target name="f1" xsi:type="File" fileName="f1.txt"/>      <target name="f2" xsi:type="File" fileName="f2.txt"/>    </targets>    <targets>      <default-wrapper xsi:type="AsyncWrapper">        <wrapper-target xsi:type="RetryingWrapper"/>      </default-wrapper>      <target name="n1" xsi:type="Network" address="tcp://localhost:4001"/>      <target name="n2" xsi:type="Network" address="tcp://localhost:4002"/>      <target name="n3" xsi:type="Network" address="tcp://localhost:4003"/>    </targets>  </nlog>

In the above example, we define two buffer file targets and three asynchronous and automatic retry network targets.

12 default target parameters)

In fact, the default is to unify the scattered definition in one region. It is just a syntactic sugar problem. The default parameter is to abstract the same parameters into one region for unified definition. The following code is equivalent.

<nlog>   <targets>     <target name="f1" xsi:type="File" fileName="f1.txt" keepFileOpen="false"/>     <target name="f2" xsi:type="File" fileName="f2.txt" keepFileOpen="false"/>     <target name="f3" xsi:type="File" fileName="f3.txt" keepFileOpen="false"/>   </targets> </nlog>
<nlog>  <targets>    <default-target-parameters xsi:type="File" keepFileOpen="false"/>    <target name="f1" xsi:type="File" fileName="f1.txt"/>    <target name="f2" xsi:type="File" fileName="f2.txt"/>    <target name="f3" xsi:type="File" fileName="f3.txt"/>  </targets></nlog>

Nlog class library usage-detailed configuration

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.