Python flushing log buffer at exit

1.6k views Asked by At

I wrote a python script which executes a while loop and requires a keyboard interrupt or system shutdown to terminate.

I would like my log file to save the log output; currently the log file gets created, but nothing gets written to it.

The following creates an output file with the contents I expect:

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# create a file handler

handler = logging.FileHandler('hello.log')
# handler.setLevel(logging.INFO)

# create a logging format

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

# add the handlers to the logger

logger.addHandler(handler)

logger.info('Mmmm...donuts')

But when I integrate it into my code, the log file lacks any contents:

from logging import log, FileHandler, getLogger, Formatter, CRITICAL    

logger = getLogger(__name__)
logger.setLevel(CRITICAL)
handler = FileHandler("test.log")
formatter = Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(formatter)

logger.info("start")
enter_while_loop()

I believe I should handle this using atexit, but how?

Thank you for your time and consideration.

0

There are 0 answers