SPIRiT_1984
SPIRiT_1984

Reputation: 2767

Is log4j thread-safe?

I have a following question. We use log4j in our two projects, that are hosted on the same GlassFish server. Each project has inside log4j.properties file, that points to the files, that are based in different catalogs (let's name them Project1 and Project2).

Now, for some unclear reasons sometimes the info messages of the first project are written to Project2 log files, and the reverse is also true. I checked the log4j.properties files for both of the projects, there is nothing pointing in them to the log of the other project.

The suspicion is that log4j is not actually thread-safe, therefore if two users are working in two systems in the same time, the messages of the loggers can get mixed. Is this suspicion correct?

Upvotes: 4

Views: 9723

Answers (2)

pls
pls

Reputation: 575

Yes, log4j is thread safe. The reason is the method AppenderSkeleton.doAppend() is synchronized. But be carefull configuring programmatically! For example you can't use the same instance of TTCCLayout in different appenders(read javadoc)! Take a look at PatternLayout method format(). It changes instance field(StringBuffer sbuf), so if you use same PatternLayout instance in different appenders you are to face race conditions. EnhancedPatternLayout is better, cause they modified format method.

Upvotes: 4

Mitch Wheat
Mitch Wheat

Reputation: 300529

Yes, log4j is thread safe:

Yes, log4j is thread-safe. Log4j components are designed to be used in heavily multithreaded systems.

Ref.

What you are describing sounds more like a config mistake, rather than a cross process/threading issue.

Upvotes: 7

Related Questions