[java] how to print an exception using logger?

I have a situation in which I want to print all the exception caught in catch block using logger.

 try {
        File file = new File("C:\\className").mkdir();
        fh = new FileHandler("C:\\className\\className.log");
        logger.addHandler(fh);
        logger.setUseParentHandlers(false);
        SimpleFormatter formatter = new SimpleFormatter();
        fh.setFormatter(formatter);
    } catch (Exception e) {
        logger.info(e);
    }

i got the error logger cannot be applied to java.io.Exception...

My concern is if I do so many thing in try block and I keep only one catch block as catch(Exception e), Then is there any way using logger that print any kind of exception caught in catch block ? Note: we are using java.util.logging.Logger API

This question is related to java exception logging

The answer is


Try to log the stack trace like below:

logger.error("Exception :: " , e);

Use: LOGGER.log(Level.INFO, "Got an exception.", e);
or LOGGER.info("Got an exception. " + e.getMessage());


You can use this method to log the exception stack to String

 public String stackTraceToString(Throwable e) {
    StringBuilder sb = new StringBuilder();
    for (StackTraceElement element : e.getStackTrace()) {
        sb.append(element.toString());
        sb.append("\n");
    }
    return sb.toString();
}

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 exception

Connection Java-MySql : Public Key Retrieval is not allowed How to print an exception in Python 3? ASP.NET Core Web API exception handling Catching FULL exception message How to get exception message in Python properly What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean? what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean? Argument Exception "Item with Same Key has already been added" The given key was not present in the dictionary. Which key? sql try/catch rollback/commit - preventing erroneous commit after rollback

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?