. NET log records of--log4net focus

Source: Internet
Author: User
Tags syslog log4net


. NET logging of--log4net highlights 1. Overview


Log4net is. NET next to a very good open source logging component. Log4net logging is a very powerful feature. It can be divided into different levels of the log, in different formats, output to different media.


Main components of 2.log4net 2.1 appenders


Appenders is used to define the output of the log, that is, the log to be written to that medium up. The more commonly used log4net has been implemented, directly in the configuration file can be called, see the configuration file example above, of course, you can also write one, need from log4net. Appender.appenderskeleton class inheritance. It can also be configured with filters and layout to implement the filtering and output format of the log.



The output methods that have been implemented are:


AdoNetAppender logs the logs to the database. You can use both SQL and stored procedures.

AnsiColorTerminalAppender highlights the log output to the ANSI terminal.

AspNetTraceAppender can view the recorded logs by using Trace in asp.net.

The BufferingForwardingAppender caches log events before outputting to the child Appenders.

ConsoleAppender outputs the log to the application console.

EventLogAppender writes the log to the Windows Event Log.

FileAppender outputs the log to a file.

ForwardingAppender sends log events to child Appenders.

LocalSyslogAppender writes the log to the local syslog service (for UNIX environments only).

MemoryAppender saves the log to a memory buffer.

NetSendAppender outputs the logs to the Windows Messenger service. These log messages will be displayed in the dialog box of the user terminal.

OutputDebugStringAppender outputs the log to the Debuger. If the program does not have a Debuger, it is output to the system Debuger. If the system Debuger is also unavailable, the message will be ignored.

RemoteSyslogAppender writes logs to the Remote syslog service via the UDP network protocol.

RemotingAppender writes logs to the remote receiver via .NET Remoting.

RollingFileAppender writes the log to the file as a rollback file.

SmtpAppender writes the log to the message.

SmtpPickupDirAppender puts messages into a directory as files, and SMTP agents like IIS SMTP agent can read or send them.

The TelnetAppender client accepts log events via Telnet.

TraceAppender writes the log to the .NET trace system.

UdpAppender sends the log to the remote host as a connectionless UDP datagram or broadcasts as a UdpClient.
2.2 Filters


Filters can be used to filter out the contents of the Appender output. Filters usually have the following types:


DenyAllFilter prevents all log events from being logged

LevelMatchFilter Only log events of the specified level are recorded

LevelRangeFilter The log level is recorded within the specified range.

LoggerMatchFilter matches the Logger name to record

PropertyFilter message is logged when it matches the specified property value

StringMathFilter message matches the specified string before being logged

2.3 Layouts


Layout is used to control the output format of the Appender, which can be linear or XML.



A appender can only have one layout.



The most commonly used layout should be the classic format patternlayout, followed by Simplelayout,rawtimestamplayout and Exceptionlayout. Then there are irawlayout,xmllayout and so on, using less. Layout can be implemented by itself and needs to be from log4net. Layout.layoutskeleton class inheritance, to output some special needs of the format, in the later extension of the implementation of a layout.


SimpleLayout is a simple output format that only outputs log levels and message content.

RawTimeStampLayout is used to format the time and will be used when outputting to the database. Styles such as "yyyy-MM-dd HH:mm:ss"

ExceptionLayout needs to pass the Exception object as a parameter to the Logger method, otherwise it will output nothing. The output will include Message and Trace.

PatternLayout uses the most Layout and can output a lot of information. For the usage, please refer to the configuration file in the above example. The formatted string of PatterLayout is described in Note 8.1.

2.4 Loggers


Logger is a component that interacts directly with the application. Logger simply generates a log, which is then recorded by the Appender it references to the specified medium, and the output format is controlled by layout.



Logger provides several ways to record a log message, or multiple logger exist simultaneously. Each instantiated logger object is maintained by the Log4net as a named entity (Named entity). 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. All logger are inherited from root, and root itself is a logger.



