Ideally any object would know how to transfer itself to a ByteBuffer as fast as possible without producing garbage. You can make that happen with Encoders.
MentaLog comes out-of-the-box with 5 encoders: one for CharSequence (String, StringBuilder, etc.), one for Byte and Char arrays, one for null objects, one for ByteBuffers and one for Throwables. These encoders are included by default and you can see them by calling Log.getEncoders().
You can add your own encoders through the Log.add(Encoder) method. Encoders go on a list and are executed from end to start of the list, so last encoder added will be the first executed. That allows you to override some of the default MentaLog encoders already included. Nevertheless you can also set your own encoder list with the Log.setEncoders(List
To add an encoder, you just do:
Log.add(myEncoder);
To set a list of encoders, you just do:
Log.setEncoders(myEncoders);
Encoders are applied across all logs, even the ones you create yourself through the createLogger() method, unless you provide your own list of encoders when you call the createLogger() method.
Logger myLogger = Log.createLogger(dir, filename, isSynchronized, isAsynchronous); // will use the system wide encoders Logger myLogger = Log.createLogger(dir, filename, isSynchronized, isAsynchronous, myEncoders); // will use the provided encoders
When an encoder decides it knows how to encode the object, it transfer the contents to the ByteBuffer and return true to indicate that no other encoder in the chain should be applied, unless you want to write the object in the log twice, encoded by two different encoders, which is unusual.
Here is the CharSequenceEncoder as an example:
package org.mentalog.encoder; import java.nio.ByteBuffer; public class CharSequenceEncoder implements Encoder { @Override public boolean encode(Object obj, ByteBuffer bb) { if (obj instanceof CharSequence) { CharSequence s = (CharSequence) obj; int len = s.length(); for (int i = 0; i < len; i++) { bb.put((byte) s.charAt(i)); } return true; } return false; } }