0

I'm using a logging object to display the process of my Python script. Things were working fine until I specified a log file.

Working Code

from datetime import timedelta
import logging
import time

def main():
    start_time = time.monotonic()

    config = get_args()

    # Logger configuration.
    msg_format = '[%(asctime)s - %(levelname)s - %(filename)s: %(lineno)d (%(funcName)s)] %(message)s'
    logging.basicConfig(format=msg_format, level=logging.INFO)
    logger = logging.getLogger()

    logger.info(msg='Starting process...')

    # End of process.
    end_time = time.monotonic()
    process_time = str(timedelta(seconds=(end_time - start_time))).split('.')[0] # Get rid of trailing microseconds.
    logger.info(msg=('End. Entire process took approximately %s' % process_time))


if __name__ == '__main__':
    main()

Not Working Code

from datetime import datetime, timedelta
import logging
import os
import time


def main():
    start_time = time.monotonic()

    config = get_args()

    # Logger configuration.
    timestamp = datetime.now().strftime(format='%Y%m%d-%H%M')
    log_filename = '_'.join(['log', timestamp])
    log_file_path = os.path.join(config.log_dir, log_filename)
    msg_format = '[%(asctime)s - %(levelname)s - %(filename)s: %(lineno)d (%(funcName)s)] %(message)s'
    logging.basicConfig(filename=log_file_path, format=msg_format, level=logging.INFO)
    logger = logging.getLogger()

    logger.info(msg='Starting process...')

    # End of process.
    end_time = time.monotonic()
    process_time = str(timedelta(seconds=(end_time - start_time))).split('.')[0] # Get rid of trailing microseconds.
    logger.info(msg=('End. Entire process took approximately %s' % process_time))


if __name__ == '__main__':
    main()

Would anyone know what might be the problem? I'm suspecting that specifying the log filename in the logging.basicConfig may have messed up the handlers or something, but I'm not 100% certain. Thanks!

Sean
  • 2,890
  • 8
  • 36
  • 78

1 Answers1

0

The answer was relatively obvious after reading the documentation a bit more carefully. I wasn't aware that I hadn't included any handlers in my configuration. To fix the issue, all I had to do was change:

logging.basicConfig(filename=log_file_path, format=msg_format, level=logging.INFO)

to this:

logging.basicConfig(format=msg_format, level=logging.INFO, \
                    handlers=[logging.FileHandler(filename=log_file_path), logging.StreamHandler()])

Hope this helps anyone else running into the same mistake.

This answer helped me: logger configuration to log to file and print ot stdout

Sean
  • 2,890
  • 8
  • 36
  • 78