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:
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);
}
}
配置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);
}
}