[slf4j-user] Logging in abstract classes in extending ones
Joern Huxhorn
jhuxhorn at googlemail.com
Wed Nov 5 21:32:29 CET 2008
Michael wrote:
> Hi folks,
>
> I have came up with a logging heirachy problem recently.
>
> The situation looks basically like this:
>
> public abstract class A {
>
> logger = .... A.class;
>
> public void out() {
> logger.info("this is out");
> }
>
> abstract protected void moreOut();
>
> }
>
> public class B extends A {
>
> logger = ... B.class;
>
> @Override
> public void moreOut() {
> logger.info("this is moreOut");
> }
>
> public static void main(String[] args) {
>
> B name = new B();
> name.out();
> name.moreUut();
>
> }
> }
>
> The output is of course:
> 0 [main] INFO A - this is out
> 0 [main] INFO B - this is moreOut
>
> Well, since I use the abstract class as a skeleton, it should be
> completely transparent and not appear in log statements.
> There seems not to be a reasonable solution except this:
>
>
I'm aware of this "problem" but I consider it a feature.
Since the code executing to output "this is out" is located in class A I
would expect it to use Logger A. One advantage of that situation is that
you can selectively disable output of class A while you could leave
class B output enabled.
I like this. This is, sometimes, exactly what I want.
> public abstract class A {
>
> public void out() {
> getLogger().info("this is out");
> }
>
> abstract protected void moreOut();
> abstract protected Logger getLogger();
>
> }
>
> public class B extends A {
>
> logger = ... B.class;
>
> @Override
> public void moreOut() {
> logger.info("this is moreOut");
> }
>
> @Override
> public Logger getLogger() {
> return LoggerFactory.getLogger(B.class);
> }
>
> public static void main(String[] args) {
>
> B name = new B();
> name.out();
> name.moreUut();
>
> }
> }
>
> and the output is as desired:
> 0 [main] INFO B - this is out
> 0 [main] INFO B - this is moreOut
>
>
> I'd like to know your opinion on that. Is my solution the best way to go?
>
>
If you absolutely want the above logging behavior then, yes, I think
your solution is the way to go.
I would just suggest to declare the class and the logger instance final
, if possible, to enable further JIT optimization but I'm not sure how
big the performance improvement would be in real life.
> Thanks!
>
Your welcome ;)
Joern.
More information about the slf4j-user
mailing list