Why do we declare Loggers static final?

JavaLogging

Java Problem Overview


In Java, why is it best practice to declare a logger static final?

private static final Logger S_LOGGER

Java Solutions


Solution 1 - Java

  • private - so that no other class can hijack your logger
  • static - so there is only one logger instance per class, also avoiding attempts to serialize loggers
  • final - no need to change the logger over the lifetime of the class

Also, I prefer name log to be as simple as possible, yet descriptive.

EDIT: However there is an interesting exception to these rules:

protected final Logger log = LoggerFactory.getLogger(getClass());

as opposed to:

private static final Logger log = LoggerFactory.getLogger(Foo.class);

The former way allows you to use the same logger name (name of the actual class) in all classes throughout the inheritance hierarchy. So if Bar extends Foo, both will log to Bar logger. Some find it more intuitive.

Solution 2 - Java

Check this blog post: Get Rid of Java Static Loggers. This is how you use slf4j with jcabi-log:

import com.jcabi.log.Logger;
class Foo {
  void save(File f) {
    Logger.info(this, "file %s saved successfully", f);
  }
}

And never use that static noise any more.

Solution 3 - Java

static means that you only create one Logger per class, not one logger per instance of your class. Generally, this is what you want - as the loggers tend to vary solely based on class.

final means that you're not going to change the value of the logger variable. Which is true, since you almost always throw all log messages (from one class) to the same logger. Even on the rare occasions where a class might want to send some messages to a different logger, it would be much clearer to create another logger variable (e.g. widgetDetailLogger) rather than by mutating the value of a static variable on the fly.

Solution 4 - Java

When would you want to change the value of the field?

If you're never going to change the value, making the field final makes it obvious that you'll never change the value.

Solution 5 - Java

Normally you initialize the logger to log using the class name -- which means that if they weren't static, you would end up with each instance of the class having an instance of it (high memory footprint), but all of these loggers would share the same configuration and behave exactly the same. That's the reason behind the static bit. Also because each Logger is initialised with the class name, to prevent conflicts with subclasses, you declare it private so it cannot be inherited. The final comes from the point that you normally don't change the Logger during the execution -- so once initialized you never "re-configured" it -- in which case it makes sense to make it final to ensure no one can change it (by mistake or otherwise). Of course if you are going to use a Logger in a different way you might need NOT to use static final -- but I would venture to guess 80% of apps would use logging as explained above.

Solution 6 - Java

To answer that question, you should have asked yourself what "static" and "final" are for.

For a Logger, (I assume you talk about Log4J Logger class) you want a category per class. Which should lead to the fact that you assign it only once, and there is no need for more than one instance per class. And presumably there is no reason to expose the Logger object of one class to another, so why dont make it private and follow some OO-Principles.

Also you should note, that the compiler is able to take benefits of that. So your code performs a bit better :)

Solution 7 - Java

Because that is usually the kind of functionnality that can be shared accross all instances of your objects. It does not make much sense (90% of the time) to have a different logger for two instances of the same class.

However, you can also see sometimes logger classes declared as singletons or even simply offering static functions to log your stuff.

Solution 8 - Java

This code is vulnerable,but, after Java7, we can use Logger lgr = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); instead of static logger.

Solution 9 - Java

In most cases, you are not going to change the reference and final modifier marks it. You don't need separate instances for each class instance - so static. And first of all this is for performance - it can be nicely optimized (final) and saves memory (static).

Solution 10 - Java

Ideally Logger should be as follows upto Java 7, for giving no Sonar and giving a Compliant Code: private: never be accessible outside of its parent class. If another class needs to log something, it should instantiate its own logger. static: not be dependent on an instance of a class (an object). When logging something, contextual information can of course be provided in the messages but the logger should be created at class level to prevent creating a logger along with each object and hence preventing High Memory footprint. final: be created once and only once per class.

Solution 11 - Java

According the the info I read from the internet about making the logger static or not, the best practice is to use it according to the use cases.

There are two main arguments:

  1. When you make it static, it is not garbage collected (memory usage & performance).

  2. When you don't make it static it is created for each class instance (memory usage)

Thus, When you are creating a logger for a singleton, you don't need to make it static. Because there will be only one instance thus one logger.

On the other hand, if you are creating a logger for a model or entity class, you should make it static not to create duplicated loggers.

Solution 12 - Java

In addition to the reasons given in the other answers one thing I ran into was that if my logger was neither static nor final:

...
public Logger logger = LoggerFactory.getLogger(DataSummary.class);

public String toJson() {
  GsonBuilder gsonBuilder = new GsonBuilder();   
  return gsonBuilder.create().toJsonTree(this).toString();
}
...

in certain cases (when I was using the Gson library) I would get stackoverflow exception. My specific situation was to instantiate the class containing the non static non final logger. Then call the toJson method which invoked GsonBuilder:

...
DataSummary ds = new DataSummary(data);    
System.out.println(ds.toJson());
...

Solution 13 - Java

Actually static loggers can be "harmful" as they are supposed to work in a static context. When having a dynamic environment eg. OSGi it might help to use non-static loggers. As some logging implementations do a caching of loggers internally (AFAIK at least log4j) the performance impact might negligible.

One drawback of static loggers is eg. garbage collection (when a class is used only once eg. during initialization the logger will be still kept around).

For more details check:

See also:

Solution 14 - Java

We use

private - so that it remains a private data member for the class (which we usually want for every class level variable).

static - this is important. We want a single logger instance for the entire class and not that every new instance/object of the class spawns a new logger. Static key word in java is made for the same. Hence we declare it static

final - we don't want to change the value of our logger variable, rather we want it to remain constant for the entire class lifecycle.

Solution 15 - Java

You still need static logger for inner static classes

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser489041View Question on Stackoverflow
Solution 1 - JavaTomasz NurkiewiczView Answer on Stackoverflow
Solution 2 - Javayegor256View Answer on Stackoverflow
Solution 3 - JavaAndrzej DoyleView Answer on Stackoverflow
Solution 4 - JavaJon SkeetView Answer on Stackoverflow
Solution 5 - JavaLivView Answer on Stackoverflow
Solution 6 - JavaDaniel LeschkowskiView Answer on Stackoverflow
Solution 7 - JavaVincent Mimoun-PratView Answer on Stackoverflow
Solution 8 - JavankduqiView Answer on Stackoverflow
Solution 9 - JavazacheuszView Answer on Stackoverflow
Solution 10 - JavaKratika ChaurasiaView Answer on Stackoverflow
Solution 11 - JavaBahadir TasdemirView Answer on Stackoverflow
Solution 12 - JavaPaulView Answer on Stackoverflow
Solution 13 - JavaViToniView Answer on Stackoverflow
Solution 14 - JavaAkash VermaView Answer on Stackoverflow
Solution 15 - JavaAl EmuView Answer on Stackoverflow