Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Configuration and use of Log4j

2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly talks about "the configuration and use of Log4j". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "the configuration and use of Log4j"!

Introduction to Log4j

Chapter 1. Advantages of Log4j

Log4j is an open source project of Apache, through the use of Log4j, we can control the transmission of log information; we can also control the output format of each log; by defining the level of each log message, we can control the log generation process in more detail. What is most interesting is that these can be flexibly configured through a configuration file without the need to modify the application code.

The benefits of log4j are:

1) by modifying the configuration file, you can determine the destination of log information-console, files, GUI components, or even socket servers, NT event loggers, UNIX Syslog daemons, etc.

2) by modifying the configuration file, you can define the level of each log message, thus controlling whether it is output or not. In the system development stage, you can print detailed log information to track the operation of the system, and after the system is stable, you can turn off the log output, which can not only track the operation of the system, but also reduce junk code (System.out.println (.) Etc.).

3) the use of log4j requires a unified log mechanism for the whole system, which is conducive to system planning.

Chapter 2. Configuration file

Log4j consists of three important components: the priority of log information, the output destination of log information, and the output format of log information. The priority of log information from high to low is FATAL, ERROR, WARN, INFO, DEBUG, which are used to specify the importance of this log information; the output destination of the log information specifies whether the log will be printed to the console or to a file; and the output format controls the display of the log information.

2.1. Priority of log information

Divided into OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL, or levels that you define.

Log4j recommends using only four levels, and the priorities from highest to lowest are ERROR, WARN, INFO, and DEBUG. With the levels defined here, you can control the switch to the corresponding level of log information in the application. If a log request at level p occurs in a Logger with level Q, if p > = Q, the request will be enabled. This is the core principle of Log4j. For example, if the INFO level is defined here, all DEBUG level log information in the application will not be printed.

2.2. Use of output sources

Selectively enabling or disabling log requests is only part of Log4j's functionality. Log4j allows log requests to be output to multiple output sources. In Log4j's words, an output source is called an Appender.

Appender includes console (console), files (file), GUI components (component of graphics), remote socket servers (socket service), JMS (java information service), NT Event Loggers (event log of NT), and and remote UNIX Syslog daemons (background log service of remote UNIX). It can also record asynchronously. A logger can be set to more than one appender. Add an appender to a given logger using the addAppender method. For a given logger, each valid log request is forwarded to all the appender of the logger and to the appender of the logger's parent logger.

2.2.1. ConsoleAppender

If you use ConsoleAppender, the log information is written to Console. The effect is equivalent to printing the information directly to System.out.

2.2.2. FileAppender

Using FileAppender, the log information is written to the specified file. This should be a situation that is used more frequently. Accordingly, the file name of the log output should be specified in the configuration file. The following configuration specifies that the log file name is dglog.txt

Log4j.appender.A2.File=dglog.txt notes that A2 is replaced with the alias of Appender in the specific configuration.

2.2.3. DailyRollingAppender

Using FileAppender, you can output log information to a file, but it is inconvenient to read if the file is too large. You can use DailyRollingAppender at this point. DailyRollingAppender can output Log information to a file distinguished by date. The configuration file produces a log file every day, and each log file records only the log information for the day:

Log4j.appender.A2=org.apache.log4j.DailyRollingFileAppender

Log4j.appender.A2.file=dglog

Log4j.appender.A2.DatePattern='.'yyyy-MM-dd

Log4j.appender.A2.layout=org.apache.log4j.PatternLayout

Log4j.appender.A2.layout.ConversionPattern=% 5r%-5p% c {2} -% m% n

2.2.4. Org.apache.log4j.RollingFileAppender

A new file is generated when the file size reaches the specified size.

Log4j.appender.R=org.apache.log4j.RollingFileAppender

Log4j.appender.R.File=.. / logs/dglog.log

# Control the maximum log file size

Log4j.appender.R.MaxFileSize=100KB

# Archive log files (one backup file here)

Log4j.appender.R.MaxBackupIndex=1

Log4j.appender.R.layout=org.apache.log4j.PatternLayout

Log4j.appender.R.layout.ConversionPattern=%p% t% c -% m% n this configuration file specifies the output source R, which is a rotational log file. The largest file is 100KB, and when a log file reaches its maximum size, Log4J automatically renames example.log to dglog.log.1, and then rebuilds a new dglog.log file in turn.

2.2.5. Org.apache.log4j.WriterAppender

Sends the log information to any specified place in a stream format.

