org.mentalog.encoder.ThrowableEncoder Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of menta-log Show documentation
Show all versions of menta-log Show documentation
A log library that embraces the kiss principle.
package org.mentalog.encoder;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.ByteBuffer;
public class ThrowableEncoder implements Encoder {
@Override
public boolean encode(Object obj, ByteBuffer bb, int varargsPos, int varargsLen) {
if (obj instanceof Throwable) {
Throwable t = (Throwable) obj;
if (varargsPos == varargsLen - 1) { // last argument...
String s = getStackTrace(t); // sorry...
bb.put((byte) '\n');
transfer(s, bb);
} else {
transferToString(t, bb);
}
return true;
}
return false;
}
private final static void transfer(CharSequence s, ByteBuffer bb) {
int len = s.length();
for (int i = 0; i < len; i++) {
bb.put((byte) s.charAt(i));
}
}
private final static void transferToString(Throwable t, ByteBuffer bb) {
transfer(t.getClass().getName(), bb);
String msg = t.getLocalizedMessage();
if (msg != null) {
bb.put((byte) ':');
bb.put((byte) ' ');
transfer(msg, bb);
}
}
public static String getStackTrace(Throwable throwable) {
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
throwable.printStackTrace(printWriter);
return writer.toString();
}
}