Lombok @Slf4j and interfaces?

10.6k views Asked by At

I am trying to add logging to my interface default method. For example:

@Slf4j // not allowed
interface MyIFace {
    default ThickAndThin doThisAndThat() {
        log.error("default doThisAndThat() called"); 
    }
}

Problem is that I get:

@Slf4j is legal only on classes and enums.

What would be the proper way to deal with this?

2

There are 2 answers

3
Andrei Kovrov On BEST ANSWER

You can't use Lombok here because the annotation generates:


private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(YourClass.class);

You can't use private keyword with an interface.

The workaround is to write directly


interface MyIFace {

   org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(MyIFace.class);

   default ThickAndThin doThisAndThat() {
     log.error("default doThisAndThat() called"); 
   }

}


0
user2786531 On

With Java 9+ you could use private methods to prevent logger from being public static

public interface MyIFace {
    private Logger log() {
        return LoggerFactory.getLogger(MyIFace.class);
    }

    default void doThisAndThat() {
        log().error("default doThisAndThat() called");
    }
}