Question about logging and inheritence

K

krzyber

Hi,
I've started to use log4j in my test app and have come upon this
problem. Should classes which extend another class use it's logger or
should they have their own logger?

public class Person {
private static Logger log = Logger.getLogger(Person.class);
/*...*/
}

public class Worker extends Person {
private static Logger log = Logger.getLogger(Worker.class);
/*...*/
}

or should it be like this

public class Person {
protected static Logger log = Logger.getLogger(Person.class);
/*...*/
}

public class Worker extends Person {
/*...*/ // the logger form Person can be used
}

Thanks in advance :)
 
J

Josh Martin

You're not going to save anything since the Logger is a singleton
instance (i.e. all classes share the same logger) - that' why there's
a getLogger() method versus a new Logger().

All you're doing when you pass in the class name is telling log4j
which logger you want to use for logging. If you only have one logger
for the application (e.g. log4j.logger.com.objects), then both Person
and Worker would respond the same (note that I'm assuming both are in
the objects package).

You would want to have a seperate declaration in each if you wanted to
control the logging differently in each:

log4j.logger.com.objects.Person=INFO, [appender]
log4j.logger.com.objects.Worker=WARN, [appender]

This would log all messages INFO+ for Person, but only WARN+ for
Worker. I usually only have multiple loggers if I'm using third-party
packages that I want to log only at ERROR+, but have my own code log
DEBUG+ (during development).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,008
Latest member
HaroldDark

Latest Threads

Top