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

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



Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}