logging-log4j-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Elias Ross <er...@m-qube.com>
Subject Re: Declaring a Logger in an Abstract Class
Date Thu, 15 Apr 2004 17:16:46 GMT
On Thu, 2004-04-15 at 05:27, Robert Pepersack wrote:
> Hi all.
> 
> I have an abstract class that has many subclasses.  There are several options:
> 
> 1.  Declare it in the abstract class using the String name of the abstract 
> class.  For example:
> 
>      protected static final Logger logger = 
> Logger.getLogger("org.happy.Superclass"); // Logger does not have name of 
> concrete class.

It's confusing to get a log message from "org.happy.Superclass", when
you're actually logging from another class.  For example, if you see:

122131232 [ERROR] (Superclass) Uh oh!

You'll want to know exactly which class is outputting that message.

> 2.  Declare it in the abstract class using the Class of the abstract 
> class.  For example:
> 
>      protected final Logger logger = 
> Logger.getLogger(getClass().getName()); // Not declared static as book 
> suggests.

It's not a bad idea.  However, then messages that occur in the
super-class get logged in the sub-class category.

> 
> 3.  Declare it in the subclasses using the String name of each subclass.
> 
>      protected static final Logger logger = 
> Logger.getLogger("org.happy.ConcreteClass");  // Logger for each 
> subclass.  Lots of loggers.

Using strings is error prone, especially if you cut/paste lots of code. 
Also, don't make it protected if you create one per class.

> 
> 4.  Declare it in the subclasses using the Class of each subclass.
> 
>      protected final Logger logger = 
> Logger.getLogger(getClass().getName()); // Not declared static as book 
> suggests.

This is what I would do.  Make the logger private in this case.

private static final Logger logger = 
   Logger.getLogger(WhateverClass.class);

I don't think they use much more than a handful of bytes.

Anyway, this is a user question... not really dev.  However, I think
it's up to the Dev people to agree on things they tell users.  What I
suggest is consistent with Sun, at least:

http://java.sun.com/j2se/1.4.2/docs/guide/util/logging/overview.html

If you have lots of subclasses that log the same things, I would look at
the overall design.  Remember the mantra:  "Inheritance breaks
encapsulation."


---------------------------------------------------------------------
To unsubscribe, e-mail: log4j-dev-unsubscribe@logging.apache.org
For additional commands, e-mail: log4j-dev-help@logging.apache.org


Mime
View raw message