如何在Python中禁用标准错误流的日志记录?这行不通:

import logging

logger = logging.getLogger()
logger.removeHandler(sys.stderr)
logger.warning('foobar')  # emits 'foobar' on sys.stderr

当前回答

我使用:

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

其他回答

这不是100%的解决方案,但这里没有一个答案解决了我的问题。我有自定义的日志模块,根据严重程度输出彩色文本。我需要禁用stdout输出,因为它复制了我的日志。我对将关键日志输出到控制台很满意,因为我几乎不使用它。我没有测试它是否为stderr,因为我没有在日志中使用它,但它应该与stdout的工作方式相同。它将CRITICAL设置为仅针对stdout的最小严重程度(如果请求则为stderr)。

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

# disable terminal output - it is handled by this module
stdout_handler = logging.StreamHandler(sys.stdout)

# set terminal output to critical only - won't output lower levels
stdout_handler.setLevel(logging.CRITICAL)

# add adjusted stream handler
logger.addHandler(stdout_handler)

使用装饰器找到了一个优雅的解决方案,它解决了以下问题:如果您正在编写一个具有多个函数的模块,每个函数都有几个调试消息,并且您希望禁用除当前关注的函数之外的所有函数的登录,该怎么办?

你可以使用装饰器:

import logging, sys
logger = logging.getLogger()
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)


def disable_debug_messages(func):
    def wrapper(*args, **kwargs):
        prev_state = logger.disabled
        logger.disabled = True
        result = func(*args, **kwargs)
        logger.disabled = prev_state
        return result
    return wrapper

然后,你可以这样做:

@disable_debug_messages
def function_already_debugged():
    ...
    logger.debug("This message won't be showed because of the decorator")
    ...

def function_being_focused():
    ...
    logger.debug("This message will be showed")
    ...

即使从function_being_focused内部调用function_already_debug,也不会显示来自function_already_debug的调试消息。 这确保您将只看到您所关注的函数的调试消息。

希望能有所帮助!

你可以使用:

logging.basicConfig(level=your_level)

your_level是其中之一:

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

如果你设置your_level为logging。CRITICAL,你只会得到由以下发送的关键消息:

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

将your_level设置为日志。DEBUG将显示所有级别的日志记录。

要了解更多详细信息,请查看日志示例。

以同样的方式更改每个Handler的级别使用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)

我不是很了解日志模块,但是我使用它的方式是我通常只希望禁用调试(或信息)消息。您可以使用Handler.setLevel()将日志级别设置为CRITICAL或更高。

此外,您还可以替换sys。Stderr和sys。打开用于写入的文件的标准输出。见http://docs.python.org/library/sys.html # sys.stdout。但我不建议这样做。

这里有一些非常好的答案,但显然没有考虑太多最简单的答案(只从无穷开始)。

root_logger = logging.getLogger()
root_logger.disabled = True

这将禁用根日志记录器,从而禁用所有其他日志记录器。 我还没有真正测试过,但它应该是最快的。

从python 2.7的日志代码中,我看到了这一点

def handle(self, record):
    """
    Call the handlers for the specified record.

    This method is used for unpickled records received from a socket, as
    well as those created locally. Logger-level filtering is applied.
    """
    if (not self.disabled) and self.filter(record):
        self.callHandlers(record)

这意味着当它被禁用时,不会调用任何处理程序,并且它应该比过滤到一个非常高的值或设置一个no-op处理程序更有效。