Over a million developers have joined DZone.

Setting Logger Levels in Tests, Using an ITD

DZone's Guide to

Setting Logger Levels in Tests, Using an ITD

· Java Zone
Free Resource

The single app analytics solutions to take your web and mobile apps to the next level.  Try today!  Brought to you in partnership with CA Technologies

Long time ago, I wrote a class called LoggerLevelStack. The idea is simple: make it possible to set a logger level programmatically from inside a test, then when the test is over, have the prior level restored automatically. The problem with it in use was that you had to make an instance, then remember to call revertAll() in the teardown(). The ITD removes these hassles: it injects the instance into the test class, and injects an @After method that reverts the levels.

package com.ontometrics.util;

import org.junit.After;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.Level;

import com.ontometrics.util.test.LoggerLevelStack;

public aspect LoggerLevelStackInjector {

private static Logger log = LoggerFactory.getLogger(LoggerLevelStackInjector.class);

private LoggerLevelStack Tester.loggerLevelStack = new LoggerLevelStack();

public void Tester.setLevel(Class logClass, Level level){
this.loggerLevelStack.setLevel(logClass, level);

public void Tester.setLevel(String packagePattern, Level level){
this.loggerLevelStack.setLevel(packagePattern, level);

public void Tester.testLoggerTearDown(){
log.info("teardown called");

declare parents: (com.ontometrics..*Test) implements Tester;


Since we are dealing with tests here, the joinpoint expression is simple: any class that ends with the name Test.

Usage is simple: test classes show that they are being intercepted by the aspect, and it's possible to just call this.setLevel(..), like so:

public void setup() throws SecurityException, NoSuchFieldException {

this.setLevel(Space.class, Level.DEBUG);
this.setLevel(CompoundCase.class, Level.DEBUG);


Aspects are good.

From http://www.jroller.com/robwilliams


CA App Experience Analytics, a whole new level of visibility. Learn more. Brought to you in partnership with CA Technologies.


Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}