从默认接口方法记录 [英] Logging from default interface methods

查看:129
本文介绍了从默认接口方法记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

向所有Java大师致敬!

Salut to all Java gurus!

从Java8开始,我们可以在接口中使用默认实现(是的!)。
但是当你想从默认方法登录时会出现问题。

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

我觉得每次我想要调用.getLogger()是不明智的。用默认方法记录一些东西。

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).

我现在的解决方案:

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没有任何意义,因为它没有提供任何方法,它应该是界面内部的。

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? :)

编辑:我使用由Logback支持的SLF4J

I use SLF4J backed by Logback

推荐答案

如果您不想将类 LogHolder 公开给公众,请不要将其作为接口的成员类。使它成为成员类没有任何好处,你甚至不保存输入,因为你必须使用持有者类的名称限定字段访问,无论它是成员类还是同一个包中的类:

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

这篇关于从默认接口方法记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