2.3. Configuration of Layout

Layout specifies the style of log information output.

2.3.1. Layout style

Org.apache.log4j.HTMLLayout (layout in HTML form)

Org.apache.log4j.PatternLayout (layout mode can be flexibly specified)

Org.apache.log4j.SimpleLayout (level containing log information and information string)

Org.apache.log4j.TTCCLayout (contains information about the time, thread, category, etc., when the log was generated)

2.3.2. Format

% m outputs the message specified in the code

% p output priority, i.e. DEBUG,INFO,WARN,ERROR,FATAL

% r output the number of milliseconds it took since the application was started to output the log information

% c outputs the category to which it belongs, which is usually the full name of the class

T outputs the name of the thread that generated the log event

% n outputs a carriage return newline character with "rn" for Windows platform and "n" for Unix platform

% d output the date or time of the log point in time. The default format is ISO8601, or you can specify the format after that, for example:% d {yyy MMM dd HH:mm:ss,SSS}. The output is similar: October 18, 2002, 22, 14, 10, 14, 28, 921.

% l outputs where the log event occurs, including the class name, the thread that occurred, and the number of lines in the code. For example: Testlog4.main (Test Log4.java:10)

2.3.3. Examples

Example 1: display date and log information

Log4j.appender.A2.layout=org.apache.log4j.PatternLayout

Log4j.appender.A2.layout.ConversionPattern=%d {yyyy-MM-dd HH:mm:ss,SSS}% m% nThe printed message is:

2002-11-12 11 order by createDate desc 4942866 SELECT * FROM Role WHERE 1 order by createDate desc example 2: display date, place of occurrence of log and log information

Log4j.appender.A2.layout=org.apache.log4j.PatternLayout

Log4j.appender.A2.layout.ConversionPattern=%d {yyyy-MM-dd HH:mm:ss,SSS}% l "#"% m% n

2002-11-12 11 cn.net.unet.weboa.system.dao.RoleDAO.select 51 cn.net.unet.weboa.system.dao.RoleDAO.select (RoleDAO.java:409) "#"

SELECT * FROM Role WHERE 1 order by createDate desc example 3: display log level, time, calling method, log information

Log4j.appender.A2.layout=org.apache.log4j.PatternLayout

Log4j.appender.A2.layout.ConversionPattern= [%-5p]% d {yyyy-MM-dd HH:mm:ss,SSS}

Method:%l%n%m%n

Log Information:

[DEBUG] 2002-11-12 12 00 Fraser 57376

Method:cn.net.unet.weboa.system.dao.RoleDAO.select (RoleDAO.java:409)

SELECT * FROM Role WHERE 1 # 1 order by createDate desc

2.4. Example of a configuration file:

Log4j.rootLogger=DEBUG

# record the DAO layer log to DAOLog,allLog

Log4j.logger.DAO=DEBUG,A2,A4

# record the logical layer log to BusinessLog,allLog

Log4j.logger.Businesslog=DEBUG,A3,A4

# A1 color-print to the screen

Log4j.appender.A1=org.apache.log4j.ConsoleAppender

Log4j.appender.A1.layout=org.apache.log4j.PatternLayout

Log4j.appender.A1.layout.ConversionPattern=%-5p [% t]% 37c% 3x -% m% n

# A2Mel-print to file DAOLog-specifically for DAO layer

Log4j.appender.A2=org.apache.log4j.DailyRollingFileAppender

Log4j.appender.A2.file=DAOLog

Log4j.appender.A2.DatePattern='.'yyyy-MM-dd

Log4j.appender.A2.layout=org.apache.log4j.PatternLayout

Log4j.appender.A2.layout.ConversionPattern= [%-5p]% d {yyyy-MM-dd HH:mm:ss,SSS}

Method:%l%n%m%n

# A3Mel-print to file BusinessLog-specifically record logic processing layer service log information

Log4j.appender.A3=org.apache.log4j.DailyRollingFileAppender

Log4j.appender.A3.file=BusinessLog

Log4j.appender.A3.DatePattern='.'yyyy-MM-dd

Log4j.appender.A3.layout=org.apache.log4j.PatternLayout

Log4j.appender.A3.layout.ConversionPattern= [%-5p]% d {yyyy-MM-dd HH:mm:ss,SSS}

Method:%l%n%m%n

# A4Mel-print to file alllog-record all log information

Log4j.appender.A4=org.apache.log4j.DailyRollingFileAppender

