0

I have a python script that prints debug and error outputs to stdout with print(). Now I want to retroactively add writing said output to a logfile, so I found logging - Redirect Python 'print' output to Logger:

import logging

# this is a hack to log print statements to a file
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
logger = logging.getLogger()
logger.addHandler(logging.FileHandler('logfile.log', 'a'))
logger.propagate = False
print = logger.info

# testing it:
print("test")
logger.info("another test")

The output of the snippet above in logfile.log is:

test
another test

but the output in stdout (python interactive console) is:

>>> print("test")
2022-05-30 02:13:31,168 test
>>> logger.info("another test")
2022-05-30 02:13:38,081 another test

Why isn't the logger writing the formatted date in logfile.log but in stdout?

martineau
  • 119,623
  • 25
  • 170
  • 301
bj4rne
  • 1
  • 1
  • 2

1 Answers1

0

After trying around for a bit, I found

import logging

# this is a hack to log print statements to a file
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s",
handlers=[
        logging.StreamHandler(),
        logging.FileHandler("logfile.log", "a"),
    ],)
logger = logging.getLogger()
logger.propagate = False
print = logger.info

# testing it:
print("test")
logger.info("another test")

to work exactly as i want. The output in logfile.log is now:

2022-05-30 19:44:02,354 test
2022-05-30 19:44:02,355 another test
bj4rne
  • 1
  • 1
  • 2