Static v Non-static loggers
One of my co-developers prefers non static loggers over static loggers, ie
private Log log = LogFactory.getLog(getClass());
over
public static Log log = LogFactory.getLog(Foo.class);
beacuse it is easer to copy and paste between classes.
Non-static is bad iin classes that may have many instances of course (because it creates a logger per instance) but often you are using loggers in singletons or few-instance classes and its more convenient to use non-static.
But there’s a nasty gotcha that just got us.
If you serialize a class with a non-static instance, the whole logger (in log4j the whole category) gets serialized with it. This can be really seriously nasty if, for example, youare sending what you expect to be small XML serialized messages across a network, and end up with whole log categories (thousands of extra lines) flying back and forth.
Of course its OK if you make the logger transient, but static is better.
(apologies to Paul)
June 19th, 2003 at 4:01 pm
Greg - I hope you are joking about that stack trace parsing ;-) Yuck!
Here, we use Eclipse and we just added a Template to cover this: Preferences -> Java -> Editor -> Templates. We created one with the name “logger” and pattern “private static final Logger LOGGER = Logger.getLogger(${enclosing_type}.class);” Now, any time we want to add a logger to a class, we just type logger and hit Ctrl + Space and viola! Most decent IDEs will let you do this.
Ryan
June 21st, 2003 at 10:54 pm
Try this variation on the template idea instead:
private static final Logger log = Logger.getLogger(”${enclosing_package}.${enclosing_type}”);
The difference is that your loggers end up using the fully qualified name.
September 4th, 2003 at 11:14 pm
Instance-specific loggers do have a place, where their very individuality imparts on the nature of the logging. To take a trivial example, imagine an instance specific logger used in a User class. Here, all messages logged could automatically log user information along with the messages. This might of course be overkill, but you get my point I hope :-) That said, I’ve never yet needed to use an object-level logger!