[slf4j-user] Logging in abstract classes in extending ones

Michael sgfan at gmx.net
Wed Nov 5 14:33:23 CET 2008


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:

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?

Thanks!



More information about the slf4j-user mailing list