[英]How do I implement logging in an enum singleton?
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: 记录器以我为普通Java类实例化记录器的方式实例化,但当然我收到以下错误:
Foo.java: illegal reference to static field from initializer
Is there an equivalent way to log in enum singletons? 是否有相同的方式登录枚举单身?
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 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... 大多数使用记录器的例子都有记录器作为静态属性......
动态记录:
Logger.getLogger(Foo.class.getName()).info("log info");
A bit shorter: use a method: logger().debug(...) 更短一点:使用方法: logger()。debug(...)
private static Logger logger()
{
if(logger == null)
{
logger = Logger.getLogger(AnEnum.class);
}
return logger;
}
/** Logger **/
private static Logger logger;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.