Tomas Zaoral Tomas Zaoral - 1 month ago 8
Java Question

Logging from default interface methods

Salut to all Java gurus!

Since Java8 we can have default implementations in interfaces (yay!).
However problem arises when you want to log from default method.

I have a feeling that it is not wise to call .getLogger() every time I want to log something in a default method.

Yes, one can define static variable in an interface - but that is not a good practice for interfaces anyway + it exposes the logger (must be public).

Solution I have at the moment:

interface WithTimeout<Action> {

default void onTimeout(Action timedOutAction) {
LogHolder.LOGGER.info("Action {} time out ignored.", timedOutAction);
}

static final class LogHolder {
private static final Logger LOGGER = getLogger(WithTimeout.class);
}
}


LogHolder is still visible to everybody which doesn't really make any sense since it does not provide any methods and it should be internal to the interface.

Does any of you know about better solution? :)

EDIT: I use SLF4J backed by Logback

Answer

If you don’t want to expose the class LogHolder to the public, don’t make it a member class of the interface. There is no benefit in making it a member class, you don’t even save typing as you have to qualify the field access with the name of the holder class anyway, regardless of whether it is a member class or a class within the same package:

public interface WithTimeout<Action> {

    default void onTimeout(Action timedOutAction) {
        LogHolder.LOGGER.info("Action {} time out ignored.", timedOutAction);
    }
}
final class LogHolder { // not public
    static final Logger LOGGER = getLogger(WithTimeout.class);
}
Comments