log4jcheckstyle

How to configure checkstyle for log4j


I want to disallow code like this:

private static final Logger LOGGER = LogManager.getLogger(...)
...
...

LOGGER.info("User(%s) not found.", userId);

It is better to do like this:

LOGGER.info("User({}) not found.", userId);

how to configure checkstyle for catching these errors?


Solution

  • There is likely no standard check to disallow this (at least in the official page).

    For 99% of cases the following custom check based on regex (RegexpSingleLineJava) will work:

    <module name="RegexpSinglelineJava">
      <property name="format" value="(LOGGER|LOG|logger|log)\.[a-z]+\(.*%s"/>
      <property name="ignoreComments" value="true"/>
      <property name="message" value="Formatting with %s in Log4J log strings is not allowed, use {} instead" />
    </module>
    

    The regexp locates a logger followed by a dot, multiple letters (i.e. info, warn, error, etc.), opening brace and %s after some arbitrary characters. The comments are ignored.

    Limitations:

    LOGGER.warn("This is an extremely awful code style."); String str = String.format("%s", "someText");
    

    Writing a custom Checkstyle check may help to overcome these limitations however I'm not sure that it worth it in real projects. If the goal is to tell your developers to stop using %s in logs rather than finding every single occurrence of this situation, then using single-line regex check should be totally fine.