What is log4j?
Log4j is an open source project of Apache . By using Log4j, we can control the destination of log information delivery to consoles , files, GUI components, and even socket servers, NT event loggers, UNIX Syslog daemons , etc.; we also The output format of each log can be controlled; by defining the level of each log information, we can control the log generation process in more detail. Most interestingly, these can be flexibly configured via a configuration file without modifying the application code.
1. Introduce log4j
There are two ways to use log4j
1. Introduce the corresponding Jar package
Add log4j-1.2.8.jar (you can choose a later version of log4j) to lib.
2. Using Maven
<!-- Add log4j support--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
2. Placement log4j.properties
Take the SSH framework as an example, create a log4j.properties
log4j.rootLogger = debug,stdout,D,E log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n log4j.appender.D = org.apache.log4j.DailyRollingFileAppender log4j.appender.D.File = D://logs/log.log log4j.appender.D.Append = true log4j.appender.D.Threshold = DEBUG log4j.appender.D.layout = org.apache.log4j.PatternLayout log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n log4j.appender.E = org.apache.log4j.DailyRollingFileAppender log4j.appender.E.File =D://logs/error.log log4j.appender.E.Append = true log4j.appender.E.Threshold = ERROR log4j.appender.E.layout = org.apache.log4j.PatternLayout log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
3. Add the following content in web.xml
<context-param> <param-name>webAppRootKey</param-name> <param-value>webapp.root</param-value> </context-param> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>3000</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener>
四.如何使用
private static Logger logger = Logger.getLogger(XXX.class);
该语句获得了一个Logger,然后在需要输出日志的地方
Logger.debug ( Object message ) ; Logger.info ( Object message ) ; Logger.warn ( Object message ) ; Logger.error ( Object message ) ;
#日志等级 #TRACE:详细等级,堆栈信息 #debug:类似于System.out.print #info:类似于Hibernate的show_sql #warn:不影响运行, 只是提示 #error:出现异常
四条语句对应了4个不同的级别,debug的级别最低,error级别最高,Threshold如果设置成DEBUG,则4个级别只会输出error级别.