Mahoney / slf4j-test

Implementation of SLF4J which allows easy access to logging events in tests
39 stars 24 forks source link

TestLogger is not serializable #14

Open toddmowen opened 8 years ago

toddmowen commented 8 years ago

The SLF4J FAQ states:

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:

(By the way, thanks for the great library!)