I am guessing you are asking how one could go one step further andmake the actual logger implementation completely garbage-free.For text-based loggers, one idea is to extract the text from the specifieddomain Object (it may not be a CharSequence, but it may implementsome other interface that allows creating a text representation), and tocopy this text representation into a StringBuilder owned by the Logger.The next step is to turn the text representation into bytes which can bewritten to disk or sent over a network. For this, the loggingimplementation needs to do some work with java.nio.CharBuffer, ByteBufferand CharsetEncoders (and making this thread-safe can be quite involved).
Or maybe the
StringBuilder is provided by the logging back-end and only borrowed by
the client?
That is a very good point!(And that is one of the reasons why focusing too much on justCharBuilder would be a mistake in my opinion.)A SLF4J implementation could provide its own interface that applicationscould implement on objects that need to be logged without allocations.For example:interface StringBuilderFormattable { /** * Writes a text representation of this object into the specified * StringBuilder, ideally without allocating temporary objects. * * @param buffer the StringBuilder to write into */ void formatTo(StringBuilder buffer);}The SLF4J implementation detects that the logged Object implementsthis interface, then calls the formatTo(StringBuilder) method on it withthe StringBuilder owned by the logger. This has the advantage that theapplication no longer needs to manage any StringBuilders, and itreduces copying between various buffers. For example:
As soon as you do this, and require that the implementation start checking if particular interfaces are implemented I have to say, why not use a Message instead. The Log4j API has been doing this for years now. It has solved the problems you are bringing up nicely. In fact I am pretty sure you implemented making some Messages reusable to make them garbage free. SLf4J wouldn’t have to do this. If it were to support a MessageFactory interface Log4j’s SLF4J binding could provide MessageFactories that implement Log4j’s Message interface so SLF4J (and Log4j) would be garbage free via the logging implementation, at least for some Message classes.
Since you have admitted that you have to leave the existing methods alone, why not just go all the way?
As you well know, the Log4j API still allows users to log Strings or arbitrary Objects. Under the covers it just puts them into a Message. The benefit here is that the logging implementation doesn’t have to check for all kinds of interfaces - it just processes the Message interface. SLF4J could do the same thing.
Ralph