Is SLF4J thread-safe?

java, logging, slf4j, thread-local, thread-safety

Solution

Certainly, everyone assumes that a `Logger` is going to be thread-safe. And (IMO) it is a reasonable working assumption. However, you would need to look at the code / javadocs of the implementation classes behind the facade to be absolutely sure.

I found the following statements on thread safety for various mainstream implementations:

- Log4j 1.2 is thread-safe

- java.util.logging.Logger is thread-safe (search for "multi-thread safe")

- Logback is thread-safe

(Obviously, these are statements that the respective code is designed to thread-safe. There can always be bugs. For example, were at the time of writing a couple of open thread-safety bugs in the Log4j 2 tracker, though it doesn't seem like those bugs would directly affect your example code.)

In fact, it is not possible to guarantee that a `Logger` will always be thread-safe. Someone could implement their own slf4j compatible logging classes. Such an implementation could be non-thread-safe, by accident or by design. If it was, then the `Logger` exposed via the slf4j facade would also be non-thread-safe.

Problem

I might have a `Dog` class that has a single instance shared across multiple threads. I plan on using SLF4J for all logging: ``` public class Dog { private Logger logger = LoggerFactory.getLogger(Dog.class); // ...etc. } ``` Is my `logger` instance thread safe? Why/why not?

Original source