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
?