How to send a stacktrace to log4j?

后端 未结 11 875
失恋的感觉
失恋的感觉 2020-11-29 19:29

Say you catch an exception and get the following on the standard output (like, say, the console) if you do a e.printStackTrace() :

java.io.FileNotFo         


        
相关标签:
11条回答
  • 2020-11-29 20:09

    You can also get stack trace as string via ExceptionUtils.getStackTrace.

    See: ExceptionUtils.java

    I use it only for log.debug, to keep log.error simple.

    0 讨论(0)
  • 2020-11-29 20:12

    This answer may be not related to the question asked but related to title of the question.

    public class ThrowableTest {
    
        public static void main(String[] args) {
    
            Throwable createdBy = new Throwable("Created at main()");
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            PrintWriter pw = new PrintWriter(os);
            createdBy.printStackTrace(pw);
            try {
                pw.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            logger.debug(os.toString());
        }
    }
    

    OR

    public static String getStackTrace (Throwable t)
    {
        StringWriter stringWriter = new StringWriter();
        PrintWriter  printWriter  = new PrintWriter(stringWriter);
        t.printStackTrace(printWriter);
        printWriter.close();    //surprise no IO exception here
        try {
            stringWriter.close();
        }
        catch (IOException e) {
        }
        return stringWriter.toString();
    }
    

    OR

    StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
    for(StackTraceElement stackTrace: stackTraceElements){
        logger.debug(stackTrace.getClassName()+ "  "+ stackTrace.getMethodName()+" "+stackTrace.getLineNumber());
    }
    
    0 讨论(0)
  • 2020-11-29 20:16

    You can use bellow code:

    import org.apache.logging.log4j.Logger;
    import org.apache.logging.log4j.LogManager;
    
    public class LogWriterUtility {
        Logger log;
    
        public LogWriterUtility(Class<?> clazz) {
            log = LogManager.getLogger(clazz);
        }
    
    public void errorWithAnalysis( Exception exception) {
    
            String message="No Message on error";
            StackTraceElement[] stackTrace = exception.getStackTrace();
            if(stackTrace!=null && stackTrace.length>0) {
                message="";
                for (StackTraceElement e : stackTrace) {
                    message += "\n" + e.toString();
                }
            }
            log.error(message);
    
    
        }
    
    }
    

    Here you can just call : LogWriterUtility.errorWithAnalysis( YOUR_EXCEPTION_INSTANCE);

    It will print stackTrace into your log.

    0 讨论(0)
  • 2020-11-29 20:20

    You pass the exception directly to the logger, e.g.

    try {
       ...
    } catch (Exception e) {
        log.error( "failed!", e );
    }
    

    It's up to log4j to render the stack trace.

    0 讨论(0)
  • 2020-11-29 20:22

    In Log4j 2, you can use Logger.catching() to log a stacktrace from an exception that was caught.

        try {
            String msg = messages[messages.length];
            logger.error("An exception should have been thrown");
        } catch (Exception ex) {
            logger.catching(ex);
        }
    
    0 讨论(0)
提交回复
热议问题