Skip to content
Advertisement

redirecting screen output from python logging to a file

How can I redirect the output of python logging statements to a file at run time using redirection?

I am using python 3.7 in Debian. When I redirect the output from a python script containing a print statement to a file, I get the expected result – a file containing the output.

If I use logging.debug to create the screen output and redirect this to a file, I get the output displayed on the screen and a zero size file.

python_test.py

JavaScript
JavaScript

python_logging_test.py

JavaScript
JavaScript

Advertisement

Answer

logging does not use the stdout stream, it uses the stderr output stream.

Redirect the stderr stream:

method 1

JavaScript
JavaScript

method 2

Use stdbuf:

JavaScript
JavaScript

from stdbuf –help -e, –error=MODE adjust standard error stream buffering If MODE is ‘L’ the corresponding stream will be line buffered.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement