Log4j 列印堆疊資訊
阿新 • • 發佈:2019-01-28
前幾天同事突然問了個問題讓我不大理解,先在這裡記錄下。
1.log4j.error和e.printstacktrace()有什麼區別?
我的理解當然很簡單,e.printstacktrace()是在控制檯輸出來的,logger4j是在日誌中輸出來的。
後來同事打了個啞謎還有一個是關係到buffer上的區別,對於這點其實我還是沒有怎麼搞明白,有知道的小夥伴可以來解答下。
2.logger.error(exception)和logger.error("",exception) 看很多人都是後者的寫法,為什麼就不能直接用logger.error(exception)呢?
對於這個問題我們可以對比下輸出結果就知道了,發現前者只打印一行報錯資訊,後者卻可以打印出堆疊資訊。其實這個問題可以在原始碼中探索出來。原來前者只把excetion.toString()當成message,異常資訊設定成null了。
Java程式碼
- /**
- Log a message object with the {@link Level#ERROR ERROR} Level.
- This method first checks if this category is ERROR
-
enabled by comparing the level of this category with {@link
- Level#ERROR ERROR} Level. If this category is ERROR
- enabled, then it converts the message object passed as parameter
- to a string by invoking the appropriate {@link
- org.apache.log4j.or.ObjectRenderer}. It proceeds to call all the
-
registered appenders in this category and also higher in the
- hierarchy depending on the value of the additivity flag.
- WARNING Note that passing a {@link Throwable} to this
- method will print the name of the Throwable but no
- stack trace. To print a stack trace use the {@link #error(Object,
- Throwable)} form instead.
- @param message the message object to log */
- public
- void error(Object message) {
- if(repository.isDisabled(Level.ERROR_INT))
- return;
- if(Level.ERROR.isGreaterOrEqual(this.getEffectiveLevel()))
- forcedLog(FQCN, Level.ERROR, message, null);
- }
- /**
- Log a message object with the ERROR level including
- the stack trace of the {@link Throwable} t passed as
- parameter.
- See {@link #error(Object)} form for more detailed information.
- @param message the message object to log.
- @param t the exception to log, including its stack trace. */
- public
- void error(Object message, Throwable t) {
- if(repository.isDisabled(Level.ERROR_INT))
- return;
- if(Level.ERROR.isGreaterOrEqual(this.getEffectiveLevel()))
- forcedLog(FQCN, Level.ERROR, message, t);
- }
具體的demo程式碼如下:
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.InputStream;
- import org.apache.log4j.Logger;
- public class TestLogger {
- private Logger logger=Logger.getLogger(TestLogger.class);
- public static void main(String[] args) {
- File file=new File("d:\\adfasf.txt");
- try {
- InputStream input=new FileInputStream(file);
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- new TestLogger().getLogger().info(e.toString());
- new TestLogger().getLogger().error(e);
- // new TestLogger().getLogger().error("error:",e);
- }
- }
- public Logger getLogger() {
- return logger;
- }
- public void setLogger(Logger logger) {
- this.logger = logger;
- }
- }