Detailed java-based configuration log4j log

Lklaog4j

1.1 understand Log4j

Apache Log4j is an open source project, by using log4j, we can control the destination log information may be conveyed console, files, GUI components, we can also control the output format of each log, by defining the level of each log information we are able to generate more detailed process control log.

Configuring Log4j step (java program)

Configure Log4j log java program is divided into four steps:

1. The first step

Add log4j-1.2.8.jar (later may select the log4j) to the lower lib.

If you are using maven project, you can also choose to add dependent in pom.xml:

<-! Join log4j support ->

<dependency>

<groupId>log4j</groupId>

<artifactId>log4j</artifactId>

<version>1.2.17</version>

</dependency>

2. The second step

Establish the corresponding modify attributes log4j.prope, must be known before modifying dryness under these are the CLASSPATH Log4j.rootLogger = the INFO, stdout, R & lt

#appender
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#layout
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#conversion
log4j.appender.stdout.layout.ConversionPattern= [QC] %p [%t] %C.%M(%L) | %m%n

 

4. The fourth step

Adding the relevant statements in the class to be output in the log:

Custom properties: static Logger logger = Logger.getLogger (LogDemo.class); // LogDemo relevant classes

In the respective methods:

if (logger.isDebugEnabled()){

logger.debug("System …..");

}

1.3 configuration instructions

The following is the configuration file log4j.properties configuration instructions.

1、log4j.rootCategory=INFO, stdout , R

The sentence level is output to stdout and destinations defined both R, and R are INFO stdout log information in the following code may be arbitrarily named. Level can be divided OFF, FATAL, ERROR, WARN, INFO, DEBUG , ALL, any configuration information if the play is not OFF, if configured as INFO so that only the display of the log information INFO, WARN, ERROR, and the information will not be displayed DEBUG , explain in detail with reference to the third portion may be defined in the configuration file logger.

2、log4j.appender.stdout=org.apache.log4j.ConsoleAppender

Sentence to define named stdout output of which type can be

org.apache.log4j.ConsoleAppender (console),

org.apache.log4j.FileAppender (file),

org.apache.log4j.DailyRollingFileAppender (produce a daily log file),

org.apache.log4j.RollingFileAppender (file size reaches the specified size when create a new file)

Org.apache.log4j.WriterAppender (log stream format information is sent to any designated place)

Referring specifically explain a third portion may be defined in the configuration file Appender.

3、log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

Sentence for defining the output terminal of the called stdout which type of layout may be

org.apache.log4j.HTMLLayout (with HTML layout table form),

org.apache.log4j.PatternLayout (the flexibility to specify the layout mode),

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

org.apache.log4j.TTCCLayout (including the time the log generated, thread , type information, etc.)

Referring specifically explain a third portion may be defined in the configuration file Layout.

4、log4j.appender.stdout.layout.ConversionPattern= [QC] %p [%t] %C.%M(%L) | %m%n

If necessary the specific format layout pattern ConversionPattern, the print parameters specified print information are as follows:

% M output code specified in the message;

% M when the log output printing method name;

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

% R output from the application starts to output the log information on the number of milliseconds spent;

% C output category belongs, where the class is usually full name;

% T thread name of the output generated log events;

Output% n Enter a newline, Windows platform "rn", Unix platform "n";

Date or time% d log output time points, the default format is ISO8601, you can specify the format followed in, for example:% d {yyyy-MM-dd HH: mm: ss, SSS}, similar output: 2002-10- 18 22: 10: 28,921;

% L output log event occurrence position and the number of lines in the code;

[QC] is the beginning of the log information, it can, usually referred to as the project any character.

Information output

[TS] DEBUG [main] AbstractBeanFactory.getBean(189) | Returning cached instance of singleton bean 'MyAutoProxy'

Specific reference may be formatted log information to explain a third portion is defined in the configuration file.

5、log4j.appender.R=org.apache.log4j.DailyRollingFileAppender

And the third line the same sentence. R type definition named output terminal to generate a log file per day.

6、log4j.appender.R.File=D:\\Tomcat 5.5\\logs\\qc.log

Sentence defined for the file named output terminal R of the named D: \\ Tomcat 5.5 \\ logs \\ qc.log can modify.

7、log4j.appender.R.layout=org.apache.log4j.PatternLayout

4 the same row.

8、log4j.appender.R.layout.ConversionPattern=%d-[TS] %p %t %c - %m%n

5 the same row.

9、log4j.logger.com. neusoft =DEBUG

Specifies com.neusoft the packet level for all classes of DEBUG.

Com.neusoft package name can be changed to your own project used.

10、log4j.logger.com.opensymphony.oscache=ERROR

11、log4j.logger.net.sf.navigator=ERROR

It is these two errors occur at the level of the two packages is set to ERROR, if the project is not configured EHCache, you do not need these two.

12、log4j.logger.org.apache.commons=ERROR

13、log4j.logger.org.apache.struts=WARN

These two packages are struts.

14、log4j.logger.org.displaytag=ERROR

The message is displaytag package. (QC page list of questions used)

15、log4j.logger.org.springframework=DEBUG

Spring sentence for the package.

16、log4j.logger.org.hibernate.ps.PreparedStatementCache=WARN

17、log4j.logger.org.hibernate=DEBUG

This is a two hibernate package.

These packets provided above may be tailored to the actual situation of the project.

1.4 Detailed profiles

Log4j supports two configuration file format, one is XML (application under the Standard Generalized Markup Language) format, one is Java properties file log4j.properties (key = value) . Log4j.properties file will be described below as a method of using the configuration file:

①, configure the root Logger

Logger handles most operations logging.

