Search code examples
pythonpython-logging

python logging module not creating/writing to file - using tutorial


I am taking below code from the logging tutorial. I see the console messages but no file is created in my working directory, and I can't find it on my computer. I have tried using the full path in the filename as well. What am I missing?

Edit: I am running on Spyder, logging version 0.5.1.2. The entire script is just this block. This morning I ran the code without any changes and an example.log file was created. I changed the filename to 'test.log' and reran, and it is no longer generating a log file. Why am I getting inconsistent creation of a log file?

Desired behavior: a log file created when I rename the filename

Shortest code: my script is verbatim below

import logging
logger = logging.getLogger(__name__)
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
logger.debug('This message should go to the log file')
logger.info('So should this')
logger.warning('And this, too')
logger.error('And non-ASCII stuff, too, like Øresund and Malmö')

Solution

  • I had the same problem some time ago using in jupyter notebooks and this fixed it.

    import logging
    logger = logging.getLogger()
    fhandler = logging.FileHandler(filename='mylog.log', mode='a')
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - % 
    (message)s')
    fhandler.setFormatter(formatter)
    logger.addHandler(fhandler)
    logger.setLevel(logging.DEBUG)
    

    I found this solution on stackoverflow. try this