[java] How to send a stacktrace to log4j?

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.FileNotFoundException: so.txt
        at java.io.FileInputStream.<init>(FileInputStream.java)
        at ExTest.readMyFile(ExTest.java:19)
        at ExTest.main(ExTest.java:7)

Now I want to send this instead to a logger like, say, log4j to get the following:

31947 [AWT-EventQueue-0] ERROR Java.io.FileNotFoundException: so.txt
32204 [AWT-EventQueue-0] ERROR    at java.io.FileInputStream.<init>(FileInputStream.java)
32235 [AWT-EventQueue-0] ERROR    at ExTest.readMyFile(ExTest.java:19)
32370 [AWT-EventQueue-0] ERROR    at ExTest.main(ExTest.java:7)

How can I do this?

try {
   ...
} catch (Exception e) {
    final String s;
    ...  // <-- What goes here?
    log.error( s );
}

This question is related to java logging log4j stack-trace

The answer is


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});
    }

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();

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.


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);
    }

Try this:

catch (Throwable t) {
    logger.error("any message" + t);
    StackTraceElement[] s = t.getStackTrace();
    for(StackTraceElement e : s){
        logger.error("\tat " + e);
    }   
}

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());
}

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);

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"


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


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.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to logging

How to redirect docker container logs to a single file? Console logging for react? Hide strange unwanted Xcode logs Where are logs located? Retrieve last 100 lines logs Spring Boot - How to log all requests and responses with exceptions in single place? How do I get logs from all pods of a Kubernetes replication controller? Where is the Docker daemon log? How to log SQL statements in Spring Boot? How to do logging in React Native?

Examples related to log4j

No log4j2 configuration file found. Using default configuration: logging only errors to the console How to stop INFO messages displaying on spark console? What is log4j's default log file dumping path How to give environmental variable path for file appender in configuration file in log4j No appenders could be found for logger(log4j)? SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". in a Maven Project log4j:WARN No appenders could be found for logger (running jar file, not web app) Error: "setFile(null,false) call failed" when using log4j java.lang.ClassNotFoundException: org.apache.log4j.Level How can I create 2 separate log files with one log4j config file?

Examples related to stack-trace

Couldn't load memtrack module Logcat Error How to Add Stacktrace or debug Option when Building Android Studio Project How to log as much information as possible for a Java Exception? e.printStackTrace equivalent in python Why is exception.printStackTrace() considered bad practice? How to store printStackTrace into a string Get exception description and stack trace which caused an exception, all as a string How to send a stacktrace to log4j? How to print full stack trace in exception? What is a stack trace, and how can I use it to debug my application errors?