We have to create the configuration file, this chapter describes in detail how the next generation of debug information and turn them into a text file.
Basic example
Here is a basic example of creation:
log4j.properties
The contents are:
log = /usr/home/log4j
log4j.rootLogger = DEBUG, FILE
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/log.out
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
It will look at what has been done:
- Level of the root logger is DEBUG, and the binding of a name is FILE appender's.
- appender FILE defined as org.apache.log4j.FileAppender, and the content is written log.out file.
- layout format is defined as% m% n, meaning that each piece of information will be followed by a newline
In use log4j java program
The following simple java classes initialized, use, etc. log4j log output:
import org.apache.log4j.Logger;
import java.io.;
import java.sql.SQLException;
import java.util.;
public class log4jExample{
/* Get actual class name to be printed on */
static Logger log = Logger.getLogger(log4jExample.class.getName());
public static void main(String[] args)throws IOException,SQLException{
log.debug("Hello this is a debug message");
log.info("Hello this is an info message");
}
}
Compile and execute
Here are the steps to compile the code above: to ensure that you set the PATH and CLASSPATH variables before execution
All library files should be placed CLASSPATH
inside, your log4j.properties
files should also be placed PATH
inside and then follow the steps below:
- create
log4j.properties
- Create
log4jExample.java
and compile it - Execute
log4jExample
binary file
You can /usr/home/log4j/log.out file, get the following information:
Hello this is a debug message
Hello this is an info message
Reproduced in: https: //my.oschina.net/u/204616/blog/545419