将异常的堆栈跟踪转换为byte []数组或ByteBuffer(Java)是否更有效?

时间:2012-09-19 17:06:48

标签: java bytearray stack-trace bytebuffer printstacktrace

我需要将异常记录到数据库中。数据库API声明我可以将值作为ByteBuffer传递或作为byte []数组传递。哪个更有效?

private final static byte[] getThrowableStackTraceBytes(Throwable throwable) {
    StringWriter throwableStackTraceStringWriter = new StringWriter();
    throwable.printStackTrace(new PrintWriter(throwableStackTraceStringWriter));
    return throwableStackTraceStringWriter.toString().getBytes();
}

VS

private final static ByteBuffer getThrowableStackTraceByteBuffer(Throwable throwable) {
    ByteArrayOutputStream throwableStackTraceByteArrayOutputStream = new ByteArrayOutputStream();
    throwable.printStackTrace(new PrintStream(throwableStackTraceByteArrayOutputStream));
    ByteBuffer throwableByteBuffer = ByteBuffer.wrap(throwableStackTraceByteArrayOutputStream.toByteArray());
    return throwableByteBuffer;
}

我认为如果我使用ByteBuffer,整体操作会更有效率,特别是在将它传递到数据库方法后进行处理时。我是对的吗?

(具体来说,我需要将异常记录到Hypertable中,它使用Thrift Java API。)

1 个答案:

答案 0 :(得分:7)

最有效的选择就是将两者结合起来。

private final static byte[] getThrowableStackTraceBytes(Throwable throwable) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    throwable.printStackTrace(new PrintStream(baos));
    return baos.toByteArray();
}

虽然我怀疑将它写入数据库会贵很多倍。