26

I was catching an exception and trying to write the stack trace to the logs like this:

log.warn(e.getMessage());

But all it said was

null

So I changed it to

log.warn(e.toString());

And now it says only

java.lang.NullPointerException

How do I write the full stack trace to the log so I can see where this Exception is being generated in the app?

Linc
  • 673
  • 2
  • 11
  • 16

6 Answers6

40

Usually:

log.warn("message", e);

But it depends on your logging framework too.

Peter Štibraný
  • 32,463
  • 16
  • 90
  • 116
9

You can use

logger.log(Level.WARN, "logged exception", ex);

or

logger.warn("logged exception", ex);

Resources :

Colin Hebert
  • 91,525
  • 15
  • 160
  • 151
6

If you using Java 8 you can do the following:

LOGGER.error("Caught exception while methodX. Please investigate: " 
    + exception 
    + Arrays.asList(exception.getStackTrace())
    .stream()
    .map(Objects::toString)
    .collect(Collectors.joining("\n"))
);
Piotr Niewinski
  • 1,298
  • 2
  • 15
  • 27
nishant
  • 955
  • 2
  • 11
  • 27
  • It works just fine and it's also useful during debugging sessions when exceptions are not properly logged. – alexandrul Oct 18 '17 at 12:38
  • I experienced processing above was much slower than log.error("message", e); I have tried on my debug session, worth checking it out especially if you write a global handler. – Charith De Silva Apr 03 '18 at 05:23
  • 2
    Arrays.asList(...).stream() can be simplified to Arrays.stream(e.getStackTrace()) – Shadoninja Sep 07 '18 at 21:20
5

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);
Hearen
  • 7,420
  • 4
  • 53
  • 63
Joe M
  • 2,527
  • 1
  • 25
  • 25
3

In your exception method, the underlying String which contains the message is null.

The above answer, now struck out, still holds, except that e is not null, but the detailMessage private instance variable on the Throwable class is null, which is why e.getMessage() is the String null, but e.toString() (which calls underlying null detailMessage.toString) throws a NullPointerException.

Joshua Taylor
  • 84,998
  • 9
  • 154
  • 353
Noel M
  • 15,812
  • 8
  • 39
  • 47
0

If you are using a Java version previous to 8, you can try this:

            LOGGER.error("Error al recuperar proveedores de la base de datos: " + 
            e + Arrays.asList(e.getStackTrace()).stream().map(new Function(){
                    @Override
                    public Object apply(Object t) {
                        return t.toString();
                    }
                }).collect(Collectors.joining("\n")));
RafaJR
  • 1