How to redirect abseil logging messages to stout instead of stderr?

2.6k views Asked by At

I am using python 3.7.6. and abseil module for logging messages with absl-py 0.9.0. I am using this piece of code for my tests.

from absl import logging
from absl import app

def main(argv):

    #logging.set_stderrthreshold(logging.ERROR)
    #logging._warn_preinit_stderr = False
    logging.set_verbosity(logging.DEBUG)

    print(' 0 -----')
    logging.debug(' 1 logging-debug-test')
    logging.info(' 2 logging-info-test')
    logging.warning(' 3 logging-warning-test')
    logging.error('4 logging-error-test')
    print(' 5 -----')

if __name__ == '__main__':
    app.run(main)

When testing it in a Jupyter notebook, it is clear from the color code of the background that abseil messages are in the stderr stream.

enter image description here

Same things when executing the python code in a shell: enter image description here enter image description here
I tried few things with different values like:

logging.set_stderrthreshold(logging.DEBUG)
logging._warn_preinit_stderr = True

but I still see 100% the same output.

  • How can I redirect output abseil logging messages to stdout instead of stderr ?
  • Is it expected to have the logging output messages redirect to stderr and not stdout? I am probably missing something with the logging logic and I want to better understand it.
2

There are 2 answers

1
Dr. Fabien Tarrade On BEST ANSWER

I was told that this is the standard behavior and what Python's standard logging module does. In my case adding the following line redirect the logging messages to stdout:

logging.get_absl_handler().python_handler.stream = sys.stdout

Now in my Jupyter notebook it looks like that: enter image description here

0
Zsolt Safrany On

This did NOT work for me for some reason:

from absl import logging
import sys

logging.get_absl_handler().python_handler.stream = sys.stdout

But this did:

import logging
import sys

logging.basicConfig(stream=sys.stdout)