Log4j.appender.A4.file=alllog

Log4j.appender.A4.DatePattern='.'yyyy-MM-dd

Log4j.appender.A4.layout=org.apache.log4j.PatternLayout

Log4j.appender.A4.layout.ConversionPattern= [%-5p]% d {yyyy-MM-dd HH:mm:ss,SSS}

Method:%l%n%m%n

Chapter 3. API usage

There are 3 steps to use log4j:

3.1. Initialization

3.1.1. Initialization under Tomcat

The default Log4j initialization is typically used in a web-server environment. Under tomcat3.x and tomcat4.x, you should put the configuration file Log4j.properties in the WEB-INF/classes directory of your web application.

Log4j will find the properties file and initialize it. This is the easiest way to make it work. You can also choose to set the system property Log4j.configuration before running tomcat. The system variable is used to set the options on the command line for tomcat 3.x _ TOMCATROPTS. For tomcat4.0, the system environment variable CATALINA_OPTS is used instead of TOMCAT_OPTS.

UNIX Command Line

Export TOMCAT_OPTS= "- DLog4j.configuration=foobar.txt" tells Log4j to use the file foobar.txt as the default configuration file. This file should be placed in the WEB-INF/classes directory. This file will be read by PropertyConfigurator. Each web-application will use a different default profile because each file is related to its web-application.

1. Export TOMCAT_OPTS= "- DLog4j.debug-DLog4j.configuration=foobar.xml" export TOMCAT_OPTS= "- DLog4j.debug-DLog4j.configuration=foobar.xml" tells Log4j to output debugging information for Log4j-internal and uses foobar.xml as the default configuration file. This file should be placed in your web-application 's WEB-INF/classes directory. Because of the .xml extension, it will be read by DOMConfigurator. Each web-application will use a different default profile. Because each file is related to the web-application in which it is located.

2. Set TOMCAT_OPTS=-DLog4j.configuration=foobar.lcf

-DLog4j.configuratorClass=com.foo.BarConfigurator tells Log4j to use the file foobar.lcf as the default configuration file. This file should be placed in your web-application 's WEB-INF/classes directory. Because the Log4j.configuratorClass system properties are defined, the file will be parsed with a custom com.foo.barconfigurator class. Each web-application will use a different default profile. Because each file is related to the web-application in which it is located.

3. Set TOMCAT_OPTS=-DLog4j.configuration=file:/c:/foobar.lcf set TOMCAT_OPTS=-DLog4j.configuration=file:/c:/foobar.lcf tells Log4j to use the file foobar.lcf as the default configuration file. This configuration file defines the full path name with URL file:/c:/foobar.lcf. So the same configuration file will be used by all web-application. Different web-application will load Log4j through their own class loaders. In this way, each Log4j environment will operate independently without any synchronization with each other. For example, a FileAppenders that defines exactly the same output source in multiple web-application will try to write the same file. The result seems to be a lack of security. You have to make sure that the Log4j configuration for each different web-application does not use the same system resources.

3.1.2. Initialization of Servlet

It is also possible to initialize Log4j with a special servlet. The following is an example:

