Reputation: 91
To get C.run() to use its own class logger, should I add a public/protected method getLogger() in B?
public abstract class A extends Thread {
@Override
public abstract void run();
}
public class B extends A {
private static final Logger logger = Logger.getLogger(B.class.getName());
@Override
protected void run() {
// do something
logger.info("B");
}
}
public class C extends B {
}
Upvotes: 9
Views: 14618
Reputation: 7951
You may use this in base class:
protected Logger logger = Logger.getLogger(this.getClass().getName());
this.getClass()
will initialize the logger with subclass name.
Upvotes: 6
Reputation: 12633
Well the Loggers are ideally set at Class level. So if C needs it own Logger then declare its own Logger in C e.g.
private static final Logger logger = Logger.getLogger(C.class.getName());
This way when C runs some code it logs to its own Logger and when B runs it logs to its own Logger. You'll be able to clearly see which Class logs what this way.
If this isn't what you're after please expand the question with what you're trying to achieve and why.
I'm not convinced if the following code is a good idea (I always want the Class which is physically running the code to be the Logger) but it should work:
public abstract class A extends Thread {
@Override
public abstract void run();
protected abstract Logger getLogger();
}
public class B extends A {
private static final Logger logger = Logger.getLogger(B.class.getName());
@Override
public void run() {
getLogger().info("B");
}
@Override
protected Logger getLogger() {return logger;);
}
public class C extends B {
private static final Logger logger = Logger.getLogger(C.class.getName());
@Override
protected Logger getLogger() {return logger;);
}
Upvotes: 14