Are you often in Baidu when you run into problems with your program? Do you often ask someone when you run into an error? If there is a time to change, for a developer that is unprofessional performance, professional developer will first look at the program's running log, first from the log, analyze the cause of the problem, and then fix it. The most important thing here is the log, then you will be very curious, how these logs are recorded, secretly told you usually use the Log management framework. Then do you want to develop a program in the development of a log management module, do not worry about the following to introduce how to do log management.
As far as I know, the Log management framework has a variety of such as Enterprise, NLog, CLog, Log4net, which log4net powerful for large-scale project log management, NLog although less function but it is simple to use, and support intelligent induction, In addition enterprise is more powerful not to say, for large-scale system development, of course, use is also more difficult. However, given their strong use of resources and capabilities, our project finally identified the use of log4net, so the main use of log4net will be discussed in the next chapter.
first, log4net composition and configuration
From the Log4net API documentation is not difficult to see, in fact, the development process of log4net is quite simple, and is not as complex as imagined, and in use only need to add the appropriate configuration section information and then call the storage method to achieve the storage of the log, concrete structure such as
1.1 Composition explanation
It shows that log4net is composed of five parts, namely Logger,appenders, Filters, Layouts and object renders, in which the main Appender namespace encapsulates the storage of logs. That is, by configuring Appender to be able to output the log to the type of execution, layout is actually the format of the data display, the layout can be configured to output the specified template data information, it can also control the output type of the data (output XML or text type); Object Renders is important to control the custom output of the data, and log4net will output the logs in accordance with user-defined standards.
1.2 Configuration MethodsWhen using log4net, you first need to configure how the log is stored, and then call the static method of the Logmanager class in your code Getlog information about the object that holds the object. Where configuration information can be written to the config file, you can also customize an XML document, the specific configuration section information to write to the XML file.
Ii. methods of Use
Log4net has multiple storage levels, which are broadly divided into 5 categories according to the log information, namely error error log, fatal critical error log, info General information log, debug debug information log, and warn warning information log. In the log management can be based on the level of the log to consider the way, for serious logs are often a major problem of the system, you can consider the storage in the server database, some other logs can be considered to save to file, can improve server performance. Here are a few ways to use it.
2.1 Log output to database
The log output to the database is also frequently used by many systems of log storage method, in the process of small data to save the log in the database is feasible, but if the amount of log data to be processed is large then this storage method will reduce the performance of the database, so use caution when storing logs, It is recommended to use this storage method when it comes to major system problems, which can improve the performance of the database. The specific configuration is as follows:
<appender name= "Adonetappender_sqlserver" type= "log4net. Appender.adonetappender "> <buffersize value=" 1 "></bufferSize> <connectiontype value=" System.Data.SqlClient.SqlConnection, System.Data, version=2.0.0.0, Culture=neutral, publickeytoken= b77a5c561934e089 "/> <connectionstring value=" Data source=.;i Nitial catalog=test;integrated security=true; Pooling=false "/> <commandtext value=" INSERT into Log ([date],[thread],[level],[logger],[message]) VALUES (@log_ Date, @thread, @log_level, @logger, @message) "/> <parameter> <parametername value=" @log_date "/> &L T;dbtype value= "DateTime"/> <layout type= "log4net. Layout.patternlayout "value="%date{yyyy '-' mm '-' dd HH ': ' mm ': ' SS '. ' FFF} "/> </parameter> <parameter> <parametername value=" @thread "/> <dbtype value=" String " /> <size value= "255"/> <layout type= "log4net. Layout.patternlayout "value="%thread "/> </parameter> <parameter> <parametername value= "@log_level"/> <dbtype value= "String"/> <size value= "/>" <layout type= "log4net. Layout.patternlayout "value="%level "/> </parameter> <parameter> <parametername value=" @logger "/&G T <dbtype value= "String"/> <size value= "255"/> <layout type= "log4net. Layout.patternlayout "value="%logger "/> </parameter> <parameter> <parametername value=" @message "/ > <dbtype value= "String"/> <size value= "4000"/> <layout type= "log4net. Layout.patternlayout "value="%message "/> </parameter></appender>
In addition, beginners may have many problems writing to the database, the main thing is not to write data, this is mainly due to connectiontype and connectionstring reasons, to re-check the changes can be, In particular, the version of SqlConnection in ConnectionType, if not successfully written data is often caused by it.
2.2 Log output to fileIn addition, we can also output data to a file, the user can customize the type of file output, through the Datepattern tag to set the type and file name of the storage file, as shown in the following configuration:
<log4net> <!--definition output to file --<appender name= "Rollinglogfileappender" type= "log4net. Appender.rollingfileappender "> <file value=" d:\ "/> <appendtofile value=" true "/> < Rollingstyle value= "Date"/> <maxsizerollbackups value= "" "/> <datepattern value= " Yyyy-MM-dd ". Log ' "/> <staticlogfilename value=" false "/> <layout type=" log4net. Layout.patternlayout "> <conversionpattern value=" {%level}%date{mm/dd HH:mm:ss}-%message%newline "/> </layout> </appender> <root> <!--file Format-- < Appender-ref ref= "Rollinglogfileappender"/> </root></log4net>
This method creates the specified file under the specified directory and writes the log information to the created file.
2.3 Log output to consoleOutput to the console is no stranger, often in the Windows operating system can see the error message, this way can be very intuitive to tell the user error and cause, but this method is only the cache level, the system restarts when the error message will be deleted, Therefore, in the use of this method should be combined with the above mentioned method to synthesize storage log, enhance the robustness of the system.
<log4net> <!--definition output to console command line --<appender name= "Consoleappender" type= "log4net. Appender.consoleappender "> <layout type=" log4net. Layout.patternlayout "> <conversionpattern value="%date [%thread]%-5level%logger [%PROPERTY{NDC}]-% Message%newline "/> </layout> </appender> <root> <!--console control display log-- <appender-ref ref= "Consoleappender"/> </root></log4net>
2.4 Log output to eventThe above describes a few commonly used output, of course, log4net there are more output, here is a way to output to Windowsevent, this method will be the error message output to the Windows event, although not often used, but also can be used as a log storage.
<log4net> <!--define output to Windows Events --<appender name= "Eventlogappender" type= "log4net. Appender.eventlogappender "> <layout type=" log4net. Layout.patternlayout "> <conversionpattern value="%date [%thread]%-5level%logger [%PROPERTY{NDC}]-% Message%newline "/> </layout> </appender> <!--define the output medium of the log, the following defines the log output in four ways. You can also output the following by one type or other type. - <root> <!--Windows Event Log- <appender-ref ref= "Eventlogappender"/> </root></log4net>
by using the above configuration file to output the log to the specified type, but want to output the log is not only using the above configuration, in addition to call the method in the code to log the logs, as follows:
Using system;using system.collections.generic;using system.linq;using system.reflection;using System.Text;using System.threading.tasks;using log4net;using log4net. Appender; [Assembly:log4net. Config.xmlconfigurator (Watch = True)]namespace consoleapplication1{ class program { static void Main ( String[] args) { ILog log = log4net. Logmanager.getlogger (typeof (Program)); Log error logs . Error ("Error", New Exception ("An exception occurred")); Log critical Error log. Fatal ("Fatal", New Exception ("A fatal error occurred")); Log General Information . info ("info"); Logs debug Information log. Debug ("Debug"); Log the warning message . Warn ("Warn"); Console.WriteLine ("Logging is complete. "); Console.read ();}}}
All forms of configuration output above can be used to store log information using the GetLogger method during testing.
Note: There is a sentence in the code: [Assembly:log4net. Config.xmlconfigurator (Watch = True)] (at the namespace of the class that needs to use log4net), if not, it will be in the following message when debugging the "program debugging up isdebugenable" situation.
Third, log4net save nhibernate Log InformationIt is often necessary to parse SQL statements when using NHibernate, but the nhibernate default is not to output SQL script, so how can I see the SQL it generates? may wish to use the next log4net bar, log4net can output nhibernate operation, can be configured to output all level of nhibernate log information, the specific configuration method is as follows, here the configuration file in the external XML.
<?xml version= "1.0" encoding= "Utf-8"? ><log4net debug= "true" > <appender name= "rollingfile" type= " Log4net. Appender.rollingfileappender,log4net "> <param name=" File "value=" D:\log\log.txt "/> <param name=" AppendT Ofile "value=" false "/> <param name=" Rollingstyle "value=" Date "/> <param name=" Staticlogfilename "value=" True "/> <layout type=" log4net. Layout.patternlayout "> <param name=" Conversionpattern "value="%d [%t]%-5p%c-%m%n "/> </layout> </appender> <logger name= "NHibernate" additivity= "true" > <level value= "ERROR"/> <appender-ref ref= "Debugappender"/> </logger> <logger name= "Nhibernate.sql" additivity= "true" > <level value= "DE BUG "/> <appender-ref ref=" Debugappender "/> </logger> <logger name=" NHIBERNATE.ADONET.ABSTRACTBATC Her "additivity=" true "> <level value=" DEBUG "/> <appender-ref ref=" Debugappender "/> </logger> <root> <!--levels:debug, INFO, WARN, ERROR, FATAL--<level value= "DEBUG"/> < Level value= "INFO"/> <level value= "WARN"/> <level value= "ERROR"/> <level value= "FATAL"/> <appender-ref ref= "Rollingfile"/> </root></log4net>
The configuration information for log4net is placed in a separate XML file, so the configuration information needs to be added to the Log4net configuration class at run time, and its configuration is oftenGlobalof the fileApplication_Startevent that is addedconfiguration, the following code:
Using system;using system.collections.generic;using system.linq;using system.web;using System.Web.Security;using System.web.sessionstate;using medici.etam.data.nhibernatesessionmanagement;using NHibernate;using Nhibernate.context;namespace medici.etam.webservice{public class Global:System.Web.HttpApplication { private static log4net. ILog logger = log4net. Logmanager.getlogger ("Logger"); protected void Application_Start (object sender, EventArgs e) {//if The log4net is a lone file then it should be config log4net. Xmlconfigurator.configure (New FileInfo ("D:\\code\\etam\\etam\\etam_webservice_t16_v1.1\\data\\log4net.cfg.xml") ); } }}
Conclusionlog4net Log storage is very powerful, it makes a detailed classification of log information, a total of 5 classes, in the storage of logs can be based on the situation to selectively store, and according to the level of the choice of storage mode. In addition, similar to the log framework, such as nlog, clog, etc., can be based on the specific log situation to select the use of log storage framework.
Notepad for the program--log4net