log实例
配置详解见2014.10月篇
log4j的pom.xml
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
log4j.properties
### direct log messages to 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 %c{1}:%L - %m%n
### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=error, A1, R
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
# Print the date in ISO 8601 format
#log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
#log4j.appender.A1.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %m%n
log4j.appender.A1.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %l "#" %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=logs/elec.log
log4j.appender.R.MaxFileSize=1000KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=10
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %l "#" %m%n
自定义一个RuntimeException
public class MyException extends RuntimeException{ public MyException(String msg) { super(msg); } }
捕获
public class TestExc { private static Logger log = Logger.getLogger(TestExc.class); public static void main(String[] args) throws NoSuchMethodException, SecurityException { try { hehe("a"); } catch (Exception e) { String errorMsg = "a"; if (e instanceof RuntimeException) { RuntimeException re = (RuntimeException) e; errorMsg = re.getMessage().trim(); } log.error(errorMsg, e); } } static void hehe(String s) { throw new MyException("aaa"); } }
日志
2016-04-14 13:15:12,028 excel.TestExc.main(TestExc.java:24) "#" aaa
excel.MyException: aaa
at excel.TestExc.hehe(TestExc.java:29)
at excel.TestExc.main(TestExc.java:17)