log4j.properties
log4j.rootCategory=INFO, stdout
log4j.rootLogger=info, stdout
### stdout ###
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=%d{ABSOLUTE} %5p - %m%n
### set package ###
log4j.logger.org.apache.catalina=info
log4j.logger.org.apache.commons.digester.Digester=info
log4j.logger.org.apache.catalina.startup.TldConfig=info
log4j.logger.com.dheaven=debug
配置Logger
log4j.rootCategory=level,appenderName,…
log4j.rootLogger=level,appenderName,…
Logger类是Category类的子类
常用level:ERROR、WARN、INFO、DEBUG
appenderName指定日志信息输出到哪个地方,可同时指定多个输出目的地。
配置输出目的地Appender
log4j.appender.appenderName = classInfo
log4j.appender.appenderName.option = value
Log4j提供的appender有以下几种:
- org.apache.log4j.ConsoleAppender(控制台)
- org.apache.log4j.FileAppender(文件)
- org.apache.log4j.DailyRollingFileAppender(每天产生一个日志文件)
- org.apache.log4j.RollingFileAppender(文件大小到达指定尺寸的时候产生一个新的文件)
- org.apache.log4j.WriterAppender(将日志信息以流格式发送到任意指定的地方)
当option为layout时,即配置日志信息的格式
log4j.appender.appenderName.layout = classInfo
log4j.appender.appenderName.layout.option = value
Log4j提供的layout有以下几种:
- org.apache.log4j.HTMLLayout(以HTML表格形式布局),
- org.apache.log4j.PatternLayout(可以灵活地指定布局模式),
- org.apache.log4j.SimpleLayout(包含日志信息的级别和信息字符串)
- org.apache.log4j.TTCCLayout(包含日志产生的时间、线程、类别等等信息)
设置package输出级别
log4j.logger.packageName=level
packageName为实际的包名,level为日志级别
web.xml
<servlet>
<servlet-name>log4j-init</servlet-name>
<servlet-class>InitLog4j</servlet-class>
<!--设置初始化参数-->
<init-param>
<param-name>log4j-init-file</param-name>
<param-value>WEB-INF/log4j.properties</param-value>
</init-param>
<!--设置该servlet的加载优先级-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>log4j-init</servlet-name>
<url-pattern>/init</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>InitServlet</servlet-name>
<servlet-class>InitServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>InitServlet</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
InitLog4j.java
public class InitLog4j extends HttpServlet{
@Override
public void init() throws ServletException {
String prefix=getServletContext().getRealPath("/");
prefix = prefix.replace("//", "/");
String file = getInitParameter("log4j-init-file");
if(file!=null){
//加载log4j.properties
PropertyConfigurator.configure(prefix + file);
}
}
}
InitServlet
public class InitServlet extends HttpServlet {
protected Logger log = Logger.getLogger(InitServlet.class);
private static final long serialVersionUID = 8550329576989690578L;
public InitServlet(){
super();
}
@Override
public void destroy() {
super.destroy();
}
@Override
public void init() throws ServletException {
log.info("print from log4j");
}
}