Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Need a logging package that will log the stacktrace

Tags:

java

logging

Is there a Logger that will easily log my stacktrace (what I get with ex.printStackTrace())? I've searched the log4j docs and found nothing about logging the stacktrace.

I can do this myself with

StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
logger.error(stacktrace);

but I don't want to duplicate this code all over the place.

If log4j won't do this for me is there another logging package that will log the stacktrace for me?

Thanks.

like image 528
Yatendra Avatar asked Feb 25 '10 06:02

Yatendra


2 Answers

Using log4j this is done with:

logger.error("An error occurred", exception);

The first argument is a message to be displayed, the second is the exception (throwable) whose stacktrace is logged.

Another option is commons-logging, where it's the same:

log.error("Message", exception);

With java.util.logging this can be done via:

logger.log(Level.SEVERE, "Message", exception);
like image 171
Bozho Avatar answered Oct 12 '22 03:10

Bozho


In java.util.logging you can initialize the logger with custom log formatter like here:

private Logger initTextLogger() throws SecurityException, IOException {
        Logger logger = Logger.getLogger(YourClass.class.getName());
        FileHandler fileHandler = new FileHandler(logFilePath, false);
        SimpleFormatter logFormatter = new SimpleFormatter() {
            @Override
            public String format(LogRecord record) {
            String stacktrace = "";
            Throwable t = record.getThrown();
            if(t!=null){
                StringWriter sw = new StringWriter();
                t.printStackTrace(new PrintWriter(sw));
                stacktrace = sw.toString();
            }               
            return record.getLevel() + ": " + record.getMessage() + "\r\n"
                    + stacktrace;
        }
        };
        fileHandler.setFormatter(logFormatter);
        logger.addHandler(fileHandler);

        return logger;
    }
like image 39
Aram Paronikyan Avatar answered Oct 12 '22 02:10

Aram Paronikyan