Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can logger instance be static in multithreaded app?

 
Jack Tyer
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In a multithreaded application, can a logger (log4j) instance be static?


I have a static method that uses logging messages, something like the code below

Public Foo{

private static Logger logger = Logger.getLogger(Foo.class.getName());

public static boolean doSomething(Boo boo){
....do something with boo.....

logger.debug("something happened");

return true/false;
}

If I want the method to be static, I have to declare my logger instance to be static. Since static variables are 1 per class and will be shared among all the instances of the class Foo, can we declare the logger instance as static?. If all the instances of class Foo try to log the messages to the one logger instance, it may cause problems, like dirty writes, am I correct? I don't want to make the method or logger instance synchronized, that's gonna hit the performance big time. In such case how to deal with the static methods that need logging in multithreaded app.

Appreciate much your replies.

Thanks,
Jack.

 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15494
43
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch.

What you're really asking is if a Log4J Logger is thread-safe. The Log4J FAQ answers this question:
Log4J FAQ wrote:
7. Is log4j thread-safe?

Yes, log4j is thread-safe. Log4j components are designed to be used in heavily multithreaded systems.
 
Saifuddin Merchant
Ranch Hand
Posts: 607
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes log4J synchronizes writes (unless you use an Async appender). Watch out could be a performance problem in really big systems!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic