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
x
2
1
print('hello')
2
JavaScript
1
4
1
python python_test.py > test.txt
2
more test.txt
3
hello
4
python_logging_test.py
JavaScript
1
6
1
import logging
2
3
logging.basicConfig(level=logging.DEBUG, format='%(message)s')
4
5
logging.debug('from logger')
6
JavaScript
1
6
1
python python_logging_test.py > test2.txt
2
from logger
3
ls -al test2.txt
4
-rw-r--r-- 1 bart bart 0 Mar 31 20:00 test2.txt
5
6
Advertisement
Answer
logging does not use the stdout stream, it uses the stderr output stream.
Redirect the stderr stream:
method 1
JavaScript
1
2
1
python python_logging_test.py 2> test2.txt
2
JavaScript
1
3
1
more test2.txt
2
from logging
3
method 2
Use stdbuf:
JavaScript
1
2
1
stdbuf -e L python python_logging_test.py > test2.txt
2
JavaScript
1
3
1
more test2.txt
2
from logger
3
from stdbuf –help -e, –error=MODE adjust standard error stream buffering If MODE is ‘L’ the corresponding stream will be line buffered.