In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces the ASP.NET debugging API Log4net how to use, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.
1 introduction
1.1 advantages of Log4net:
Almost all large applications have their own API for tracking and debugging. Because once the program is deployed, it is no longer possible to use specialized debugging tools. However, an administrator may need to have a powerful logging system to diagnose and fix configuration problems.
Experience has shown that logging is often an important part of the software development cycle. It has the following advantages: it can provide a precise environment for developers to find the Bug; in the application as soon as possible. Once the Log output code is added to the program, log information can be generated and output during the program running without human intervention. In addition, the log information can be output to different places (console, files, etc.) for future research.
Log4net is designed for this purpose as a logging package for the .NET development environment.
1.2 installation of Log4net for ASP.NET debugging tools:
Users can download the source code of log4net from http://logging.apache.org/log4net/. After unzipping the package, load log4net.sln into Visual Studio .NET in the extracted src directory, and you can get log4net.dll after compilation. To add logging to your program, users only need to introduce log4net.dll into the project.
2 the structure of Log4net
Log4net has four main components, namely Logger (logger), Repository (library), Appender (attachment) and Layout (layout).
2.1 Logger
2.1.1 Logger interface
Logger is the main component that the application needs to interact with, and it is used to generate log messages. The resulting log messages are not displayed directly and are not output until they are formatted by Layout in advance.
Logger provides a variety of ways to log a message, you can create multiple Logger in your application, and each instantiated Logger object is maintained by the log4net framework as a named entity (named entity). This means that in order to reuse a Logger object, you don't have to pass it between different classes or objects, you just need to call it with its name as an argument. The log4net framework uses an inheritance system, which is similar to namespaces in .NET. That is, if there are two logger, which are defined as a.b.c and A.B, then we say that A.B is the ancestor of a.b.c. Each logger inherits the attributes of its ancestors
The Log4net framework defines an ILog interface that all logger classes must implement. If you want to implement a custom logger, you must first implement this interface. You can refer to several examples in the / extension directory.
The definition of ILog interface is as follows:
Public interface ILog {void Debug (object message); void Info (object message); void Warn (object message); void Error (object message); void Fatal (object message); / / each of the above methods has an overloaded method to support exception handling. / / each overloaded method is shown below, with an additional parameter of the exception type. The void Debug (object message, Exception ex); / /... / Boolean attribute is used to check the log level of Logger / / (we'll see the log level later) bool isDebugEnabled; bool isInfoEnabled; / /... Boolean attribute corresponding to other methods}
The Log4net framework defines a class called LogManager that manages 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:
Log4net.ILog log = log4net.LogManager.GetLogger ("logger-name")
Typically, we call GetLogger () with the type of the class (class) as an argument to keep track of the class we are logging. The type of the passed class (class) can be obtained using the typeof (Classname) method, or it can be obtained using the following reflection method:
System.Reflection.MethodBase.GetCurrentMethod () DeclaringType
Although the symbol is a little longer, the latter can be used in some situations, such as getting the type (type) of the class (class) that calls the method.
2.1.2 level of log
As you can see in the ILog interface, there are five different ways to track an application. In fact, these five methods operate on different logging priorities set by the Logger object. These different levels are defined as constants in the log4net.spi.Level class. You can use any method in the program. But in the release of * * you may not want all the code to waste your CPU cycle, so the framework provides seven levels and corresponding Boolean attributes to control the type of logging.
There are several values for Level
Table 1 Log level of Logger
In the log4net framework, each log object is assigned a log priority by setting the configuration file. If a log object is not explicitly assigned a level, the object attempts to inherit a level value from its ancestors.
Each method of the ILog interface has a predefined level value. As you can see in Table 1, the Inof () method of ILog has an INFO level. Again, and so on, the Error () method has an ERROR level. When we use any of the above methods, the log4net framework checks the level of the log object logger and the level of the method. Log requests are accepted and executed only if the level of the method is higher than the log level.
For example, when you create a log object and set its level to INFO. So the framework sets each Boolean property of the log. When you call the corresponding logging method, the framework checks the corresponding Boolean property to determine whether the method can be executed. The code is as follows:
Logger.Info ("message"); Logger.Debug ("message"); Logger.Warn ("message")
For the * method, the level of Info () is equal to that of the log (INFO), so the log request is passed and we can get the output "message".
For the second method, the level of Debug () is lower than the log level (INFO) of the log object logger, so the log request is rejected and we don't get any output. Similarly, for the third line of statements, we can easily draw a conclusion.
There are two special levels in Table 1: ALL and OFF. ALL means that all log requests are allowed. OFF is denying all requests.
You can also explicitly check the Boolean property of the Logger object, as follows:
If (logger.IsDebugEnabled) {Logger.Debug ("message");}
2.2 Repository
Repository is mainly used to maintain the organizational structure of log objects. In previous versions of log4net, the framework only supported hierarchical organizational structures (hierarchical organization). This hierarchical structure is essentially an implementation of the library and is defined in the log4net.Repository.Hierarchy namespace. To implement a Repository, you need to implement the log4net.Repository.ILoggerRepository interface. However, this interface is not usually implemented directly, but is inherited from the log4net.Repository.LoggerRepositorySkeleton base class. System libraries (hierarchical repository) are implemented by the log4net.Repository.Hierarchy.Hierarchy class.
If you are a user of the log4net framework, not an extender, you will hardly use Repository classes in your code. Instead, you need to use the LogManager class to automate the management of libraries and log objects.
2.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 very well. It uses a component called Appender to define the output medium. As the name suggests, these components attach them to the Logger logging component and pass the output to the output stream. You can attach multiple Appender components to a log object. The Log4net framework provides several Appender components. A complete list of the Appender components provided by log4net can be found in the help manual of the log4net framework. With these off-the-shelf Appender components, you don't have to write them yourself in general. But you can inherit from the log4net.Appender.AppenderSkeleton class if you like.
2.4 Appender Filters
An Appender object passes all log events to the output stream by default. Appender's filter (Appender Filters) can filter log events by different criteria. There are already several predefined filters under the log4net.Filter namespace. Using these filters, you can filter log events by log level range, or by a particular string. You can find more information about filters in the API help file.
2.5 Layout
The Layout component is used to display formatted output information to the user. The output information can be displayed in a variety of formats, depending on the type of Layout component we use. It can be linear or an XML file. The Layout component works with an Appender component. There is a list of different Layout components in the API help manual. An Appender object can only correspond to one Layout object. To implement your own Layout class, you need to inherit from the log4net.Layout.LayoutSkeleton class, which implements the ILayout interface.
3 use log4net in the program
Before you start logging your program, you need to start the log4net engine. This means that you need to configure the three components mentioned above first. You can set the configuration in two ways: setting the configuration in a separate file or defining the configuration in the code.
It is recommended to define the configuration in a separate file for the following reasons:
You don't need to recompile the source code to change the configuration
You can change the configuration while the program is running. This is sometimes important in some WEB programs and remote procedure call programs
Considering the importance of the * method, let's first look at how to set the configuration information in the file.
3.1 define profile
Configuration information can be placed in one of the following forms of files.
In the program's configuration file, such as AssemblyName.config or web.config.
In your own file. The file name can be any name you want, such as AppName.exe.xyz, etc.
The log4net framework looks for the configuration file under the directory path defined relative to the AppDomain.CurrentDomain.BaseDirectory attribute. The only identity that the framework is looking for in the configuration file is the tag. An example of a complete configuration file is as follows:
< ?xml version="1.0" encoding="utf-8" ?> < configuration> < configSections> < section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net-net-1.0" /> < /configSections> < log4net> < root> < level value="WARN" /> < appender-ref ref="LogFileAppender" /> < appender-ref ref="ConsoleAppender" /> < /root> < logger name="testApp.Logging"> < level value="DEBUG"/> < /logger> < appender name="LogFileAppender" type="log4net.Appender.FileAppender" > < param name="File" value="log-file.txt" /> < param name="AppendToFile" value="true" /> < layout type="log4net.Layout.PatternLayout"> < param name="Header" value="[Header]\r\n"/> < param name="Footer" value="[Footer]\r\n"/> < param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" /> < /layout> < filter type="log4net.Filter.LevelRangeFilter"> < param name="LevelMin" value="DEBUG" /> < param name="LevelMax" value="WARN" /> < /filter> < /appender> < appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" > < layout type="log4net.Layout.PatternLayout"> < param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" /> < /layout> < /appender> < /log4net> < /configuration>You can copy the above text directly to any program, but you can still understand how the configuration file is made up. Only if you need to use the log4net configuration in the application configuration file, you need to use the
< configSection>Add to the label
< section>Configure the node portal. For other separate files, only
< log4net>It is the text within the tags that is required, and the order of these tags is not fixed. Let's explain the meaning of the text in each tag in turn:
3.1.1
< root> < root> < level value="WARN" /> < appender-ref ref="LogFileAppender" /> < appender-ref ref="ConsoleAppender" /> < /root>In the framework system, all log objects are descendants of the root log (root logger). So if a log object is not explicitly defined in the configuration file, the framework uses the properties defined in the root log. In
< root>Tag, you can define a list of level level values and Appender. If the value of LEVEL is not defined, the default is DEBUG. Can be passed through
< appender-ref>The tag defines the Appender object used by the log object.
< appender-ref>Declares a reference to an Appender object defined elsewhere. The setting in a logger object overrides the setting of the root log. For the Appender property, the child log object inherits the Appender list of the parent log object. This default behavior can also be explicitly set
< logger>The additivity attribute of the tag is changed to false.
< logger name="testApp.Logging" additivity="false"> < /logger>The default value of Additivity is true.
3.1.2
< Logger> < logger name="testApp.Logging"> < level value="DEBUG"/> < /logger> < logger>Element predefines the settings for a specific log object. You can then retrieve the log with that name by calling the LogManager.GetLogger ("testAPP.Logging") function. If LogManager.GetLogger (...) If a predefined log object is not opened, the log object inherits the properties of the root log object. Knowing this, we can say that, in fact,
< logger>Labels are not required.
3.1.3
< appender> < appender name="LogFileAppender" type="log4net.Appender.FileAppender" > < param name="File" value="log-file.txt" /> < param name="AppendToFile" value="true" /> < layout type="log4net.Layout.PatternLayout"> < param name="Header" value="[Header]\r\n" /> < param name="Footer" value="[Footer]\r\n"/> < param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" /> < /layout> < filter type="log4net.Filter.LevelRangeFilter"> < param name="LevelMin" value="DEBUG" /> < param name="LevelMax" value="WARN" /> < /filter> < /appender>In
< root>Label or individual
< logger>The Appender object in the tag can use the
< appender>Label definition.
< appender>The basic form of the label is shown above. It defines the name and type of appender. What is more important is that
< appender>Other tags inside the tag. Different appender have different
< param>Label. In this case, in order to use FileAppender, you need a file name as a parameter. In addition, we need another one in
< appender>A Layout object is defined inside the tag. The Layout object is defined in its own
< layout>Inside the label.
< layout>The type attribute of the tag defines the type of Layout (in this case, PatternLayout) and also determines the parameter values to be provided. The Header and Footer tags provide text output at the beginning and end of a log session (logging session). Examples of the specific configuration of each appender can be found in log4net\ doc\ manual\ example- config-appender.html.
3.1.4 Translation patterns in log4net.Layout.PatternLayout (ConversionPattern)
% m (message): output log messages, such as ILog.Debug (…) An output message
% n (new line): line feeds
% d (datetime): outputs the time the current statement is running
% r (run time): output the number of milliseconds consumed by the program from run to execution to the current statement
% t (thread id): thread ID on which the current statement resides
% p (priority): the current priority of the log, namely DEBUG, INFO, WARN … Etc.
% c (class): the name of the current log object, for example:
The pattern string is:%-10c -% m% n
The code is:
ILog log=LogManager.GetLogger ("Exam.Log"); log.Debug ("Hello")
The output is in the following form:
Exam.Log-Hello
% L: line number where the output statement is located
% F: file name where the output statement is located
%-number: indicates the minimum length of the item. If not, fill it with blanks.
For example, a PatternLayout with a translation pattern of% r [% t]%-5p% c -% m% n produces output similar to the following:
176 [main] INFO org.foo.Bar-Located nearest gas station.
3.1.5
< filter>*, let's look at the
< filter>Label. It defines the filter applied to the Appender object. In this example, we use the LevelRangeFilter filter, which logs only log events between the log levels specified by the LevelMin and LevelMax parameters. You can define multiple filters (Filter) on an Appender that will filter log events in the order in which they are defined. Information about other filters can be found in log4net's SDK documentation.
3.2 use Profil
3.2.1 Associated profile
After we have created the above configuration file, we next need to associate it with our application. By default, each independent executable assembly defines its own configuration. The log4net framework uses log4net.Config.DOMConfiguratorAttribute to define configuration files at the assembly level.
For example, you can add the following statement to the AssemblyInfo.cs file of the project
[assembly:log4net.Config.DOMConfigurator (ConfigFile= "filename"
ConfigFileExtension= "ext", Watch=true/false)]
L Configfile: indicates the path and file name of our configuration file, including the extension.
L 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 configuration file extension for the assembly is "config".
L Watch (Boolean attribute): the log4net framework uses this property to determine whether it is necessary to monitor changes to the file at run time. If this property is true, then FileSystemWatcher will be used to monitor file changes, renames, deletions, and so on.
Where: the ConfigFile and ConfigFileExtension attributes cannot be used at the same time, and ConfigFile indicates the name of the configuration file, for example, ConfigFile= "Config.txt"
ConfigFileExtension refers to the extension of a configuration file with the same name as the executable assembly. For example, if the name of the application is "test.exe", ConfigFileExtension= "txt", the configuration file should be "test.exe.txt".
You can also apply DOMConfiguratio () without parameters:
[assembly: log4net.Config.DOMConfigurator ()]
You can also open the configuration file with the DOMConfigurator class in the program code. The constructor of the class requires a FileInfo object as an argument to indicate the name of the configuration file to open. This method has the same effect as setting properties in the assembly to open a configuration file.
Log4net.Config.DOMConfigurator.Configure (
New FileInfo ("TestLogger.Exe.Config"))
The DOMConfigurator class also has a method ConfigureAndWatch (..), which is used to configure the framework and detect changes in the file.
The above steps summarize the various aspects related to configuration, and we will use the logger object in two steps.
3.2.2 create or get a log object
The log object uses the properties defined in the configuration file. If a log object is not defined in advance in the configuration file, the framework acquires the properties of the ancestor node according to the inheritance structure, and finally, the attributes from the root log. As follows:
Log4net.ILog log = Log4net.LogManager.GetLogger ("MyLogger")
3.2.3 output log information
You can use several methods of ILog to output log information. You can also check the IsXXXEnabled Boolean variable before calling a method, and then decide whether to call a function that outputs log information, which can improve the performance of the program. Because the framework is calling things like ILog.Debug (...) When such a function is used, it is also determined whether the Level log level condition is met.
If (log.IsDebugEnabled) log.Debug ("message")
If (log.IsInfoEnabled) log.Info ("message)
3.3 configure log4net in the program
In addition to configuring log4net with a configuration file mentioned earlier, you can also configure the log4net framework with code in your program. Such as the following example:
/ / use FileAppender log4net.Config.BasicConfigurator.Configure with PatternLayout (new log4net.Appender.FileAppender (new log4net.Layout.PatternLayout ("% d [% t]%-5p% c [% x] -% m% n"), "testfile.log"); / / using a FileAppender with an XMLLayout log4net.Config.BasicConfigurator.Configure (new log4net.Appender.FileAppender (new log4net.Layout.XMLLayout (), "testfile.xml")) / / using a ConsoleAppender with a PatternLayout log4net.Config.BasicConfigurator.Configure (new log4net.Appender.ConsoleAppender ("% d [% t]%-5p% c -% m% n")); / / using a ConsoleAppender with a SimpleLayout log4net.Config.BasicConfigurator.Configure (new log4net.Appender.ConsoleAppender (new log4net.Layout.SimpleLayout ()
Although it is convenient to configure log4net in code here, you cannot configure each log object separately. All of these configurations are applied to the root log.
The log4net.Config.BasicConfigurator class sets an Appender object using the static method Configure. The constructor of Appender requires the Layout object accordingly. You can also call BasicConfigurator.Configure () directly without arguments, which uses a default PatternLayout object to output information in a ConsoleAppender. As follows:
Log4net.Config.BasicConfigurator.Configure ()
Information in the following format is displayed on output:
0 [1688] DEBUG log1 A B C-Test
20 [1688] INFO log1 A B C-Test
When the log4net framework is configured, you can use the logging feature as described earlier.
Thank you for reading this article carefully. I hope the article "how to use ASP.NET debugging API Log4net" shared by the editor will be helpful to everyone. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.