C # Use Log4Net for logging,

Source: Internet
Author: User

C # Use Log4Net for logging,

This article describes how to use Log4Net for logging and the advantages of Logging During program development:

  • It provides a precise environment for applications to run and allows developers to locate bugs in applications as soon as possible;
  • Once the Log output code is added to the program, logs can be generated and output during the program running without manual intervention.
  • Log information can be output to different places (such as the console and files) for future research.

Official description of Log4Net:

The Apache log4net library is a tool to help the programmer output log statements to a variety of output targets. log4net is a port of the excellent Apache log4j framework to the Microsoft. NET runtime. we have kept the framework similar in spirit to the original log4j while taking advantage of new features in. NET runtime.

Apache log4net is a class library that helps programmers output log statuses to multiple target platforms. Log4net is an excellent Implementation of the Apache log4jTM framework on the Microsoft. Net platform. While keeping the original idea of log4j, the new features of. Net are also used.

Log4Net is used in a program. It can be configured in the configuration file or defined by program code. This article mainly explains how to implement it through configuration.

Shows the configuration file structure:

The configuration file can be configured in app.config. after compilation, the corresponding program name "cmd.exe. config" will be generated, or it can be configured in an independent xml file.

If the configuration is in an independent xml file, you need to add a description in Assembly. cs, as shown below:

[Assembly: log4net. Config. DOMConfigurator (ConfigFile = "Log4NetConfig. xml", ConfigFileExtension = "xml", Watch = true)]

If the configuration is in App. config, in addition to configuring the log4net node, you must declare the node, that is, add the configSection node [the first element placed on the root node], as shown below:

<ConfigSections>
<Section name = "log4net" type = "log4net. Config. Log4NetConfigurationSectionHandler, log4net"/>
</ConfigSections>

The content of the generated log file is shown in:

Bytes -----------------------------------------------------------------------------------------

The Code is as follows:

1 using log4net; 2 using System; 3 using System. collections. generic; 4 using System. linq; 5 using System. text; 6 using System. threading. tasks; 7 8 [assembly: log4net. config. xmlConfigurator (Watch = true)] 9 namespace DemoLog4Net10 {11 /// <summary> 12 // log record 13 /// </summary> 14 public class LogHelper15 {16 /// <summary> 17 // /log instance 18 /// </summary> 19 private static ILog logInstance = LogManager. getLogger ("testApp"); 20 21 public static void WriteLog (string message, LogLevel level) {22 switch (level) {23 case LogLevel. debug: 24 logInstance. debug (message); 25 break; 26 case LogLevel. error: 27 logInstance. error (message); 28 break; 29 case LogLevel. fatal: 30 logInstance. fatal (message); 31 break; 32 case LogLevel. info: 33 logInstance. info (message); 34 break; 35 case LogLevel. warn: 36 logInstance. warn (message); 37 break; 38 default: 39 logInstance. info (message); 40 break; 41} 42} 43} 44 45 public enum LogLevel {46 Debug = 451 Error = Fatal = Info = Warn =} 52}
View Code

The independent configuration file is as follows:

 1 <?xml version="1.0" encoding="utf-8" ?> 2 <log4net> 3   <root> 4     <level value="DEBUG" /> 5     <appender-ref ref="LogFileAppender" /> 6     <appender-ref ref="ConsoleAppender" /> 7   </root> 8   <logger name="testApp"> 9     <level value="DEBUG" />10   </logger>11   <appender name="LogFileAppender" type="log4net.Appender.FileAppender" >12     <param name="File" value="${TMO}log-file.txt" />13     <StaticLogFileName value="false"/>14     <param name="AppendToFile" value="true" />15     <layout type="log4net.Layout.PatternLayout">16       <param name="Header" value="[Header]&#13;&#10;"/>17       <param name="Footer" value="[Footer]&#13;&#10;"/>18       <param name="ConversionPattern" value="%d [%t] %-5p %c [%x]  - %m%n"/>19     </layout>20     <filter type="log4net.Filter.LevelRangeFilter">21       <param name="LevelMin" value="DEBUG" />22       <param name="LevelMax" value="ERROR" />23     </filter>24   </appender>25   <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >26     <layout type="log4net.Layout.PatternLayout">27       <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />28     </layout>29   </appender>30 </log4net>
View Code


Additional:

How to Set environment variables:

System. Environment. SetEnvironmentVariable ("TMO", DateTime. Now. ToString ("yyyyMMdd "));

The log record priority is shown in the following table:

 

Level Allowed methods Boolean attribute Priority
OFF     Highest
FATAL Void Fatal (...); Bool IsFatalEnabled;  
RROR Void Error (...); Bool IsErrorEnabled;  
WARN Void Warn (...); Bool IsWarnEnabled;  
INFO Void Info (...); Bool IsInfoEnabled;  
DEBUG Void Debug (...); Bool IsDebugEnabled;  
ALL     Lowest
 

 

 

 

 

 

 

 

 

Note:

Log4net is indeed a widely used and easy-to-use logging framework. This article is a simple description and will continue to study other functions in the future.

 

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.