mogronalol mogronalol - 2 months ago 14
Java Question

Java library to style exception stacktrace with html / css

I am converting the body of my exception to a string, and then emailing that exception to a given address in java. I want to format my exception string with html to make it a human readable format, similar to how it is displayed on stack overflow. I was wondering if there are any libraries in Java which do this?

StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
String body = stringWriter.toString();
//add html to body here

To elabarate, I mean things like separate the line with
, display class name names with a different coloured font, display line numbers with a different coloured font. This can be done with some regular expressions but I was wondering if there is a library that does it out of the box.


Yes, there are a couple and they even come with a "free" mail backend: Use a Java logging framework like slf4j or log4j.

All these frameworks can produce HTML emails with a bit of configuration. The general approach is like this:

  • Create a logger for all exceptions or one logger per class. The former is easier to configure, the latter gives you more freedom
  • add an appender to this logger which is configured to send emails

If you don't want to use logging in your app, you can write your own appender which reuses the existing formatters.