Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

Foo.java: illegal reference to static field from initializer 

Is there an equivalent way to log in enum singletons?

like image 691
Eric Nguyen Avatar asked Nov 24 '10 22:11

Eric Nguyen


1 Answers

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

like image 139
hvgotcodes Avatar answered Sep 18 '22 18:09

hvgotcodes