Brief introduction:
LOG4J is an Apache open source project, through the use of log4j, we can control the log information delivery destination is the console, files, GUI components, even the socket server, NT Event recorder, UNIX syslog daemon, etc. We can also control the output format of each log, and by defining the level of each log information, we can control the log generation process more carefully. Most interesting of all, these can be configured flexibly with a single configuration file, without the need to modify the code of the application.
Official site: http://logging.apache.org/log4j/
LOG4J configuration:
The first step: join Log4j-1.2.8.jar to Lib.
Step Two: establish log4j.properties under the classpath. The contents are as follows:
#定义DEBUG优先级, R is the purpose of the log output
Log4j.rootlogger=debug, R
#设置日志输出类型, for file type
Log4j.appender.r=org.apache.log4j.fileappender
#设置日志文件名my. Log
Log4j.appender.r.file=weather.log
#每次在文件尾写入新的日志信息
Log4j.appender.r.append=true
#日志输出信息格式类型
Log4j.appender.r.layout=org.apache.log4j.patternlayout
#日志输出信息格式为 line break, newline, date, priority, [class name], log information, line break
log4j.appender.r.layout.conversionpattern=%n%n%d%p[%c]-%m%n
Step three: Define the Log class Log.java
PackageCom.kyny.weather.log;ImportOrg.apache.log4j.Logger;ImportOrg.apache.log4j.PropertyConfigurator;/*** Log class *@authorZhoucan **/ Public classLog {//Logger Instances PublicLogger Logger =NULL; //encapsulate the log class as a singleton mode Private Staticlog log; //constructor to initialize the required properties for the logger configuration PrivateLog () {//get the current directory pathString filepath= This. GetClass (). GetResource ("/"). GetPath (); //Locate the directory where the log4j.properties configuration file is located (already created)Filepath=filepath.substring (1). Replace ("bin", "src"); //get an instance of the log class loggerLogger=logger.getlogger ( This. GetClass ()); //Logger Required configuration file pathPropertyconfigurator.configure (filepath+ "Log4j.properties"); } Public StaticLog GetLogger () {if(Log! =NULL)returnlog; Else return NewLog (); }}
Examples of Use:
Log log = Log.getlogger (); Log.logger.error ("XXX", e);
Using log4j to log errors, output logs in Java