如何在枚举单例中实现日志记录?
我使用的是枚举单例,但实现日志记录很麻烦。这:
public enum Foo {
INSTANCE;
private final Logger log = Logger.getLogger(Foo.class.getName());
...
}
记录器的实例化方式与我为普通 Java 类实例化记录器的方式相同,但我当然会收到以下错误:
Foo.java: illegal reference to static field from initializer
是否有等效的方法来登录枚举单例?
I'm using an enum singleton, but implementing logging is troublesome. This:
public enum Foo {
INSTANCE;
private final Logger log = Logger.getLogger(Foo.class.getName());
...
}
The logger is instantiated in the way that I would instantiate a logger for a normal Java class, but of course I get the following error:
Foo.java: illegal reference to static field from initializer
Is there an equivalent way to log in enum singletons?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为了回答你的问题,只需将记录器设置为静态...
顺便说一句,我认为即使对于对象实例也使用静态记录器是标准做法。换句话说,记录器在类上;所有对象都使用静态记录器引用。
请参阅
http://logging.apache.org/log4j/1.2/manual.html
那里使用记录器的大多数示例都将记录器作为静态属性......
In answer to your question, just make the logger static...
BTW, I think its standard practice to use a static logger even for object instances. In other words, the logger is on the class; all objects use the static logger references.
See
http://logging.apache.org/log4j/1.2/manual.html
Most of the examples of using a logger in there have the logger as a static property...
动态记录:
Log dynamically:
更短一点:使用方法:logger().debug(...)
A bit shorter: use a method: logger().debug(...)