1:需要的jar
log4j-1.2.14.jar
tomcat-juli-adapters.jar
tomcat-juli.jar
2:src下添加log4j.properties
<span >log4j.rootLogger=debug, stdout, log, errorlog#log4j.addivity.org.apache=true ###Console ###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} [ %p ] [ %C{1}.java :%L(%M)] %m%n### Log ### log4j.appender.log = org.apache.log4j.DailyRollingFileAppenderlog4j.appender.log.File = c:/logs/osd/log.loglog4j.appender.log.Append = truelog4j.appender.log.Threshold = DEBUGlog4j.appender.log.DatePattern='.'yyyy-MM-ddlog4j.appender.log.layout = org.apache.log4j.PatternLayoutlog4j.appender.log.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %p ] [ %C{1}.java :%L(%M)] %m%n### Error ###log4j.appender.errorlog = org.apache.log4j.DailyRollingFileAppenderlog4j.appender.errorlog.File = c:/logs/osd/errorlog.loglog4j.appender.errorlog.Append = truelog4j.appender.errorlog.Threshold = ERROR log4j.appender.errorlog.DatePattern='.'yyyy-MM-ddlog4j.appender.errorlog.layout = org.apache.log4j.PatternLayoutlog4j.appender.errorlog.layout.ConversionPattern =%-d{yyyy-MM-dd HH:mm:ss} [ %p ] [ %C{1}.java :%L(%M)] %m%n</span>
<span ></span>
<span >3:使用方法</span>
<span ></span><pre name="code" >public class BaseApi {private static Logger logger = Logger.getLogger(BaseApi.class);public BaseApi() throws Throwable {logger.debug(getClass().getSimpleName() + " has created!");}}
<span >(1)log4j.rootLogger=debug 表示日志输出的最低级别</span>
<span ></span>
<span >(2)如果使用Hibernate框架的话,还需要屏蔽Hibernate带的日志,否则很难跟踪日志。</span>
<span >第一步: <property name="hibernate.show_sql" value="false" /></span>
<span >第二步:Log4j配置文件中加入</span>
<pre name="code" ># Control logging for other open source packageslog4j.logger.com.opensymphony.oscache=ERRORlog4j.logger.net.sf.navigator=ERRORlog4j.logger.net.sf.acegisecurity=WARNlog4j.logger.net.sf.acegisecurity.intercept.event.LoggerListener=WARNlog4j.logger.org.apache.commons=ERRORlog4j.logger.org.apache.struts=WARNlog4j.logger.org.displaytag=ERRORlog4j.logger.org.springframework=WARNlog4j.logger.com.ibatis.db=WARNlog4j.logger.org.apache.velocity=WARN# Don't show debug logs for WebTestlog4j.logger.com.canoo.webtest=WARN# All hibernate log output of "info" level or higher goes to stdout.# For more verbose logging, change the "info" to "debug" on the last line.log4j.logger.org.hibernate.ps.PreparedStatementCache=WARNlog4j.logger.org.hibernate=WARN# Changing the log level to DEBUG will result in Hibernate generated# SQL to be logged.log4j.logger.org.hibernate.SQL=ERROR# Changing the log level to DEBUG will result in the PreparedStatement# bound variable values to be logged.log4j.logger.org.hibernate.type=ERROR