Logging in test mode

Answered

I have a problem with generating log files while using the test runner and I can't wrap my head around it. Basically, if execute my test function with pytest, no log file is created. If I run the function as a script call (so normal run module, without "pytest for ...") the logging file is generated as expected.

As you can see in the example below it is not a complicated logger. I assume the problem has something to do with the pytest configuration but I just don't understand what is going wrong here.

 

import os
import datetime
import logging


def test_logging():
LOG_PATH = os.path.join(os.getcwd(), 'log')

if not os.path.exists(LOG_PATH):
os.mkdir(LOG_PATH)
now = datetime.datetime.now()
filename = os.path.join(LOG_PATH, 'log-'+now.strftime("%Y-%m-%d %H-%M")+'.log')

logging.basicConfig(filename=filename, level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%Y/%m/%d %H:%M:%S')
logger = logging.getLogger()

logger.debug("Test")

test_logging()
1 comment
Comment actions Permalink

I found the solution. Adding force=True to the arguments it works (doc: any existing handlers attached to the root logger are removed and closed, before carrying out the configuration as specified by the other arguments).

    logging.basicConfig(filename=filename, level=logging.DEBUG,
                        format='%(asctime)s - %(levelname)s - %(message)s',
                        datefmt='%Y/%m/%d %H:%M:%S', force=True)

I don't understand why this happens in a clean file where no other loggers should be around. Maybe Pycharm is using logging in the background as well? Anyway, I'm happy I found the error. Hope this helps others as well some time.

0

Please sign in to leave a comment.