log4j.properties文件配置:
#Output pattern : date [thread] priority category - message
log4j.rootLogger=INFO,Console,RollingFile,ExceptionFile
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Threshold=WARN
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
#RollingFile
log4j.appender.RollingFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.RollingFile.File=./logs/web.log
log4j.appender.RollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.RollingFile.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
#ExceptionFile
log4j.appender.ExceptionFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.ExceptionFile.Threshold=ERROR
log4j.appender.ExceptionFile.File=./logs/exception.log
log4j.appender.ExceptionFile.layout=org.apache.log4j.PatternLayout
log4j.appender.ExceptionFile.layout.ConversionPattern=%d [%t] %-5p [%c] Userexception: %n%m%n%n
类中这样写:
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class LogFile
{
private Log log = LogFactory.getLog(this.getClass());
public void log()
{
try
{
String string = "";
string.charAt(2);
}
catch (Exception e)
{
log.error("异常信息:",e);
}
}
}
log4j.rootLogger=INFO,Console,RollingFile,ExceptionFile
log4j.appender.ExceptionFile.Threshold=ERROR
日志输出级别顺序(低到高): DEBUG < INFO < WARN < ERROR < FATAL
log4j.rootLogger的输出级别只要低于或等于ERROR即可,在异常级别log4j.appender.XX.Threshold过滤比它低的即可