e.printStackTrace()打印在哪里以及如何e.printStackTrace()的内容打印在日志中

1、e.printStackTrace()打印在哪里

在catch中的e.printStackTrace()将打印到控制台

2、e.printStackTrace()打印的内容是什么

如下代码:

import org.apache.logging.log4j.Logger;

public class ExceptionTest {
    private static final Logger logger=LogManager.getLogger(); 
    public void  test() {
        try {
            int i=1/0;
            
        }catch(Exception e){    
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        ExceptionTest test= new ExceptionTest();
        test.test();
        
    }
    
}

输出结果如下:

java.lang.ArithmeticException: / by zero
    at myProject.ExceptionTest.test(ExceptionTest.java:10)
    at myProject.ExceptionTest.main(ExceptionTest.java:18)

可见,e.printStackTrace()打印了错误的具体信息,即这个错误出现的位置,便于查找错误源

3、如果将e.printStackTrace()的信息打印在日志里应该怎么做呢?

见如下代码:

package myProject;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class ExceptionTest {
    private static final Logger logger=LogManager.getLogger(); 
    public void  test() {
        try {
            int i=1/0;
            
        }catch(Exception e){    
            logger.error(e);
        }
    }
    public static void main(String[] args) {
        ExceptionTest test= new ExceptionTest();
        test.test();
        
    }
    
}

用logger.error(e);打印日志,输出结果如下:

19:17:39.753 [main] ERROR myProject.ExceptionTest - java.lang.ArithmeticException: / by zero

可见,用这种方法打印的日志,只有大概的错误信息,并没有指出报错的代码位置,不便于查找错误。用logger.error(e.getMessage());也是输出这种大概的错误信息。

再见如下代码:

package myProject;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class ExceptionTest {
    private static final Logger logger=LogManager.getLogger(); 
    public void  test() {
        try {
            int i=1/0;
            
        }catch(Exception e){    
            logger.error("ExceptionTest Exception:",e);
        }
    }
    public static void main(String[] args) {
        ExceptionTest test= new ExceptionTest();
        test.test();
        
    }
    
}

logger.error("ExceptionTest Exception:",e);,则输出结果如下:

19:20:32.948 [main] ERROR myProject.ExceptionTest - ExceptionTest Exception:
java.lang.ArithmeticException: / by zero
    at myProject.ExceptionTest.test(ExceptionTest.java:10) [classes/:?]
    at myProject.ExceptionTest.main(ExceptionTest.java:18) [classes/:?]

这和e.printStackTrace()打印的内容大致是相同的。

猜你喜欢

转载自www.cnblogs.com/BonnieWss/p/9264957.html