25 March 2013

Unit test your logging

I have a few log statements which are really important for me in production. Without them, I would be screwed when tracking whats actually going on. So I decided that this important code shouldn't be left out in the cold.

Here is a trivial example. Lets say the "Replacing address" log statement in the following code is really important when stuff hits the fan.



void setAddress(Address adr) {
  log.info "Replacing address ${this.address} with ${adr} on ${this}"
  this.address = adr
  log.debug "Updated{person} with new address"
}



setup:
def log = []
def collectLog = {String message -> log << message}
def finn = new Person(name:'finn', new Address(streetname:'homeless'))
finn.metaClass.log = [debug:collectLog, info:collectLog, error: collectLog]
when:
finn.address = new Address(streetname:'Slottsplassen 1')
then:
assert log.find {String msg -> msg.contains "Replacing address homeless with Slottsplassen 1 on Finn"}


The code turned out simpler than I feared when I initially decided I need to test my logging. Joy!

No comments:

Post a Comment