Nlog article series-Getting Started tutorial (II)

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 fourth article in The nlog article series, that is, the last article of the Getting Started tutorial. The following describes how to use nlog to write logs.

 

Automatic Reconfiguration

The nlog configuration file will be automatically loaded after the program starts. For some processes that will run for a long time (such as Windows service or ASP.. NET application), it is often necessary to temporarily raise the record level during the program running, but we do not want to restart the application. Nlog can automatically track the changes in its configuration file. Once the configuration file is modified, nlog will be automatically reloaded immediately. We can achieve this by setting <nlog autoreload = "true"/> in the configuration file. This Automatic Reconfiguration function will also be applied to the included files. That is to say, if the included files change, nlog will automatically reload the entire configuration file.

Log function troubleshooting

Although nlog has been configured, some problems still occur in the application, for example, there is no log output. The most common cause is the permission of asp.net--asp.net's aspnet_wp.exeor w3wp.exe may not have the write permission for the specified directory in the nlog configuration file. Nlog has a strong monitoring capability for exceptions in its own operation. The following settings can output the monitoring results to a specified location or handle these exceptions (the default settings will ignore their own exceptions ):

  • <Nlog throwexceptions = "true"/>-When nlog throws an exception, this option can throw the exception back to the log caller. In the development process, this setting will become very useful and can help us quickly locate the exception and its causes. When the program is developed and deployed to the application environment, set throwexceptions to false as soon as possible to avoid nlog exceptions causing the entire application to crash.
  • <Nlog internallogfile = "file.txt"/>-enable nlog to write the log information (including possible exceptions) in its running process to the file.
  • <Nlog internalloglevel = "trace | debug | info | warn | error | fatal"/>-select the record level for writing internal logs. The higher the level, the smaller the corresponding output log file.
  • <Nlog internallogtoconsole = "false | true"/>-send internal log information to the console.
  • <Nlog internallogtoconsoleerror = "false | true"/>-send internal log information to stderr ).

Asynchronous processing, package (warpper), and composite output target

The nlog package and the composite output Target Feature allow us to modify the default behavior of the output target, which is reflected in the following aspects:

  • Asynchronous processing (the output to the target will be processed by a separate thread)
  • Automatic retry upon exception
  • Load Balancing
  • Cache
  • Filter
  • Standby output target (enable the standby output target when the primary output target fails)
  • Others, see http://www.nlog-project.org/targets.html

You only need to nest several target nodes in the configuration file to complete the definition of the wrapper or composite output target. The nested depth is unlimited. For example, to add asynchronous processing and automatic retry for an output target, you only need to configure nlog according to the following code:

<targets> 
  <target name="n" xsi:type="AsyncWrapper"> 
    <target xsi:type="RetryingWrapper"> 
      <target xsi:type="File" fileName="${file}.txt"/> 
    </target> 
  </target> 
</targets> 

Asynchronous processing is very common. Therefore, nlog provides a shorthand method, namely <targets async = "true"/>, which automatically applies the asyncwrapper package to the output target.

 

Configuration by programming

In some cases, we may not want to use the configuration file to configure nlog, but choose to use the nlog configuration API. The detailed introduction to these Apis is beyond the scope of this article, so we will only briefly introduce them here. To configure nlog programmatically, We need:

  1. Create a loggingconfiguration object to save configuration information
  2. Create at least one output target object
  3. Set the attributes of the output target object
  4. Set the loggingrule object and add it to the loggingrules set of the loggingconfiguration object
  5. Enable this loggingconfiguration object (set logmanager. configuration to this loggingconfiguration object)

The following code snippet creates two output target objects programmatically-consoles and files supporting colors, and sends the log information with the record level equal to or higher than debug to these two output targets:

using NLog; 
using NLog.Targets; 
using NLog.Config; 
using NLog.Win32.Targets; 
 
class Example 
{ 
    static void Main(string[] args) 
    { 
        // Step 1. Create configuration object 
         
        LoggingConfiguration config = new LoggingConfiguration(); 
         
        // Step 2. Create targets and add them to the configuration 
 
        ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget(); 
        config.AddTarget("console", consoleTarget); 
         
        FileTarget fileTarget = new FileTarget(); 
        config.AddTarget("file", fileTarget); 
         
        // Step 3. Set target properties 
         
        consoleTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}"; 
        fileTarget.FileName = "${basedir}/file.txt"; 
        fileTarget.Layout = "${message}"; 
         
        // Step 4. Define rules 
         
        LoggingRule rule1 = new LoggingRule("*", LogLevel.Debug, consoleTarget); 
        config.LoggingRules.Add(rule1); 
 
        LoggingRule rule2 = new LoggingRule("*", LogLevel.Debug, fileTarget); 
        config.LoggingRules.Add(rule2); 
         
        // Step 5. Activate the configuration 
 
        LogManager.Configuration = config; 
         
        // Example usage 
 
        Logger logger = LogManager.GetLogger("Example"); 
        logger.Trace("trace log message"); 
        logger.Debug("debug log message"); 
        logger.Info("info log message"); 
        logger.Warn("warn log message"); 
        logger.Error("error log message"); 
        logger.Fatal("fatal log message"); 
    } 
}

 

What else can nlog do?

Nlog supports some more logging scenarios, which couldn't be fully described here. See the links below for more information:

In addition, nlog supports more complex scenarios that require logging. It cannot be listed here. If you are interested in it, you can refer to the following link:

  • Exception logging-http://sourceforge.net/mailarchive/forum.php? Thread_id = 6766833 & forum_id = 41984
  • Conditional Expression Language-http://www.nlog-project.org/conditions.html
  • Nlogviewer-real-time log record Viewer (currently in the pre-alpha phase)-http://viewer.nlog-project.org/

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

 

Notes

Crazycoder will be added to the nlog document translation process. He has completed the translation of the nlog configuration file, which will be released soon. I am very grateful to crazycoder for his selfless dedication!

For some reason, I will be busy again this time ............ This blog may not be updated as frequently as this month. Of course, I will try my best to reply to this blog as soon as possible. Thank you for your consistent support!

Although reluctant, it is very likely that this "nlog article series" cannot be written further ...... I really hope that enthusiastic friends can participate in the development of the open-source community, learn new knowledge, and communicate with friends, by the way, you can improve your English skills.

If you are willing to give yourself a little time to participate in nlog article series translation, please contact me. After participating in the translation, if you have the ability and willingness, I would like to do my best to help you contact the publishing house and translate and publish real books.

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.