The rank of the logs, which are from high to the bottom:


OFF > FATAL > ERROR > WARN > INFO > DEBUG


Above the level SetPoint method (how to set See "Profile Details") can be written to the log, off all write methods are not written to the log, all the opposite. For example, when we set up info, logger. Debug will be ignored without writing to the file, but Fatal,error,warn,info will be written because they are higher than info.



In a specific write log, it is generally possible to understand the log level:


FATAL (Fatal Error): Errors in the system that can be used to completely lose functionality, stop the service, crash the system, etc., so that the system cannot continue to run. For example, the database cannot be connected and the system has an infinite loop.

ERROR (General Error): Records errors in the system that cause system instability, some functions are confusing, or some functions fail. For example, the data field is empty, the data operation is incomplete, the operation is abnormal, and so on.

WARN (Warning): The information in the recording system that does not affect the system's continued operation but does not meet the normal operating conditions of the system and may cause system errors. For example, the recorded content is empty, the data content is incorrect, and the like.

INFO (General Information): Record the basic information that should be known to the user during system operation. For example, the service starts running, the function has been opened, and so on.

DEBUG (Debug Information): Record all the information that the system uses for debugging, content or output of some key data content.


Logger implements the Ilog interface, Ilog defines 5 methods (Debug,inof,warn,error,fatal) to log different log levels separately. There are 5 overloads of these 5 methods. Take debug as an example to illustrate that the others are similar to it.



The Debug method is defined in Ilog as follows:


void Debug(object message);

void Debug(object message, Exception ex);


There is also a Boolean property:


bool IsDebugEnabled { get; }


If you use Debug (object message, Exception Ex), the default configuration logs will output Exception regardless of whether%exception is defined in the layout. Contains the message and trace of exception. If you use Debug (Object message), the log is not output exception.



Finally, there is a Logmanager class, which is used to manage all logger. It's GetLogger static method that can get the corresponding logger in the configuration file:


log4net.ILog log = log4net.LogManager.GetLogger("logger-name");
2.5 Object Renders


It will tell logger how to convert an object into a string log. (The interface that is defined in Ilog receives a parameter that is an object, not a string.) )



For example, if you want to log orange objects to the logs, logger only calls the Orange default ToString method. So to define a Orangerender class to implement the Log4net.ObjectRender.IObjectRender interface, and then register it (our extensions in this article do not use this method, but instead implement a custom layout directly). Then logger will know how to record orange in the log.


2.6 Repository


Repository is primarily used to maintain the organization structure of log objects.


3. Detailed Configuration Files 3.1 configuration file composition


There are two main parts, one is the declaration of a custom configuration section named "Log4net", as follows:


<configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
    ...
    ...
    ...
</log4net>


The second is the specific configuration of the <log4net> festival, which is to be highlighted below.


3.1.1 <log4net>


All configurations are defined in the <log4net> element.



Supported Properties:


Properties detailed
Debug Optional, the value is true or FALSE, the default is False. Set to True to turn on internal debugging of log4net.
Update Optional, the value is merge (merge) or overwrite (overwrite), the default value is merge. Set to overwrite, the configured libraries are reset when the configuration is submitted.
Threshold Optionally, the value is the level registered in Repository (library), and the default value is all.


Supported sub-elements:


Properties detailed
Appender 0 or more
Logger 0 or more
Renderer 0 or more
Root Up to one
Param 0 or more
3.1.2 <root>


is actually a root logger, all other logger inherit it by default, and if not explicitly defined in the configuration file, the framework uses the attributes defined in the root log. The root element has no attributes.



Supported sub-elements:


Properties detailed
Appender-ref 0 or more, the name of the Appender to refer to.
Level At most one. Only events at this level or above will be logged.
Param 0 or more, set some parameters.
3.1.3 <logger>


Supported Properties:


Properties detailed
Name Must be, the name of the logger
Additivity Optionally, the value is true or FALSE, and the default value is true. When set to False, the Appender in the parent logger is blocked.


