[英]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. 我正在将异常的主体转换为字符串,然后将该异常通过电子邮件发送到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.
我想用html格式化我的异常字符串,使其成为一种人类可读的格式,类似于它在堆栈溢出时的显示方式。 I was wondering if there are any libraries in Java which do this?
我想知道Java中是否有任何库可以执行此操作?
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
t.printStackTrace(printWriter);
String body = stringWriter.toString();
//add html to body here
setMessageBody(body);
To elabarate, I mean things like separate the line with <br/>
, display class name names with a different coloured font, display line numbers with a different coloured font. 为了详细说明,我的意思是将行与
<br/>
分开,使用不同颜色的字体显示类名称,使用不同颜色的字体显示行号。 This can be done with some regular expressions but I was wondering if there is a library that does it out of the box. 这可以通过一些正则表达式完成,但我想知道是否有一个开箱即用的库。
It doesn't do colors, but a really simple approach is to wrap the stack trace in a HTML <pre>
element. 它不做颜色,但一个非常简单的方法是将堆栈跟踪包装在HTML
<pre>
元素中。 That will at least preserve the whitespaces and new lines. 这将至少保留空白和新行。
For example 例如
<pre>
java.lang.ClassCastException: java.lang.Double cannot be cast to java.math.BigDecimal
at org.hibernate.type.descriptor.java.BigDecimalTypeDescriptor.unwrap(BigDecimalTypeDescriptor.java:36)
at org.hibernate.type.descriptor.sql.DecimalTypeDescriptor$1.doBind(DecimalTypeDescriptor.java:65)
at org.hibernate.type.descriptor.sql.BasicBinder.bind(BasicBinder.java:90)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:286)
</pre>
Yes, there are a couple and they even come with a "free" mail backend: Use a Java logging framework like slf4j or log4j . 是的,有一对,他们甚至带有“免费”邮件后端:使用像slf4j或log4j这样的Java日志框架。
All these frameworks can produce HTML emails with a bit of configuration. 所有这些框架都可以生成带有一些配置的HTML电子邮件。 The general approach is like this:
一般方法是这样的:
If you don't want to use logging in your app, you can write your own appender which reuses the existing formatters. 如果您不想在应用程序中使用日志记录,则可以编写自己的appender,重用现有的格式化程序。
I wrote this, https://github.com/StefanLiebenberg/html-exception-formatter 我写了这个, https://github.com/StefanLiebenberg/html-exception-formatter
Its a simple utility to format exceptions as readable html. 它是将异常格式化为可读html的简单实用程序。
String html = new HtmlExceptionFormatter().toString(exception);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.