How to send a stacktrace to log4j?

后端 未结 11 874
失恋的感觉
失恋的感觉 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 19:57
    Try this:
    
    catch (Throwable t) {
        logger.error("any message" + t);
        StackTraceElement[] s = t.getStackTrace();
        for(StackTraceElement e : s){
            logger.error("\tat " + e);
        }   
    }
    
    0 讨论(0)
  • 2020-11-29 20:00

    Create this class:

    public class StdOutErrLog {
    
    private static final Logger logger = Logger.getLogger(StdOutErrLog.class);
    
    public static void tieSystemOutAndErrToLog() {
        System.setOut(createLoggingProxy(System.out));
        System.setErr(createLoggingProxy(System.err));
    }
    
    public static PrintStream createLoggingProxy(final PrintStream realPrintStream) {
        return new PrintStream(realPrintStream) {
            public void print(final String string) {
                logger.info(string);
            }
            public void println(final String string) {
                logger.info(string);
            }
        };
    }
    }
    

    Call this in your code

    StdOutErrLog.tieSystemOutAndErrToLog();
    
    0 讨论(0)
  • 2020-11-29 20:02

    Just because it happened to me and can be useful. If you do this

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

    you will get the header of the exception and not the whole stacktrace. Because the logger will think that you are passing a String. Do it without {} as skaffman said

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

    The answer from skaffman is definitely the correct answer. All logger methods such as error(), warn(), info(), debug() take Throwable as a second parameter:

    try {
    ...
     } catch (Exception e) {
    logger.error("error: ", e);
    }
    

    However, you can extract stacktrace as a String as well. Sometimes it could be useful if you wish to take advantage of formatting feature using "{}" placeholder - see method void info(String var1, Object... var2); In this case say you have a stacktrace as String, then you can actually do something like this:

    try {
    ...
     } catch (Exception e) {
    String stacktrace = TextUtils.getStacktrace(e);
    logger.error("error occurred for usename {} and group {}, details: {}",username, group, stacktrace);
    }
    

    This will print parametrized message and the stacktrace at the end the same way it does for method: logger.error("error: ", e);

    I actually wrote an open source library that has a Utility for extraction of a stacktrace as a String with an option to smartly filter out some noise out of stacktrace. I.e. if you specify the package prefix that you are interested in your extracted stacktrace would be filtered out of some irrelevant parts and leave you with very consized info. Here is the link to the article that explains what utilities the library has and where to get it (both as maven artifacts and git sources) and how to use it as well. Open Source Java library with stack trace filtering, Silent String parsing Unicode converter and Version comparison See the paragraph "Stacktrace noise filter"

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

    If you want to log a stacktrace without involving an exception just do this:

    String message = "";
    
    for(StackTraceElement stackTraceElement : Thread.currentThread().getStackTrace()) {                         
        message = message + System.lineSeparator() + stackTraceElement.toString();
    }   
    log.warn("Something weird happened. I will print the the complete stacktrace even if we have no exception just to help you find the cause" + message);
    
    0 讨论(0)
  • 2020-11-29 20:07

    this would be good log4j error/exception logging - readable by splunk/other logging/monitoring s/w. everything is form of key-value pair. log4j would get the stack trace from Exception obj e

        try {
              ---
              ---
        } catch (Exception e) {
            log.error("api_name={} method={} _message=\"error description.\" msg={}", 
                      new Object[]{"api_name", "method_name", e.getMessage(), e});
        }
    
    0 讨论(0)
提交回复
热议问题