Log4net Introduction
Log4net is Apache's next open source project, which is a cloned version of log4j. We can control the output destination of the log information. A variety of log information output modes are defined in log4net. It can output logs to the console, text files, Windows log Event Viewer, including databases, mail, and so on as needed so we quickly track program bugs.
Log4net provides 7 log levels from high to the bottom:off > FATAL > ERROR > WARN > INFO > DEBUG > All
Log4net has 3 main members, loggers, appenders and layouts.
- Logger Introduction
Logger is the logger responsible for logging, assuming that we need to record some normal runtime logs and error log when the exception occurs, we can add two logger implementations in the configuration file. Logger is primarily used to record the classification of logs and the level of control logs. It can output log information in a variety of formats, and it can also control the output level of the log. Log4net uses the inheritance system, i.e. if there are two logger, the names are A.B.C and a.b respectively. Then A.B is the ancestor of A.B.C. Each logger inherits the attributes of its ancestors.
- Appender Introduction
Provide logging output source, we can output the log to the console, text files, Windows Log Event Viewer (view in Window Log > Application), database, mail, etc. These output sources are configured with Appender to implement.
It is not recommended to save log files to the database because it is difficult to use SQL to troubleshoot logs, preferably a log management service or Elasticsearch that saves log files, which can provide good full-text indexing and other features.
- Layout Introduction
Layout is used to control the output format of the Appender.
Patternlayout conventions for string conversion interpretation in Layout
%m,%message output log message%d,%datetime output the moment the current statement runs, format%date{yyyy-mm-dd hh:mm:ss,fff}%r,%timestamp The number of milliseconds that the output program consumes from running to executing to the current statement%p, the current priority level of the%level log,%c,%logger the name of the current log object%l, the line number where the%line output statement resides %F,%file the file name of the output statement, warning: only valid when debugging, calling local information can affect performance%a,%appdomain the name of the application domain that raised the log event. %c,%class,%type the full name of the class that raised the log request, Warning: Performance%exception exception information%u,%identity the name of the currently active user,%identity return is empty when I test Of Warning: The name space, class name, method, line number that will affect performance%l,%location raises log events. Warning: Affects performance, relies on PDB file%M,%method method name of log request, Warning: Performance%n,%newline line break%x,%NDC NDC (nested D Iagnostic context)%x,%MDC,%P,%properties, etc.%property%property output {log4net:identity=, log4net:username= , log4net:hostname=}%t,%thread the thread that raised the log event, and uses the thread number if there is no thread name. %w,%username the current user's WindowsIdentity, similar to: Hostname/username. Warning: The UTC time that will affect performance%utcdate the log event occurs. For example:%UTCDATE{HH:MM:SS,FFF} percent output a scoreNo.
For more information, please refer to: http://logging.apache.org/log4net/release/sdk/html/T_log4net_Layout_PatternLayout.htm
How to use
Take the ASP. NET MVC Project as an example
1. Using Nuget to install Log4net,
1 |
PM> Install-Package log4net |
2. Create the Log4net.config configuration file and modify the file's properties "Copy to Output directory" to "Always copy"
<?xml version= "1.0" encoding= "Utf-8"?><configuration> <configSections> <section name= "Log4net" Type= "Log4net. config.log4netconfigurationsectionhandler,log4net-net-2.0 "/> </configSections> <log4net> <root > <level value= "All"/> <appender-ref ref= "Logfileappender"/> <!--<appender-ref ref= " Eventlogappender "/>--> </root> <!--definition output to file--<appender name =" Logfileappender "type=" log4n Et. Appender.rollingfileappender "> <!--definition file storage location-<param name=" file "value =" App_data\ "/> <p Aram Name= "Appendtofile" value= "true"/> <param name= "maxsizerollbackups" value= "+"/> <param name = "MaxFileSize" value= "10240"/> <param name= "Staticlogfilename" value= "false"/> <!--file name format-- <param name= "Datepattern" value= "yyyy. Mm.dd '. txt ' "/> <param name=" rollingstyle "value =" Date "/> <!--not exclusiveLogging, locked only within the shortest time that each log is logged, because the deployment to the server encountered a file that was occupied unable to download the log--<lockingmodel type= "log4net. Appender.fileappender+minimallock "/> <layout type=" log4net. Layout.patternlayout "> <!--define output format-<!--example 2018-08-20 12:10:49,348-thread id:[21] Log level: [INFO]: [Day Log information]--> <param name= "Conversionpattern" value= "%date thread Id:[%thread" Logging level: [%-5level]: [%message]%newline]/> ; </layout> <!--filtering level FATAL > ERROR > WARN > INFO > Debug--> <filter type= "log4net. Filter.levelrangefilter "> <param name=" levelmin "value=" DEBUG "/> <param name=" Levelmax "value=" FATAL "/> </filter> </appender> <!--define output to Windows events--<appender name=" Eventlogapp Ender "Type=" log4net. Appender.eventlogappender "> <layout type=" log4net. Layout.patternlayout "> <conversionpattern value="%date [%thread]%-5level%logger [%PROPERTY{NDC}]-%message %newline "></conversionpattern> </layout> </appender> </log4net></configuration>
3. Create a Loghelper class that provides a way to log records
View Code
4. Load your Log4net.config file in the Global.asax file Application_Start method and call the Loghelper class to test the logging.
log4net. Config.XmlConfigurator.Configure (New FileInfo (Server.MapPath ("~/log4net.config"));
LogHelper.Default.WriteInfo ("AppStart"); LogHelper.Default.WriteWarning ("Warning"); LogHelper.Default.WriteError ("Error"); LogHelper.Default.WriteFatal ("Fatal"); Try { int a = 3/4; int r = 4/a; } catch (Exception ex) { LogHelper.Default.WriteError (ex. Message, ex); }
5. Log
Problems that you may encounter
Since Log4net is the exclusive file by default, if the program is deployed on FTP space and you need to download the log file, you will find that you cannot download it (process is occupied) and you need to change the lockingmodel of the Appender (output source) .
For more Lockingmodel information, please refer to https://logging.apache.org/log4net/release/sdk/html/P_log4net_Appender_FileAppender_LockingModel.htm
<!--does not record the log exclusively, it is locked only in the shortest time that each log is recorded, because deployment to the server encounters a file that is occupied unable to download the log--><lockingmodel type= "log4net. Appender.fileappender+minimallock "/>
Sample Download
ASP. NET MVC uses log4net to log logs