aspose file tools*
The moose likes Java in General and the fly likes Can logger instance be static in multithreaded app? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Can logger instance be static in multithreaded app?" Watch "Can logger instance be static in multithreaded app?" New topic
Author

Can logger instance be static in multithreaded app?

Jack Tyer
Greenhorn

Joined: Feb 17, 2011
Posts: 1
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

Joined: Aug 16, 2005
Posts: 14146
    
  18

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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Saifuddin Merchant
Ranch Hand

Joined: Feb 08, 2009
Posts: 605

Yes log4J synchronizes writes (unless you use an Async appender). Watch out could be a performance problem in really big systems!


Cheers - Sam.
Twisters - The new age Java Quiz || My Blog
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Can logger instance be static in multithreaded app?