1. Overview
The log4net library is an implementation of the Apache log4j framework on the Microsoft .NET platform. It is a tool that helps programmers output log information to various targets (console, file, database, etc.).
1. Download and version
Apache log4net ™, the latest version log4net 2.0.8
2. The structure of Log4net
log4net has four main components, namely Logger, Repository, Appender and Layout.
3. Log level
If no value of LEVEL is defined, the default is DEBUG.
- The highest OFF level
- FATAL
- RROR
- WARN
- INFO
- DEBUG Default
- The lowest level of ALL
For example: define a log object and set the level to INFO, which means that logs with a higher (or equal) level than INFO will be recorded. That is ("XX") will record, ("**") will not record
2. Create log4net configuration file
config/file:
<log4net> <root> <level value="INFO" /> <appender-ref ref="RollingFileAppender" /> <appender-ref ref="ColoredConsoleAppender" /> </root> <logger name="MessageHandler"> <level value="ERROR" /> <appender-ref ref="SmtpAppender" /> </logger> <appender name="RollingFileAppender" type=""> <file value="Log\pamsdc" /> <threshold value="INFO" /> <appendToFile value="true" /> <rollingStyle value="Composite" /> <datePattern value="yyyyMMdd" /> <maxSizeRollBackups value="100"></maxSizeRollBackups> <layout type=""> <header value="[Header]" /> <footer value="[Footer]" /> <conversionPattern value="%date [%thread] %-5level %logger [%ndc] <%property{auth}> - %message%newline" /> </layout> </appender> <appender name="ColoredConsoleAppender" type=""> <mapping> <level value="WARN" /> <foreColor value="White" /> <backColor value="Red, HighIntensity" /> </mapping> <layout type=""> <header value="[Header]" /> <footer value="[Footer]" /> <conversionPattern value="%date [%thread] %-5level %logger [%ndc] <%property{auth}> - %message%newline" /> </layout> </appender> <appender name="SmtpAppender" type=",log4net"> <to value="" /> <from value="GPEHZ-MIS@GoldPeak" /> <subject value="PAMS DC Fatal Error" /> <smtpHost value="192.50.6.248" /> <bufferSize value="32" /> <lossy value="true" /> <Authentication value="Basic"/> <Username value="GPEHZ-MIS@GoldPeak"/> <Password value=""/> <evaluator type=",log4net"> <threshold value="ERROR" /> </evaluator> <layout type=",log4net"> <conversionPattern value="date:%date Thread:[%thread] level: %-5level kind:%logger [%ndc] < %property{auth}> - information:%message%newline" /> </layout> </appender> </log4net>
1. Configuration file
Configuration information is generally placed in a separate configuration file, or in a program configuration file, such as or. or any file.
The log4net framework will look for configuration files under the directory path defined relative to the attribute.
The only identifier that the framework is looking for in the configuration file is the label. An example of a complete configuration file is as follows:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type=".Log4NetConfigurationSectionHandler, log4net-net-1.0" /> </configSections> <log4net> .. </log4net> </configuration>
2、Logger
Logger is the main component that applications need to interact with, and it is used to generate log messages. The generated log message is not displayed directly, and it must be formatted in advance by Layout before it will be output.
Logger provides multiple ways to record a log message. You can create multiple loggers in your application. Each instantiated Logger object is maintained by the log4net framework as a named entity. This means that in order to reuse the Logger object, you don't have to pass it between different classes or objects, just call it with its name as a parameter.
The log4net framework uses an inheritance system, and all log objects in the framework system are descendants of the root logger. That is, if there are two loggers, respectively defined as sum, then we say it is the ancestor. Each logger inherits the attributes of the ancestors. This default inheritance method can also be changed by explicitly setting the tag's addition property to false.
The Log4net framework defines an ILog interface, and all logger classes must implement this interface. If you want to implement a custom logger, you must first implement this interface.
The Log4net framework defines a class called LogManager to manage all logger objects. It has a GetLogger() static method that uses the name parameter we provide to retrieve the existing Logger object. If the Logger object does not exist in the framework, it will also create a Logger object for us. The code is as follows:
log = ("logger-name");
Generally speaking, we call GetLogger() with the type (type) of the class as the parameter to track the class we are logging.
3、Appender
A good logging framework should be able to produce multi-destination output. For example, output to the console or save to a log file. log4net can meet these requirements well. It uses a component called Appender to define the output media. As the name suggests, these components attach them to the Logger log component and pass the output into the output stream. You can attach multiple Appender components to a log object. The Log4net framework provides several Appender components.
A complete list of Appender components provided by log4net can be found in the help manual of the log4net framework. With these ready-made Appender components, generally speaking, there is no need to write them yourself. But if you want, you can inherit from the class.
Examples of various Appender configurations for log4net
/log4net/release/
The output methods mainly include:
- AdoNetAppender: Record the logs to the database. SQL and stored procedures can be used
- AspNetTraceAppender: Can view recorded logs in a tracking way.
- BufferingForwardingAppender: Cache log events before output to subAppenders.
- ColoredConsoleAppender: Write down high-bright log events in the terminal window.
- ConsoleAppender: Output logs to the console.
- EventLogAppender: Write the log to the log of the Windows operating system.
- FileAppender: Write the log to the file.
- ForwardingAppender: Used to specify a set of constraints for an Appender.
- MemoryAppender: Store the logs in the memory buffer.
- NetSendAppender: Output logs to Windows Messenger service, and these log information will be displayed in the dialog box of the user terminal.
- OutputDebugStringAppender: Configure this Appender to write logs to the OutputDebugString API.
- RemotingAppender: Write logs to the remote receiver through .NET Remoting.
- RollingFileAppender: Write the log into the file in the form of a rollback file.
- SmtpAppender: Write the log to the email.
- SmtpPickupDirAppender: The configuration is similar to SmtpAppender, but you need to replace SmtpHost with PickupDir.
- TraceAppender: Write the log to the .NET trace system.
- UdpAppender: Send the log connectionless UDP datagrams to the remote host or broadcast in the form of UdpClient.
4. Conversion mode in PatternLayout
- %F/%file: The file name where the output statement is located
- %U/%identity:username
- %l/%location:Caller location
- %L/%line: The line number where the output statement is located
- %M/%method:method
- %C(class),%class,%type::Class name
- %w/%username:Windows Identity
- %a/%appdomain:domain
- %t/%thread:The thread ID of the current statement
- %c(category), %logger::The name of the current log object
- %p(priority),%level: The current priority level of the log, namely DEBUG, INFO, WARN, etc.
- %m/%message: The output log message, such as a message output by (…)
- %exception:abnormal
- %d,%date: Output the time when the current statement is running, the default format is ISO8601, and you can also specify the format afterwards, such as: %d{yyy-MM-dd HH:mm:ss }, output 2015-03-10 14:53:28; %d{ISO8601} output 2015-03-10 14:51:12,220, %d{DATE} output ‘10 Mar 2015 14:51:51,318’, %d{ABSOLUTE} output 14:54:07,943,%d{HH:mm:ss,ffff}, %d{dd MM yyyy HH:mm:ss,ffff},yyyyy Year, MM month, dd date, HH hour 24 system, hh hour 12 hour system, mm minutes, ss seconds, ffff milliseconds (f is the exact number of seconds, several f represents the exact number of digits after the decimal point)
- %r/%timestamp: Output the number of milliseconds the program consumes from running to executing to the current statement
- %X/%mdc:Output (mapped diagnostic context) mdc context content
- %x/%ndc: Output (nested diagnostic context) ndc context content
- %p/%Proerties{user}: renders the specified attribute
- %n(newline): line break
- %-Number: indicates the minimum length of the item. If it is not enough, fill it with spaces. %-10 means the minimum length is 10. If it is not enough, fill it with the right side of the space; %.10 means the maximum length is 10; it can be used in combination with other formats such as %m, example %10m, %-10m, %10.10m, %-10.10m
- %%: Output %
For example, a PatternLayout with conversion mode %r [%t]%-5p %c - %m%n will generate an output similar to the following:
176 [main] INFO - Located nearest gas station.
3. Define configuration files
After we create the above configuration file, we need to connect it to our application next. By default, each independent executable assembly defines its own configuration.
The log4net framework uses the configuration file to define the assembly level.
- ConfigFile: indicates the path and file name of our configuration file, including the extension.
- ConfigFileExtension: If we use a different file extension for the assembly of the compiled program, then we need to define this property. By default, the assembly's configuration file extension is "config".
- Watch (Boolean property): The log4net framework uses this property to determine whether it is necessary to monitor file changes at runtime. If this property is true, FileSystemWatcher will be used to monitor file changes, renaming, deletion and other events.
1. In Winfrom, add the following code:
[assembly: (ConfigFile = "", Watch = true)]//Affiliated files//or[assembly: (ConfigFileExtension = "log4net", Watch = true)]//The key is.log4netor.log4net,And monitor changes。
2. In, add to the Application_Start method in the file:
(new ("")); //or(new FileInfo((@”Config.”)))
4. Call log4net to write log
1. Create or obtain log objects
The log object will use the Name property of the Logger defined in the configuration file. If a log object is not defined in the configuration file in advance, the framework will obtain the attributes of the ancestor node based on the inheritance structure, and finally, the attributes will be obtained from the root root log. As shown below:
log = ("MyLogger"); //or log = (typeof(_Default)); //or log = (().DeclaringType);
2. Output log information
if () ("message"); if () ("message); ()//Close the log
5. Change Appender settings
1. Get the root Appender
h = ()(); ac = ;
2. Get the Appender for the specified Logger: Excluding inherited Appender
logger = (typeof(_Defaut)); ac = (()).Appenders;
3. Change Appender settings
for (int i = 0; i < ; i++) { rfa = ac[i] as ; if (rfa != null) { = "";//Dynamic setting of the file name of the log log when the program is running = new (, , ); } }
6. Custom appender
The log is stored in memory and the data is posted to the server after reaching a certain threshold. At the same time, the address of the server receiving data can be configured.
1. Define myMemAppender class
public class MyMemAppender : AppenderSkeleton { private ArrayList eventQueue; public string RemoteAddress { get; set; } public int QueueSize { get; set; } public MyMemAppender() : base() { eventQueue = new ArrayList(); } protected override void Append( loggingEvent) { lock () { (loggingEvent); if ( >= QueueSize) { lock () { SaveToServer(); (); } } } } private void SaveToServer() { lock () { List logList = new List(); foreach ( evt in eventQueue) { try { LogModel m = ();//or as LogModel (m); } catch (Exception ex) { (()); continue; } } //Upload logList serialization to remoteAddress } } virtual public LoggingEvent[] GetEvents() { lock () { return (LoggingEvent[])(typeof(LoggingEvent)); } } }
2. Register Appender
(1) Add it in the root directory
Configuration file method:
<?xml version="1.0" encoding="utf-8" ?> <log4net debug="true"> <appender name="myMemAppender" type=""> <param name="QueueSize" value="10"/> <param name="RemoteAddress" value="http://localhost/"/> </appender> <root> <level value="ALL"/> <appender-ref ref="myMemAppender" /> </root> </log4net>
Code method:
MyMemAppender appender = new MyMemAppender(); = 5; = "http://localhost:57427/"; (appender); ILog log = (().DeclaringType);
(2) Specify the appender to the Logger name:
MyMemAppender appender = new MyMemAppender(); = "MyMemAppender"; = 5; = "http://localhost:57427/"; Logger logger1 = (Logger)(().DeclaringType); = ; IAppender appendered = ("MyMemAppender"); if (appendered != null) ("MyMemAppender"); (appendered); ();
This is all about this article about C# using log component log4net. I hope it will be helpful to everyone's learning and I hope everyone will support me more.