在Java里怎样把exception的stacktrace压缩到一行?

在Java里怎样把exception的stacktrace压缩到一行?

一般在Java里,我们可以用printStackTrace把stacktrace打印出来。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
try {
// do something
} catch (Exception e) {
e.printStackTrace();
}
try { // do something } catch (Exception e) { e.printStackTrace(); }
try {
    // do something
} catch (Exception e) {
    e.printStackTrace();    
}

在server里,如果我们需要用graylog来search log,就需要把stacktrace压缩到一行。我们可以用apache的ExceptionUtils

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import org.apache.commons.lang.exception.ExceptionUtils;
//...
try {
// do something
} catch (Exception e) {
logger.error("Exception: {}",
ExceptionUtils.getStackTrace(e)
);
}
import org.apache.commons.lang.exception.ExceptionUtils; //... try { // do something } catch (Exception e) { logger.error("Exception: {}", ExceptionUtils.getStackTrace(e) ); }
import org.apache.commons.lang.exception.ExceptionUtils;
//...

try {
    // do something
} catch (Exception e) {
    logger.error("Exception: {}", 
        ExceptionUtils.getStackTrace(e)
    );
}

Leave a Comment

Your email address will not be published.