Tech and travel

Python logging output file change

2009-08-12

I run unit tests in Python using the standard unittest module. The output should be logged to a file. For this Python has a standard logging library, which is somewhat similar to the logging library for Java.

The problem is that there is no easy way to direct the logging to a new file for every test case. Here’s how I got around it. Firstly the setup method of my testcase object contains the following :

def setUp(self):
    self.logger = logging.getLogger('MyLogger')
    self.logger.setLevel(logging.DEBUG)
    self.log_handler = None
    self.formatter = logging.Formatter("%(asctime)s - %(name)s - %(message)s")

A logger is created and the default level is set. Then variables are set for the log_handler and formatter. These are used in the settestcasename method found below. This gets called in every test method of the testcase class. First it removes the old handler. The testcase name given as parameter is then used to create a new FileHandler. This will create and log to a new file when something is logged. This new handler is then added to the logger.

def settestcasename(self,giventestcasename,description=""):
    now=datetime.datetime.today().strftime('%Y%m%d_%H%M%S')
    if self.log_handler is not None:
        self.log_handler.close()
        self.logger.removeHandler(self.log_handler)
    filename='%s_%s.log' % (giventestcasename.replace(' ','_'), now)
    self.log_handler=logging.FileHandler(filename,'w')
    self.log_handler.setFormatter(self.formatter)
    self.logger.addHandler(self.log_handler)

The fact that the settestcasename has to be called is not ideal. but it works me. Something evil like this could be used to get the name of the current method, which can then be used as a filename. A decorator can possibly be created as well.

Copyright (c) 2024 Michel Hollands