常用 Log4j 打印日志的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class TestLog {
  private static Logger log = Logger.getLogger(TestLog.class);
  public static void main(String[] args) {
    test1();
    System.out.println("--------------------------");
    test2();
  }
  public static void test1(){
    try {
      int x = 1 / 0;
    } catch (Exception e) {
      log.error("", e);
    }
  }
  public static void test2(){
    try {
      int x = 1 / 0;
    } catch (Exception e) {
      log.error(e);
    }
  }
}

代码中test1 和test2 打印区别是: test1() 会打印出Exception e的异常堆栈信息, test2()只会打印出Exception 的 message 信息

其结果:

` 14/12/09 19:14:57 ERROR common.TestLog:

-————————-

java.lang.ArithmeticException: / by zero at com.flyover.test.common.TestLog.test1(TestLog.java:19) at com.flyover.test.common.TestLog.main(TestLog.java:12) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134) 14/12/09 19:14:57 ERROR common.TestLog: java.lang.ArithmeticException: / by zero `