How to disable logging on the standard error stream?
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Luau
--
Chapters
00:00 How To Disable Logging On The Standard Error Stream?
00:17 Answer 1 Score 85
00:59 Accepted Answer Score 246
01:14 Answer 3 Score 158
01:24 Answer 4 Score 50
02:07 Thank you
--
Full question
https://stackoverflow.com/questions/2266...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #logging #console #stdout
#avk47
ACCEPTED ANSWER
Score 246
I found a solution for this:
logger = logging.getLogger('my-logger')
logger.propagate = False
# now if you use logger it will not log to console.
This will prevent logging from being sent to the upper logger that includes the console logging.
ANSWER 2
Score 158
I use:
logger = logging.getLogger()
logger.disabled = True
... whatever you want ...
logger.disabled = False
ANSWER 3
Score 85
You can use:
logging.basicConfig(level=your_level)
where your_level is one of those:
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL
So, if you set your_level to logging.CRITICAL, you will get only critical messages sent by:
logging.critical('This is a critical error message')
Setting your_level to logging.DEBUG will show all levels of logging.
For more details, please take a look at logging examples.
In the same manner to change level for each Handler use Handler.setLevel() function.
import logging
import logging.handlers
LOG_FILENAME = '/tmp/logging_rotatingfile_example.out'
# Set up a specific logger with our desired output level
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
# Add the log message handler to the logger
handler = logging.handlers.RotatingFileHandler(
          LOG_FILENAME, maxBytes=20, backupCount=5)
handler.setLevel(logging.CRITICAL)
my_logger.addHandler(handler)
ANSWER 4
Score 50
(long dead question, but for future searchers)
Closer to the original poster's code/intent, this works for me under python 2.6
#!/usr/bin/python
import logging
logger = logging.getLogger() # this gets the root logger
lhStdout = logger.handlers[0]  # stdout is the only handler initially
# ... here I add my own handlers 
f = open("/tmp/debug","w")          # example handler
lh = logging.StreamHandler(f)
logger.addHandler(lh)
logger.removeHandler(lhStdout)
logger.debug("bla bla")
The gotcha I had to work out was to remove the stdout handler after adding a new one; the logger code appears to automatically re-add the stdout if no handlers are present.
IndexOutOfBound Fix: If you get a IndexOutOfBound Error while instantiating lhStdout, move the instantiation to after adding your file handler i.e.
...
logger.addHandler(lh)
lhStdout = logger.handlers[0]
logger.removeHandler(lhStdout)