log4j.properties
log4j.rootCategory=INFO, stdoutlog4j.rootLogger=info, stdout### stdout ###log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.outlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p - %m%n### set package ###log4j.logger.org.apache.catalina=infolog4j.logger.org.apache.commons.digester.Digester=infolog4j.logger.org.apache.catalina.startup.TldConfig=infolog4j.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 = valueLog4j提供的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 = valueLog4j提供的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
log4j-init InitLog4j log4j-init-file WEB-INF/log4j.properties 1 log4j-init /init InitServlet InitServlet 2 InitServlet /test
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"); }}