As of SLF4J version 1.5.3, logger instances survive serialization. Thus, serialization of the host class no longer requires any special action, even when loggers are declared as instance variables.
This is true of the official bindings, but not slf4j-test.
Test case (can be added to TestLoggerTests.java):
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
public class TestLoggerTests {
// ...
@Test
public void serializable() throws IOException, ClassNotFoundException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
new ObjectOutputStream(outStream).writeObject(testLogger);
ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
TestLogger deserializedLogger = (TestLogger) new ObjectInputStream(inStream).readObject();
deserializedLogger.info(message);
assertEquals(asList(info(mdcValues, message)), deserializedLogger.getLoggingEvents());
}
}
Test output:
serializable(uk.org.lidalia.slf4jtest.TestLoggerTests) Time elapsed: 0.095 sec <<< ERROR!
java.io.NotSerializableException: uk.org.lidalia.slf4jtest.TestLogger
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at uk.org.lidalia.slf4jtest.TestLoggerTests.serializable(TestLoggerTests.java:313)
Current workarounds include:
Use static loggers instead of per-instance loggers
In Scala, instance loggers can be marked lazy transient
The SLF4J FAQ states:
This is true of the official bindings, but not slf4j-test.
Test case (can be added to
TestLoggerTests.java
):Test output:
Current workarounds include:
lazy transient
(By the way, thanks for the great library!)