Platinum Partner
java,testing

Setting Logger Levels in Tests, Using an ITD

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);
}

@After
public void Tester.testLoggerTearDown(){
log.info("teardown called");
this.loggerLevelStack.revertAll();
}

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:

@Before
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

 

{{ tag }}, {{tag}},

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

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}