如何在Python中禁用和重新启用控制台日志记录?

2024-05-19 09:00:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python的logging模块,我想禁用控制台日志记录一段时间,但它不起作用。

#!/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 logger.handlers 
# this will print [<logging.StreamHandler instance at ...>]
# but I may have other handlers there that I want to keep

logger.debug("bla bla")

上面的代码显示stdout上的bla bla,我不知道如何安全地禁用控制台处理程序。如何确保临时删除控制台StreamHandler而不是另一个?


Tags: 模块importbinusrlogginghandlersstdoutsys
3条回答

我使用:

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

我找到了解决办法:

logger = logging.getLogger('my-logger')
logger.propagate = False
# now if you use logger it will not log to console.

这将阻止将日志发送到包括控制台日志记录的上层日志记录程序。

您可以使用:

logging.basicConfig(level=your_level)

其中您的_级别是:

      'debug': logging.DEBUG,
      'info': logging.INFO,
      'warning': logging.WARNING,
      'error': logging.ERROR,
      'critical': logging.CRITICAL

因此,如果您将您的_级别设置为日志记录。严重,您将只收到由以下人员发送的严重消息:

logging.critical('This is a critical error message')

您的日志记录级别设置为日志记录。调试将显示所有级别的日志记录。

有关详细信息,请查看logging examples.

使用Handler.setLevel()函数以同样的方式更改每个处理程序的级别。

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)

相关问题 更多 >

    热门问题