views:

516

answers:

5

I am using python logging module and I want to disable the console logging for some time but it doesn't work.


  #!/usr/bin/python
  import logging

  logger = logging.getLogger() # this gets the root logger
  # ... here I add my own handlers 
  #logger.removeHandler(sys.stdout)
  #logger.removeHandler(sys.stderr)

  print logging.handlers 
  # this will print [<logging.StreamHandler instance at ...>]
  # but I may have other handlers there that I want to keep

  logger.debug("bla bla")

The above code displays the "bla bla" on stdout and I don't know how can I safely disable the console handler. How can I bu sure that I temporary remove the console streamhandler and not another one?

+1  A: 

I don't know the logging module very well, but I'm using it in the way that I usually want to disable only debug (or info) messages. You can use Handler.setLevel() to set the logging level to CRITICAL or higher.

Also, you could replace sys.stderr and sys.stdout by a file open for writing. See http://docs.python.org/library/sys.html#sys.stdout. But I wouldn't recommend that.

Krab
This could work if logger.handlers would be contain something, currently is `[]`.
Sorin Sbarnea
+2  A: 

No need to divert stdout. Here is better way to do it:

import logging
class MyLogHandler(logging.Handler):
    def emit(self, record):
        pass

logging.getLogger().addHandler(MyLogHandler())

An even simpler way is:

logging.getLogger().setLevel(100)
Ehsan Foroughi
+2  A: 

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)
Vadikus
+1  A: 

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 logging from being send to the upper logger that includes the console logging.

Sorin Sbarnea
+1  A: 

I use:

logger = logging.getLogger()
logger.disabled = True
... whatever you want ...
logger.disabled = False
infinito