配置Log4J2的异常堆栈跟踪

    
banq
16-10-09 0 557 2

有时我们在日志文件中不需要记录异常栈跟踪信息或者限制栈跟踪最大深度,在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”


日志结果会是出现:

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


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

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


日志结果是:

[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)


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

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


日志结果:

[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)


Configuring how exception stack traces appear in l

2