0

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.

  • Are you sure this is a buffer-flushing issue? E.g. if you get rid of the line `enter_while_loop()` so that your program immediately exits, does the log file contain the "start" log message? You are setting the logger level to CRITICAL but logging at info level - is that what you mean to do? Are you logging any messages at the CRITICAL level? – Tom Dalton Nov 12 '14 at 12:08
  • @TomDalton Thank you for your help. I'd like to log at multiple levels. CRITICAL down through INFO. I followed your suggestion, changing CRITICAL to INFO and commenting out enter_while_loop(), but still no output. Similarly, I changed logging.INFO to logging.CRITICAL in my first code snippet, and got an empty log file when I reran it. So I'm not sure this is entirely a buffer-flushing issue; I think it may be two separate problems: logging to the same file at multiple levels (should I consider multiple log files instead?) and ensuring the log file(s) get written to atexit. – Homer Simpson Nov 12 '14 at 12:28
  • @TomDalton -- I misread the python API (D'oh!). You're right, I need INFO level, not CRITICAL; if I use CRITICAL every log event must be CRITICAL to reach the log file. Thank you again. – Homer Simpson Nov 12 '14 at 12:55
  • Also logger.addHandler(formatter) should have been logger.addHandler(handler) – Homer Simpson Nov 12 '14 at 13:12

0 Answers0