子类中的 Java Logger
为了让 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 {
}
To get C.run() to use its own class logger, should I add a public/protected method getLogger() in B?
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 {
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
记录仪最好设置在班级级别。因此,如果 C 需要它自己的 Logger,则在 C 中声明它自己的 Logger,例如
这样,当 C 运行某些代码时,它会记录到它自己的 Logger,当 B 运行时,它会记录到它自己的 Logger。您将能够清楚地看到哪个类通过这种方式记录了什么。
如果这不是您想要的,请扩展问题,说明您想要实现的目标以及原因。
我不相信以下代码是否是一个好主意(我总是希望物理运行代码的类成为记录器),但它应该可以工作:
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.
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.
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:
您可以在基类中使用它:
this.getClass()
将使用子类名称初始化记录器。You may use this in base class:
this.getClass()
will initialize the logger with subclass name.