Should a “static final Logger” be declared in UPPE

2020-01-24 10:42发布

问题:

In Java, static final variables are constants and the convention is that they should be in upper-case. However, I have seen that most people declare loggers in lower-case which comes up as a violation in PMD.

e.g:

private static final Logger logger = Logger.getLogger(MyClass.class);

Just search googleor SO for "static final logger" and you will see this for yourself.

Should we be using LOGGER instead?

回答1:

The logger reference is not a constant, but a final reference, and should NOT be in uppercase. A constant VALUE should be in uppercase.

private static final Logger logger = Logger.getLogger(MyClass.class);

private static final double MY_CONSTANT = 0.0;


回答2:

To add more value to crunchdog's answer, The Java Coding Style Guide states this in paragraph 3.3 Field Naming

Names of fields being used as constants should be all upper-case, with underscores separating words. The following are considered to be constants:

  1. All static final primitive types (Remember that all interface fields are inherently static final).
  2. All static final object reference types that are never followed by "." (dot).
  3. All static final arrays that are never followed by "[" (dot).

Examples:

MIN_VALUE, MAX_BUFFER_SIZE, OPTIONS_FILE_NAME

Following this convention, logger is a static final object reference as stated in point 2, but because it is followed by "." everytime you use it, it can not be considered as a constant and thus should be lower case.



回答3:

From effective java, 2nd ed.,

The sole exception to the previous rule concerns “constant fields,” whose names should consist of one or more uppercase words separated by the underscore character, for example, VALUES or NEGATIVE_INFINITY. A constant field is a static final field whose value is immutable. If a static final field has a primitive type or an immutable reference type (Item 15), then it is a constant field. For example, enum constants are constant fields. If a static final field has a mutable reference type, it can still be a constant field if the referenced object is immutable.

In summary, constant == static final, plus if it's a reference (vs. a simple type), immutability.

Looking at the slf4j logger, http://www.slf4j.org/api/org/slf4j/Logger.html

It is immutable. On the other hand, the JUL logger is mutable. The log4j logger is also mutable. So to be correct, if you are using log4j or JUL, it should be "logger", and if you are using slf4j, it should be LOGGER.

Note that the slf4j javadocs page linked above has an example where they use "logger", not "LOGGER".

These are of course only conventions and not rules. If you happen to be using slf4j and you want to use "logger" because you are used to that from other frameworks, or if it is easier to type, or for readability, go ahead.



回答4:

I like Google's take on it (Google Java Style)

Every constant is a static final field, but not all static final fields are constants. Before choosing constant case, consider whether the field really feels like a constant. For example, if any of that instance's observable state can change, it is almost certainly not a constant. Merely intending to never mutate the object is generally not enough.

Examples:

// Constants
static final int NUMBER = 5;
static final ImmutableList<String> NAMES = ImmutableList.of("Ed", "Ann");
static final Joiner COMMA_JOINER = Joiner.on(',');  // because Joiner is immutable
static final SomeMutableType[] EMPTY_ARRAY = {};
enum SomeEnum { ENUM_CONSTANT }

// Not constants
static String nonFinal = "non-final";
final String nonStatic = "non-static";
static final Set<String> mutableCollection = new HashSet<String>();
static final ImmutableSet<SomeMutableType> mutableElements = ImmutableSet.of(mutable);
static final Logger logger = Logger.getLogger(MyClass.getName());
static final String[] nonEmptyArray = {"these", "can", "change"};


回答5:

If you are using an automated tool to check your coding standards and it violates said standards then it or the standards should be fixed. If you're using an external standard, fix the code.

The convention in Sun Java is uppercase for public static constants. Obviously a logger is not constant, but represents a mutable thing ( otherwise there would be no point calling methods on it in the hope that something will happen ); there's no specific standard for non-constant final fields.



回答6:

If you google this, you might find that in some cases, the loggers are not defined as static final. Add some quick copy-n-paste to this, and this might explain it.

We use LOGGER in all our code, and this corresponds to our naming convention (and our CheckStyle is happy with it).


We even go further, taking advantage of the strict naming convention in Eclipse. We create a new class with a code template of :

    // private static final Logger LOGGER = Logger.getLogger(${enclosing_type}.class);

The logger is commented out, as initially we don't need it. But should we need it later, we just uncomment it.

Then in the code, we use code templates that expect this logger to be present. Example with the try-catch template:

    try {
      ${cursor} or some other template
    } catch (Exception t) {
      LOGGER.error("${methodName} ${method parameters}", t);
    }

We have a few more templates that use it.

The strict convention allow us to be more productive and coherent with code templates.



回答7:

I personally think it looks really big in upper-case. Moreover, since it's a class that it's not directly related to the class behaviour, I don't see a major problem in using logger instead of LOGGER. But if you are going to be strictly pedantic, then use LOGGER.



回答8:

Don't forget that PMD will respect a comment with

// NOPMD

in it. This will cause PMD to skip the line from its checks, this will allow you to choose whichever style you want.



回答9:

Usually constants are in uppercase.

Loggers, however, should not be static but looked up for every "new" of the containing class if using the slf4j facade. This avoids some nasty classloader issues in notably web containers, plus it allows the logger framework to do special stuff depending on the invocation context.



回答10:

If your coding standards - if you have any - say that it should be uppercase then yes.

I don't see any stringent reason for one way or the other. I think it totally depends on your personal likes resp. your company coding standards.

BTW: I prefer "LOGGER" ;-)



回答11:

I prefer 'logger', i.e. the lower case. The reason is not that it's a constant or not a constant (mutable or immutable). If we'd use that reasoning, we'd have to rename the variable if we change the logging framework (or if the framework changes the mutability of loggers).

For me, other reasons are more important.

  1. A logger is a shadow object in the class and should not be very prominent as it does not implement the main logic. If we use 'LOGGER', it's an eye catcher in the code that attracts too much attention.

  2. Sometimes loggers are declared at instance level (i.e. not as static), and even are injected as a dependency. I wouldn't like to change my code if I decide to change the way I obtain the logger. The code stability wrt. this (hypothetical in many cases) change is the other reason why I prefer the lower case.