Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 680
Himanshu Shekhar Avatar asked Oct 16 '25 04:10

Himanshu Shekhar


1 Answers

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).

like image 142
Jonas Byström Avatar answered Oct 17 '25 17:10

Jonas Byström



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!