Public class Log4jInit extends HttpServlet {

Public void init () {

String prefix = getServletContext () .getRealPath ("/")

String file = getInitParameter ("Log4j-init-file")

If (file! = null) {

PropertyConfigurator.configure (prefix+file)

}

}

Public void doGet (HttpServletRequest req, HttpServletResponse res) {

}

Define the subsequent servlet in web.xml as your web-application.

Log4j-init

Xx.xx.Log4jInit

Log4j-init-file

WEB-INF/classes/Log4j.properties

one

Writing an initialized servlet is the most flexible way to initialize Log4j. There are no restrictions in the code, which you can define in the init method of servlet.

3.2. Initialize log4j according to the configuration file

Log4j can be initialized using the configurator in 3: the syntax for BasicConfigurator,DOMConfigurator,PropertyConfigurator is:

BasicConfigurator.configure (): automatically and quickly use the default Log4j environment.

PropertyConfigurator.configure (String configFilename): reads a configuration file written using the property file of Java.

DOMConfigurator.configure (String filename): reads the configuration file in the form of XML. PropertyConfigurator is used here. Using PropertyConfigurator is suitable for all systems. The following statement:

PropertyConfigurator.configure ("log4j.properties"); initializes the log4j environment with log4j.properties as the configuration file. One thing to note: this statement only needs to be executed once when the system starts. For example, it is called once in the init () method of ActionServlet.

Public class ActionServlet extends HttpServlet {

...

/ * *

* Initialize global variables

, /

Public void init () throws ServletException {

/ / initialize Action resources

Try {

InitLog4j ()

...

} catch (IOException e) {

Throw new ServletException ("Load ActionRes is Error")

}

}

...

Protected void initLog4j () {

PropertyConfigurator.configure ("log4j.properties")

}

...

} / / end class ActionServlet

3.3. Get Logger instances where you need to use log4j

With Log4j, the first step is to get the logger, which will be responsible for controlling the log information. Its syntax is:

Public static Logger getLogger (String name), which gets the logger by the specified name and, if necessary, creates a new logger for that name. Name usually takes the name of this class, such as:

Static Logger logger = Logger.getLogger (ServerWithLog4j.class.getName ())

Log4j makes it easy to name logger through software components. We can define a logger in each class through the static initialization method of Logger, so that the name of logger is equal to the global name of the class name, and the naming of logger is realized. This is a practical and simple way to define a logger. Because the log output contains the name of the class that generated the log, this naming strategy makes it easier to locate a source of log information. Although common, it is one of the common strategies for naming logger.

Log4j does not limit the possibility of defining logger. Developers are free to define the name of the logger as they wish. However, naming the Logger after the location of the class seems to be the best known way.

3.4. Use the debug,info,fatal... of the Logger object Method

Log.debug ("it is the debug info")

Chapter 4. Optimize

A frequently referenced parameter that depends on logging is the cost that can be calculated. This is a reasonable concept, and a moderate application may generate thousands of log requests. A lot of effort is spent on measuring and debugging logging optimization. Log4j requires speed and flexibility: speed is the most important, elasticity is the second.

4.1. Optimization of logs when logging is disabled.

The log is completely closed, and the cost of a log request is equal to a method call plus an integer comparison time. On 233mhz's Pentium II machines, this usually costs between 5 and 50 nanoseconds. However, method calls include the hidden cost of parameter construction. For example, for logger cat,logger.debug ("Entry number:" + I + "is" + String.valueOf (entry [I])); it causes the cost of building information parameters, such as converting integers I and input [I] to a string, and concatenating intermediate strings, regardless of whether the information is output or not. The cost of building this parameter can be high, and it mainly depends on the size of the parameter being called. The cost of avoiding parameter construction should be as follows

If (logger.isDebugEnabled ())

{

Logger.debug ("result is" + result)

}

If the debug of logger is turned off, this will not incur the cost of building parameters. On the other hand, if logger is debug, it will incur the cost of determining twice whether logger is available or not. Once in debugenabled, once in debug. This is irrelevant, because judging that the log is available accounts for only about 1% of the actual time spent on the log. In Log4j, log requests are in an instance of the Logger class. Logger is a class, not an interface. This greatly reduces the cost of flexibility in method calls. Of course, users use preprocessing or compile-time techniques to compile all log declarations. This will lead to perfect implementation results. However, because the binary application does not include the result of any log declaration, logging cannot be opened for that binary program. In my opinion, it is not worthwhile to get smaller performance optimizations at such a high cost.

4.2. Optimization of the log when the log status is enabled.

This is essentially the optimization of the logger hierarchy. When the log status is on, Log4j still needs to compare the requested level with the logger level. However, logger may not be assigned a level; they will inherit from their father. In this way, logger may need to search its ancestor before inheriting. Here is a serious effort to make the hierarchical search as fast as possible. For example, a child logger is only connected to its existing father logger. In the BasicConfigurator example shown earlier, a logger named com.foo.bar is connected to the root logger, thus bypassing logger com and com.foo that do not exist. This will significantly improve the speed of execution, especially when parsing the layer structure of logger. Parsing a typical hierarchy costs three times as much as when logger shuts down completely.

4.3. Log information is output when the log is optimized.

This is mainly spent on formatting the log output and sending it to its output source. Here we make another effort to make the formatting as fast as possible. Same as appender. In fact, the typical cost is about 100-300 milliseconds. See org.apache.log4.performance.Logging for details. Although Log4j has many features, its first design goal is speed. Some Log4j components have been rewritten many times to improve performance. However, contributors often propose new optimizations. You should be satisfied to know that performing tests with SimpleLayout configuration has shown that the output of Log4j is as fast as System.out.println.

At this point, I believe you have a deeper understanding of "the configuration and use of Log4j". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue 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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report