I'm trying to use the logging module in Python so that, when I run my program, I end up with a log file, debug.log, containing:
- Every log message (logging.DEBUG, logging.WARNING etc.)
- Every time my code prints something to STDOUT
When I run the program, I only want the debug messages to appear in the log file, not to be printed on the terminal.
Based on this answer, here's my example code, test.py:
import logging import sys root = logging.getLogger() root.setLevel(logging.DEBUG) fh = logging.FileHandler('debug.log') fh.setLevel(logging.DEBUG) sh = logging.StreamHandler(sys.stdout) sh.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') sh.setFormatter(formatter) fh.setFormatter(formatter) root.addHandler(sh) root.addHandler(fh) x = 4 y = 5 logging.debug("X: %s", x) logging.debug("Y: %s", y) print("x is", x) print("y is", y) print("x * y =", x*y) print("x^y =", x**y) And here's what I would want to be the contents of debug.log:
2021-02-01 12:10:48,263 - root - DEBUG - X: 4 2021-02-01 12:10:48,264 - root - DEBUG - Y: 5 x is 4 y is 5 x * y = 20 x^y = 1024 Instead, the contents of debug.log is just the first two lines:
2021-02-01 12:10:48,263 - root - DEBUG - X: 4 2021-02-01 12:10:48,264 - root - DEBUG - Y: 5 When I run test.py, I get this output:
2021-02-01 12:17:04,201 - root - DEBUG - X: 4 2021-02-01 12:17:04,201 - root - DEBUG - Y: 5 x is 4 y is 5 x * y = 20 x^y = 1024 So I've actually got the opposite results to what I want: the log file excludes STDOUT prints where I want them included, and the program output includes the debug messages where I want them excluded.
How can I fix this, so that running test.py only outputs the lines in print statements, and the resulting debug.log file contains both the DEBUG logs and the print lines?
print()and log allstdoutoutput to file, maybe this can help. However, instead ofprint(), I would just use alogginglogger, with a special stream handler that prints tostdoutwithout any additional formatting.