Supported sub-elements:


Properties detailed
Appender-ref 0 or more, the name of the Appender to refer to.
Level At most one. Only events at this level or above will be logged.
Param 0 or more, set some parameters.
3.1.4 <appender>


Defines how the log will be exported, only as a child of the log4net. The Name property must be unique, and the Type property must be specified.



Supported Properties:


Properties detailed
Name Required, the name of the Appender object
Type Required, the output type of the Appender object


Supported sub-elements:


Properties detailed
Appender-ref 0 or more, allowing this appender to reference other Appender, is not supported by the Appender type.
Filter 0 or more, define the filters used by this app.
Layout At most one. Defines the output format used by the Appender.
Param 0 or more, set the value of the corresponding property in the Appender class.


<appender> can actually contain more than 4 sub-elements.


3.1.5 <layout>


Layout, only as a sub-element of <appender>.



Supported Properties:


Properties detailed
Type Required, type of layout


Supported sub-elements:


Properties detailed
Param 0 or more, set some parameters.
3.1.6 <filter>


Filter, only as a sub-element of <appender>.



Supported Properties:


Properties detailed
Type Required, type of filter


Supported sub-elements:


Properties detailed
Param 0 or more, set some parameters.
3.1.7 <param>


The <param> element can be a child element of any element.



Supported Properties:


Properties detailed
Name Required, the value is the parameter name of the parent object.
Value An optional, value, and type must have a property specified. Value is a string that can be converted to a parameter value.
Type An optional, value, and type must have a property specified. Type is the name of a class, and the full name is required if the type is not defined in the Log4net assembly.


Supported sub-elements:


Properties detailed
Param 0 or more, set some parameters.
4. Associating profiles


Log4net is associated with the application's configuration file, App. config (the BS program is web. config), and can be set using assembly custom properties. Here's a look at this custom property:



Log4net. Config.xmlconifguratorattribute



Xmlconfiguratorattribute has 3 properties:



ConfigFile: The name of the configuration file, the file path relative to the application directory



(AppDomain.CurrentDomain.BaseDirectory). The ConfigFile property cannot be used with the Configfileextension property.



Configfileextension: The extension of the configuration file, the file path relative to the application's directory. The Configfileextension property cannot be used with the ConfigFile property.



Watch: If you set the Watch property to True, the configuration file is monitored. When the configuration file changes, it reloads.



If both ConfigFile and configfileextension are not set, the application's configuration file, App. config, is used.



The following statements can be added to the project's AssemblyInfo.cs file:


/ / Monitor the default configuration file, App.config
[assembly: log4net.Config.XmlConfigurator(Watch = true)]

/ / Use the configuration file log4net.config, do not monitor changes. Note the directory of the log4net.config file, the BS program is in the site directory //, and the CS is in the application startup directory. For example, under /bin/Debug during debugging, the file output directory of the file attribute is generally adjusted to // permanent copy You can

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config")]


/ / Use the configuration file log4net.config, do not monitor changes

[assembly: log4net.Config.XmlConfigurator()]


can also be added in Global.asax's Application_Start or in the main method in Program.cs, note that this must be an absolute path, as follows:


/ / This is in the BS program, use the custom configuration file log4net.config, use Server.MapPath ("~") + @ "/log4net.config" to get the path. /log4net.config is the path relative to the site

// ConfigureAndWatch() is equivalent to Configure(Watch = true)

log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(Server.MapPath("~") + @"/log4net.config"));

//This is under the CS program and can be obtained in the following way:

String assemblyFilePath = Assembly.GetExecutingAssembly().Location;

String assemblyDirPath = Path.GetDirectoryName(assemblyFilePath);

String configFilePath = assemblyDirPath + " //log4net.config";

log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(configFilePath));


or use the absolute path directly:


/ / Use a custom configuration file, the direct absolute path is: c: / log4net.config

log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(@"c:/log4net.config"));  


</font>



. NET log records of--log4net focus


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.