LuckyCoder3607
LuckyCoder3607

Reputation: 65

How is the logging module still outputting even when stdout and stderr are set to None?

This is a simple proof-of-concept script

import logging
import sys

logging.basicConfig(level=logging.DEBUG)

logging.info('This is a test for info')
logging.error('This is a test for error')
print('This is a test for print')

sys.__stdout__ = None
sys.stdout = None

sys.__stderr__ = None
sys.stderr = None

logging.info('This is a test for info after setting stdout to None')
logging.error('This is a test for error after setting stderr to None')
print('This is a test for print after setting stdout to None')

And the output is:

INFO:root:This is a test for info
ERROR:root:This is a test for error
This is a test for print
INFO:root:This is a test for info after setting stdout to None
ERROR:root:This is a test for error after setting stderr to None

As you can see the print statement is not outputting the string after setting stdout/stderr to None.

But how is the logging module still outputting the strings into the terminal, is there a reason behind this?

Upvotes: 0

Views: 51

Answers (1)

pippo1980
pippo1980

Reputation: 3061

I don't know; nevertheless try adding:

logging.basicConfig(stream=None , force=True)

after: sys.stderr = None

Then try again with:

logging.basicConfig(stream=None)

Then try the output of:

import logging
import sys

logging.basicConfig(level=logging.DEBUG)

logging.info('This is a test for info')
logging.error('This is a test for error')
print('This is a test for print')

sys.__stdout__ = None
sys.stdout = None

sys.__stderr__ = None
sys.stderr = None

logging.basicConfig(stream = sys.stdout, level=logging.DEBUG , force= True)

logging.info('This is a test for info after setting stdout to None')
logging.error('This is a test for error after setting stderr to None')
print('This is a test for print after setting stdout to None')

And again try to change:

logging.basicConfig(stream = sys.stdout, level=logging.DEBUG , force= True)

to:

logging.basicConfig(stream = sys.stdout, level=logging.DEBUG , force= False)

Upvotes: 0

Related Questions