Skip to content

Instantly share code, notes, and snippets.

@chabala
Created November 9, 2025 17:16
Show Gist options
  • Select an option

  • Save chabala/eb2459ac22f9913e123076ea7ed03aac to your computer and use it in GitHub Desktop.

Select an option

Save chabala/eb2459ac22f9913e123076ea7ed03aac to your computer and use it in GitHub Desktop.
SLF4J best practice for logger declaration

SLF4J has a note in the FAQ about a recommended idiom for declaring a logger, which uses MethodHandles to avoid naming the logger explicitly, which makes it easy to copy into a new class or include in a new file template.

After switching to static imports for both the MethodHandle and the LoggerFactory, this becomes the most unintrusive form I've ever seen, with both a short line length and requiring few import lines:

import org.slf4j.Logger;

import static java.lang.invoke.MethodHandles.lookup;
import static org.slf4j.LoggerFactory.getLogger;

public class Example {
    private static final Logger log = getLogger(lookup().lookupClass());
    
}

This pattern can be used in Java 7 and above (when MethodHandles was introduced).

I would much rather see this than Lombok's @Slf4j annotation, because it is less magical, and doesn't require Lombok, which should be avoided in general.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment