1. 加入log4j和slf4j的jar包
2. web.xml:
- <context-param>
- <!--log4j配置地址 -->
- <param-name>log4jConfigLocation</param-name>
- <!-- <param-value>/WEB-INF/classes/log4j.properties</param-value> -->
- <param-value>classpath:log4j.properties</param-value>
- </context-param>
- <context-param>
- <!-- log4j 配置扫描刷新间隔 可以不用 -->
- <param-name>log4jRefreshInterval</param-name>
- <param-value>10000</param-value>
- </context-param>
- <!-- spring里的log4j配置监听器 -->
- <listener>
- <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
- </listener>
3. src/log4j.properties:
- ### set log levels ###
- log4j.rootLogger = debug,stdout,D,E
- ### 输出到控制台 ###
- log4j.appender.stdout = org.apache.log4j.ConsoleAppender
- log4j.appender.stdout.Target = System.out
- log4j.appender.stdout.Threshold = INFO
- log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
- log4j.appender.stdout.layout.ConversionPattern = %d{ABSOLUTE} %5p %c{1}:%L - %m%n
- log4j.appender.stdout.Encoding=UTF-8
- ### 输出到日志文件 ###
- log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
- log4j.appender.D.File = ${ssh}WEB-INF/logs/debug.log
- log4j.appender.D.file.MaxFileSize=500KB
- log4j.appender.D.Append = true
- ##输出DEBUG级别以上的日志
- 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.D.Encoding=UTF-8
- ### 保存异常信息到单独文件 ###
- log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
- ## 异常日志文件名
- log4j.appender.E.File = ${ssh}WEB-INF/logs/error.log
- log4j.appender.E.file.MaxFileSize=500KB
- log4j.appender.E.Append = true
- ## 只输出ERROR级别以上的日志!!!
- 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
- log4j.appender.E.Encoding=UTF-8
配置info级输出到控制台,debug和error 都输出到对应文件中。
4. 使用log对象
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import com.stone.action.DefaultAction;
- public class LogUtil {
- //使用slf4j创建日志对象,好处时,以后更换为其它日志工具时,只要修改配置文件,不用修改代码
- private static Logger logger = LoggerFactory.getLogger(LogUtil.class);
- //使用log4j创建日志对象
- // private org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(getClass());
- public static void error(String message) {
- logger.error(message);
- }
- public static void debug(String message) {
- logger.debug(message);
- }
- public static void info(String message) {
- logger.info(message);
- // org.apache.log4j.Logger.getLogger(LogUtil.class).info(message);
- }
- }