Search code examples
javaloggingslf4jlombokdefault-method

Lombok @Slf4j and interfaces?


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?


Solution

  • 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"); 
       }
    
    }