配置Log4J2的异常堆栈跟踪

16-10-09 banq
    

有时我们在日志文件中不需要记录异常栈跟踪信息或者限制栈跟踪最大深度,在Java中,栈跟踪信息超过500行很常见,每天都可能有数千个这样的情况。

使用Lo4j2容易配置规定在日志中出现多少栈跟踪信息,下面是三个案例:

1.记录异常信息,但是隐去整个栈跟踪信息:

# log4j2.yml
Configuration:
 Appenders:
  Console:
   — name: NoStackTrace
     target: SYSTEM_OUT
     PatternLayout:
      Pattern: “[%t] %-5level %logger{36} %msg — %ex{short.message} %n”
<p>

日志结果会是出现:

<p>[main] ERROR org.behrang.labs.Main An error occurred — I am thrown from a rogue method
<p>

2.记录异常信息和其栈跟踪第一行:

# log4j2.yml
Configuration:
 Appenders:
  Console:
   — name: FirstLineOfStackTrace
     target: SYSTEM_OUT
     PatternLayout:
      Pattern: “[%t] %-5level %logger{36} %msg — %ex{short} %n”
<p>

日志结果是:

<p>[main] ERROR org.behrang.labs.Main An error occurred — java.lang.Exception: I am thrown from a rogue method
 at org.behrang.labs.Main.rogueMethod(Main.java:22)
<p>

3.记录异常信息和栈跟踪头5行。

#log4j2.yml
Configuration:
 Appenders:
  Console:
   — name: FirstFiveLines
     target: SYSTEM_OUT
     PatternLayout:
      Pattern: “[%t] %-5level %logger{36} %msg — %ex{5} %n”
<p>

日志结果:

<p>[main] ERROR org.behrang.labs.Main An error occurred — java.lang.Exception: I am thrown from a rogue method
 at org.behrang.labs.Main.rogueMethod(Main.java:22)
 at org.behrang.labs.Main.main(Main.java:15)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
<p>

Configuring how exception stack traces appear in l

    

2