Read Catalogue
- Features that the log system should have
- Log4net
- Configuration file: Log4net.config
- Initialization
- Output information
- Encapsulation of the Log4net
- Log4net.config Complex Configuration
Whether it's a Web application or a WinForm application, Visual Studio's debugging capabilities are strong enough to handle the various debugging requirements in development. However, for an application that has already been published, it is necessary to log the error, record the various status information in operation, and rely on the logging system.
Back to the top of the log system should have the features
A good logging system should have the following features:
1, stable operation. Because the function of the log is to output information when the system has various errors and anomalies, it must be robust and stable enough to perform its functions at all times.
2, wide applicability. Where log functionality is needed, it can be said everywhere in the program: ASPX pages, WinForm forms, class files, ashx pages, threads ... Therefore, the log system should be able to function in any location.
3, classification management. Logs should be divided into different levels of importance, such as info, Debug, Warning, Error, fatal, and so on. The user can decide what level of logging to output. When debugging, you can output as comprehensive information as possible, such as info, debug and other levels of information can be output. After deployment, only the levels above warning are output.
4, the output is rich. The log can be output in the user-specified format according to the user's needs.
Back to top of log4net
The above characteristics, in fact, is the characteristics of log4net. It originates from the famous log component log4j in the Java platform and is a very mature log system. Its version update is extremely slow, but even from the version released under. Net 1.0, in the back. NET version will work properly!
Since log4net is open source, it can be modified in a variety of ways. The official website address is http://logging.apache.org/log4net/
There are many articles about log4net, so there is no intention to repeat these details here. In the quickest realization of the goal, to achieve the goal must be a few key points to the point.
Back to top configuration file: Log4net.config
Log4net works very simply by using Log4net's corresponding method (from info to fatal) in the code to output the log information, and where does it end up? The output is controlled by the Log4net.config configuration file. So the importance of Log4net.config is key. Here is a typical configuration file, in fact, it is basically enough!
<?xml version= "1.0" encoding= "Utf-8"?><configuration> <log4net> <!--error log, Save to a file Error.log --<appender name= "Log" type= "log4net. Appender.fileappender "> <file value=" Log/log.txt "/> <appendtofile value=" true "/> < Layout type= "log4net. Layout.patternlayout "> <conversionpattern value=" [%date{yyyy-mm-dd hh:mm:ss}]%message-(%logger)% NewLine "/> </layout> <filter type=" log4net. Filter.levelrangefilter "> <param name=" levelmin "value=" DEBUG "/> <param name=" Levelmax "value = "FATAL"/> </filter> </appender> <root> <level value= "All"/> <appender-ref ref= "Log"/> </root> </log4net> </configuration>
Go back to the top of initialization
Log4net is a global base setting and must be initialized. differs in Web programs and form programs.
1. In the WinForm application, the following statements need to be displayed:
Log4net. Config.XmlConfigurator.ConfigureAndWatch (New System.IO.FileInfo (System.Windows.Forms.Application.StartupPath + "\ \log4net.config "));
2. The Web application can also be completed by invoking the initialization statement:
Log4net. Config.XmlConfigurator.ConfigureAndWatch (New System.IO.FileInfo (System.Web.HttpContext.Current.Server.MapPath (" ~ ") +" \\log4net.config ");
However, because Web applications do not have a clear entry point like WinForm applications, the initialization of Web programs often adds settings in Application_Start in Global.ascx, as follows:
void Application_Start (object sender, EventArgs e) {//code log4net run at application startup. Config.XmlConfigurator.ConfigureAndWatch (New System.IO.FileInfo (Server.MapPath ("~") + "\\log4net.config"));
So, for a web program, just add global.ascx and add code to the Application_Start.
Back to top output information
The main method of log4net output information is debug (), Error () and other methods, the key point is to get the logger object. There are several ways to get the logger object, which, after experimentation, can be applied to the output of normal and static classes using the following methods:
Perform a simple test in WinForm:
private void Button1_Click (object sender, EventArgs e) {log4net. Logmanager.getlogger (System.Reflection.MethodBase.GetCurrentMethod (). DeclaringType). Debug ("Information in a common class"); Sclass.staticfunc (); for (int i = 0; i < 5; i++) {(New Thread (test)). Start ();}} void Test () {log4net. Logmanager.getlogger (System.Reflection.MethodBase.GetCurrentMethod (). DeclaringType). Debug ("In Thread:" +thread.currentthread.managedthreadid.tostring ());}
The Staticfunc in Sclass is a simple static method with log information output. The final log is as follows:
In a Web application, a similar test can be done, proving that adaptability is good.
Back to the top of the log4net package
After a variety of tests, and finally found some general-purpose strong method, in order to prevent each time you have to come back to copy paste, or it is better to encapsulate it, in the Commoncode, with logger encapsulated the relevant functions of the log, as follows:
public class Logger{public static void Init (String configfile) {log4net. Config.XmlConfigurator.ConfigureAndWatch (New System.IO.FileInfo (ConfigFile));} public static void Winforminit ()//winform The initialization of the program {log4net. Config.XmlConfigurator.ConfigureAndWatch (New System.IO.FileInfo (System.Windows.Forms.Application.StartupPath + "\ \log4net.config "));} public static void Webinit ()//winform The initialization of the program {log4net. Config.XmlConfigurator.ConfigureAndWatch (New System.IO.FileInfo (System.Web.HttpContext.Current.Server.MapPath (" ~ ") +" \\log4net.config ");} public static void Debug (String info) {log4net. Logmanager.getlogger (System.Reflection.MethodBase.GetCurrentMethod (). DeclaringType). Debug (info);} public static void info (String info) {log4net. Logmanager.getlogger (System.Reflection.MethodBase.GetCurrentMethod (). DeclaringType). info (info);} public static void Error (String info) {log4net. Logmanager.getlogger (System.Reflection.MethodBase.GetCurrentMethod (). DeclaringType). Error (info);} public static void Fatal (String info) {LoG4net. Logmanager.getlogger (System.Reflection.MethodBase.GetCurrentMethod (). DeclaringType). Fatal (info);}}
The call to the web has to be modified Global.ascx, but the WinForm can be initialized by Wininit. As for the output information, you can
CommonCode.Logger.Debug (String)
In the form of output.
In Commoncode, log4net is a generic output mechanism, and the log output of various applications needs to be used, so, in most cases, Log4Net.dll and CommonCode.dll need to be put together.
Back to top log4net.config complex configuration
The output of the log4net is very powerful, and here are some of the configurations I used:
<?xml version= "1.0" encoding= "Utf-8"?><configuration> <log4net> <!--output to log file by date, no error message is logged-- > <appender name= "logappender" type= "log4net. Appender.rollingfileappender "> <file value=" log/logs_ "/> <appendtofile value=" true "/> < Rollingstyle value= "Date"/> <datepattern value= "yyyymmdd". txt" "/> <staticlogfilename value=" false "/> <layout type=" log4net. Layout.patternlayout "> <conversionpattern value=" [%date{hh:mm:ss}]%message-(%logger)%newline "/> &L t;/layout> <filter type= "log4net. Filter.levelrangefilter "> <param name=" levelmin "value=" DEBUG "/> <param name=" Levelmax "value=" WARN "/> </filter> </appender> <!--error log, save to a file Error.log--<appender name=" ERR Orlog "Type=" log4net. Appender.fileappender "> <file value=" log/error.log "/> <appendtofile value=" trUE "/> <layout type=" log4net. Layout.patternlayout "> <conversionpattern value=" [%date{yyyy-mm-dd hh:mm:ss}]%message-(%logger)%newline "/& Gt </layout> <filter type= "log4net. Filter.levelrangefilter "> <param name=" levelmin "value=" ERROR "/> <param name=" Levelmax "value=" FATAL "/> </filter> </appender> <!--output to Log2console and can be tracked in real time--<appender name=" T Olog2console "Type=" log4net. Appender.udpappender "> <param name=" Encoding "value=" Utf-8 "/> <param name=" remoteaddress "value=" 12 7.0.0.1 "/> <param name=" RemotePort "value=" 8003 "/> <layout type=" log4net. layout.xmllayoutschemalog4j "/> </appender> <root> <level value=" All "/> <appender -ref ref= "Logappender"/> <appender-ref ref= "errorlog"/> <appender-ref ref= "ToLog2Console"/> </root> </log4net> </configuratIon>
A brief description is as follows:
- Logappender: Output debug to warn information, stored in the log file Log_ timestamp. txt, and will be actively segmented as the file increases
- Errorlog: output error message only
- Tolog2console: Send logs to the network via UDP, you can receive them with Log2console, etc.