log4j的使用分为几种情况:
1.配置log4j.properties文件。
2.获取logger对象。
3.记录日志。
例子:struts2使用log4j:
配置文件:log4j.properties
#config root logger
log4j.rootLogger = INFO,system.out
log4j.appender.system.out=org.apache.log4j.ConsoleAppender
log4j.appender.system.out.layout=org.apache.log4j.PatternLayout
log4j.appender.system.out.layout.ConversionPattern=this4j-->%5p{%F:%L}-%m%n%n
#config this Project.file logger
log4j.logger.thisProject.file=INFO,thisProject.file.out
#set the log location on the hard disk
log4j.appender.thisProject.file.out=org.apache.log4j.DailyRollingFileAppender
#set the location in the tomcat root file
#log4j.appender.thisProject.file.out.File=d:\\log.txt
log4j.appender.thisProject.file.out.File=${catalina.home}/logs/logs_tomcat.log
log4j.appender.thisProject.file.out.layout=org.apache.log4j.PatternLayout
log4j.appender.thisProject.file.out.layout.ConversionPattern=log4j-->%d{yyyy MMM dd HH\:mm\:ss,SSS}%p{%F\:%L}-%m%n%n
BaseAction:
import org.apache.log4j.Logger;
import com.opensymphony.xwork2.ActionSupport;
public class BaseAction extends ActionSupport {
//把logger在基础的servlet里面进行初始化,这样其他的所有的servlet都可以继承这个类
//然后就可以在程序运行期间直接的使用它了,而不必再自己去获取一个logger对象了
Logger loggerFile;
private static final long serialVersionUID = 1L;
public BaseAction() {
//这个地方就不需要再对手动的加载log4j.properties文件了,tomcat会加载的
//PropertyConfigurator.configure(projectRealPath+"log4j.properties");
loggerFile = Logger.getLogger("thisProject.file");
}
}
TestBaseAction:
public class TestBaseAction extends BaseAction {
private static final long serialVersionUID = 1L;
@Override
public String execute() throws Exception {
loggerFile.info("我继承了BaseAction");
loggerFile.warn("警告要出错啦");
return SUCCESS;
}
}