The syntax is:

log4j.rootLogger = [ level ] , appenderName, appenderName, …

Wherein, level priority is logging, into OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL or custom levels. Log4j recommended to use only four levels, from highest to lowest priority are ERROR, WARN, INFO, DEBUG. Defined by the level here, you can control the switch to log the application of the appropriate level of information. For example, in the definition of the INFO level here, only equal to and above this level and then processed, the application of all the DEBUG level log information will not be printed. ALL: Print all logs, OFF: close all log output. appenderName is to specify the output log information to which place. You can specify multiple output destinations.

②, configuration information log output destination Appender

Appender responsible for controlling the output of the logging operation.

The syntax is:

log4j.appender.appenderName = fully.qualified.name.of.appender.class

log4j.appender.appenderName.option1 = value1

log4j.appender.appenderName.optionN = valueN

appenderName here is, can be arbitrarily defined in ① named.

Which, appender Log4j provided are the following:

org.apache.log4j.ConsoleAppender (console),

org.apache.log4j.FileAppender (file),

org.apache.log4j.DailyRollingFileAppender (produce a daily log file),

org.apache.log4j.RollingFileAppender (file size reaches the specified size to generate a new file), by setting the file size log4j.appender.R.MaxFileSize = 100KB, may also be provided by log4j.appender.R.MaxBackupIndex = 1 to save a backup file .

Org.apache.log4j.WriterAppender (log stream format information is sent to any designated place)

例如:log4j.appender.stdout=org.apache.log4j.ConsoleAppender

Define a named destination output to stdout, ConsoleAppender for the console.

Format (layout) Layout ③, log information

Layout is responsible for formatting the output of Appender .

The syntax is:

log4j.appender.appenderName.layout = fully.qualified.name.of.layout.class

log4j.appender.appenderName.layout.option1 = value1

log4j.appender.appenderName.layout.optionN = valueN

Which, layout Log4j provided are the following:

org.apache.log4j.HTMLLayout (in HTML table format layout),

org.apache.log4j.PatternLayout (the flexibility to specify the layout mode),

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

org.apache.log4j.TTCCLayout (including the time the log generated, thread, type information, etc.)

1.5 Formatting log

When log4j.applender.appendlerName = org.apache.log4j.PatternLayout, it represents want to customize the output format, and therefore need to set log4j.appender.stdout.layout.ConversionPattern.

Log4J print format formatted using log information similar to the C language printf function, the printing parameters are as follows:

% M output code specified in the message;

% M when the log output printing method name;

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

% R output from the application starts to output the log information on the number of milliseconds spent;

% C output category belongs, where the class is usually full name;

% T thread name of the output generated log events;

Output% n Enter a newline, Windows platform "rn", Unix platform "n";

Date or time% d log output time points, the default format is ISO8601, you can specify the format followed in, for example:% d {yyyy-MM-dd HH: mm: ss, SSS}, similar output: 2002-10- 18 22: 10: 28,921;

% L occurrence position output log events, and the number of lines in the code.

1.6 Definition and acquisition of different levels recorder

Any use of the recorder has a two steps:

1) the definition of the corresponding record in the configuration file.

Recorder defined in the configuration file format, there are two

# Define the root logger format

log4j.rootLogger = [ level ], appendName1, appendName2, …appendNameN

# Define a non-root logger format

log4j.logger.loggerName1 = [ level ], appendName1,…appendNameN

……

log4j.logger.loggerNameM = [ level ], appendName1, …appendNameN

We can define any non-root logger.

2) obtaining call logger Logger class method to obtain the appropriate record in the object code .

To obtain the root recording object by invoking the Logger.getRootLogger () function, to obtain a non-root logger by Logger.getLogger () function.

1.7 Configuring log4j java web-based project

So far, this article is talking about how to use log4j in the application, whereas Java is now mainstream J2EE and J2ME. Now, let's look at how to use log4j in J2EE development. In fact, very simple log4j application in the Web application is to initialize the log4j on the application of the different applications log4j log4j place before any application code. So, we just put in the web application in log4j initialization independent, put it in a Servlet. Let's look at an example.

Example 5- A: 

for initializing Servlet: 

Import org.apache.log4j.PropertyConfigurator; 

Import the javax.servlet.http.HttpServlet; 

Import the javax.servlet.http.HttpServletRequest; 

Import javax.servlet.http.HttpServletResponse; 

/ ** 

* log4j.jar class initialization, reference the web.xml 

* / 

public  class Log4jInit the extends the HttpServlet 

{ 

public  void the init () 

{ 

// dynamically profile achieved by the web.xml 

String prefix = GetServletContext () the getRealPath ( "/." ); 

File String = getInitParameter ( "log4j-the init-File" ); 

//If no corresponding profile, not initialized 

IF (File =! Null ) 

{ 

PropertyConfigurator.configure (prefix + File); // (. 1) 

} 

} 

public  void the doGet (the HttpServletRequest REQ, the HttpServletResponse RES) 

{} 

}

The following look at the Servlet defined in web.xml.

例5-b:

<servlet>

<servlet-name>log4j-init</servlet-name>

<servlet-class>TestLog4j.Log4jInit</servlet-class>

<init-param>

<param-name>log4j-init-file</param-name>

<param-value>sort.properties</param-value>

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>

Because log4j initialization to be completed before all of log4j calls, so the web.xml file, load-on-startup Servlet we must take the corresponding definition should be set to 1, so that is loaded into the container when the Web started Servlet.

After the completion of these two steps that we can use the same log4j as a web application in any place in application development.

Guess you like

Origin www.cnblogs.com/z-x-p/p/11527248.html