Search code examples
javaloggingcoding-style

What should be the position of logger in the class?


There is an ongoing discussion with friends regarding the position of the logger. According the clean code static final attributes must locate on top the class. My friend is insisting on to keep like that which is below:

public class SomeDummyClass {
    private static final String PREFIX = "xxx";
    private static final String SUFFIX = "yyy";
    private static final Logger LOG = LoggerFactory.getLogger(SomeDummyClass.class);
    // other implementations
}

Here is my suggestion:

public class SomeDummyClass {
    private static final Logger LOG = LoggerFactory.getLogger(SomeDummyClass.class);
    private static final String PREFIX = "xxx";
    private static final String SUFFIX = "yyy";
    // other implementations
}

My point of you is to keep code more readable at first look. I know there is no written rule to put log definition on top of everything but I want to hear your experiences and ideas.


Solution

  • The most common approach is for it to be at the topmost line. Also, the logger is not a constant, it is an object that is performing side effects (writing to a log), so it should not be fully capitalized.

    public class SomeDummyClass {
        private static final Logger logger = LoggerFactory.getLogger(SomeDummyClass.class);
    
        private static final String PREFIX = "xxx";
        private static final String SUFFIX = "yyy";
        // other implementations
    }
    

    All the examples below follow the same convention:

    https://www.baeldung.com/slf4j-with-log4j2-logback

    https://www.stubbornjava.com/posts/logging-in-java-with-slf4j-and-logback

    https://www.mkyong.com/spring-mvc/spring-mvc-logback-slf4j-example/

    https://www.javacodegeeks.com/2012/04/using-slf4j-with-logback-tutorial.html

    Clean Code also tells you to follow common conventions as much as possible, to minimise the amount of time and effort needed for a new developer to understand your code and navigate through it. So in this case, given that the global convention is to put the logger in this way, I would just abide with it.