Log4j official document translation (Fourth, how to output log messages in java)

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.propertiesThe 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 CLASSPATHinside, your log4j.propertiesfiles should also be placed PATHinside and then follow the steps below:

  • createlog4j.properties
  • Create log4jExample.javaand compile it
  • Execute log4jExamplebinary 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

Guess you like

Origin blog.csdn.net/weixin_33841722/article/details/91990091