子类中的 Java 记录器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5976816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:48:32  来源:igfitidea点击:

Java Logger in subclass

javalogging

提问by Nicklas

To get C.run() to use its own class logger, should I add a public/protected method getLogger() in B?

为了让 C.run() 使用它自己的类记录器,我应该在 B 中添加一个公共/受保护的方法 getLogger() 吗?

public abstract class A extends Thread {
    @Override
    public abstract void run();
}

public class B extends A {

    private static final Logger logger = Logger.getLogger(B.class.getName());

    @Override
    protected void run() {
        // do something

        logger.info("B");
    }
}

public class C extends B {
}

回答by planetjones

Well the Loggers are ideally set at Class level. So if C needs it own Logger then declare its own Logger in C e.g.

那么 Loggers 理想情况下设置在 Class 级别。所以如果 C 需要它自己的记录器,那么在 C 中声明它自己的记录器,例如

private static final Logger logger = Logger.getLogger(C.class.getName());

This way when C runs some code it logs to its own Logger and when B runs it logs to its own Logger. You'll be able to clearly see which Class logs what this way.

这样,当 C 运行某些代码时,它会记录到自己的 Logger 中,而当 B 运行时,它会记录到自己的 Logger 中。您将能够清楚地看到哪个类以这种方式记录了什么。

If this isn't what you're after please expand the question with what you're trying to achieve and why.

如果这不是您所追求的,请用您想要实现的目标以及原因来扩展问题。

I'm not convinced if the following code is a good idea (I always want the Class which is physically running the code to be the Logger) but it should work:

我不相信以下代码是否是个好主意(我总是希望实际运行代码的类是记录器),但它应该可以工作:

public abstract class A extends Thread {
    @Override
    public abstract void run();
    protected abstract Logger getLogger();
}

public class B extends A {

    private static final Logger logger = Logger.getLogger(B.class.getName());

    @Override
    public void run() {
        getLogger().info("B");
    }

    @Override
    protected Logger getLogger() {return logger;);  
}

public class C extends B {

    private static final Logger logger = Logger.getLogger(C.class.getName());

    @Override
    protected Logger getLogger() {return logger;);  
}

回答by StKiller

You may use this in base class:

您可以在基类中使用它:

protected Logger logger = Logger.getLogger(this.getClass().getName());

this.getClass()will initialize the logger with subclass name.

this.getClass()将使用子类名称初始化记录器。