Himanshu Shekhar
Himanshu Shekhar

Reputation: 368

How to redirect python logging output to file instead of stdout?

I want to redirect all the output, even from the external modules which are imported to a file.

sys.stdout = open('logfile', 'a')

doesn't do the job for the logging done by external files is echoed on stdout.

I've tinkered with the source code of external modules, and they are deeply knitted with python's "logging" module and rely on it for the output.

Also, I don't want to use stream redirection using > operator.

Upvotes: 4

Views: 5349

Answers (2)

Jonas Byström
Jonas Byström

Reputation: 26129

import sys

sys.stdout = sys.stderr = open('logfile', 'a')

print('this should be working from anywhere')
import logging
logging.warn('this too')

The reasson you saw external modules print to console was probably that they were using stderr (which is the default output handler for the logging module).

Upvotes: 3

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181270

Try this:

sysstdout = sys.stdout
log_file = open("your_log_file.txt","w")
sys.stdout = log_file
print("this will be written to message.log")
sys.stdout = sysstdout
log_file.close()

Or, do the right thing and use Python's logging module properly.

Upvotes: 0

Related Questions