Python:如何在python使用记录模块中创建和使用自定义记录器? [英] Python: How to create and use a custom logger in python use logging module?

查看:67
本文介绍了Python:如何在python使用记录模块中创建和使用自定义记录器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个自定义记录器,如下面的代码所示.但是,无论我传递给该功能的级别如何,记录器都只会打印警告消息.例如,即使我默认设置参数 level = logging.DEBUG ,我的代码也无法记录调试或信息消息.有人可以在这里指出问题.

I am trying to create a custom logger as in the code below. However, no matter what level I pass to the function, logger only prints warning messages. For example even if I set the argument level = logging.DEBUG by default my code fails to log the debug or info messages. Can someone point out the problem here.

import boto3
import logging


def get_logger(name=__name__, level=logging.DEBUG):
    # Create log handler
    logHandler = logging.StreamHandler()
    logHandler.setLevel(level)

    # Set handler format
    logFormat = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s", datefmt="%d-%b-%y")
    logHandler.setFormatter(logFormat)

    # Create logger
    logger = logging.getLogger(name)
    # Add handler to logger
    logger.addHandler(logHandler)

    # Stop propagating the log messages to root logger
    # logger.propagate = False

    return logger


def listBuckets():

    logThis = get_logger(level=logging.DEBUG)

    s3 = boto3.resource('s3')
    for bucket in s3.buckets.all():
        logThis.debug(msg='This message is from logger')
        print(bucket.name)


listBuckets()

推荐答案

您会忽略以下事实:a)每个记录器的最终祖先都是 root 记录器(默认情况下级别为WARNING) b)记录器和处理程序都具有级别.

You are missing the fact that a) every logger's ultimate ancestor is the root logger (which has level WARNING by default) and b) that both, loggers and handlers have levels.

文档状态:

创建记录器时,级别设置为NOTSET(这将导致 当记录器是根记录器时要处理的消息,或者 当记录器为非根记录器时委托给父级).

When a logger is created, the level is set to NOTSET (which causes all messages to be processed when the logger is the root logger, or delegation to the parent when the logger is a non-root logger).

因此,您将使用默认级别NOTSET创建记录器和StreamHandler.您的记录器是 root 记录器的隐式后代.您可以使用该处理程序将处理程序设置为级别DEBUG,但不能将 logger 设置为级别. 由于记录器上的级别仍为NOTSET,因此在发生日志事件时,将遍历其祖先链...

So, you create a logger and a StreamHandler with their default level NOTSET. Your logger is an implicit descendant of the root logger. You set the handler to level DEBUG, but not the logger using that handler. Since the level on your logger still is NOTSET, when a log event occurs, its chain of ancestors is traversed ...

...直到找到一个非NOTSET级别的祖先,或者 到达根.

... until either an ancestor with a level other than NOTSET is found, or the root is reached.

[...]

如果到达根目录,并且其级别为NOTSET,则所有 消息将被处理.否则,将使用根级别 作为有效级别.

If the root is reached, and it has a level of NOTSET, then all messages will be processed. Otherwise, the root’s level will be used as the effective level.

这意味着,您立即结束 root 记录器以确定有效的日志级别;根据 root 记录器的默认值,它设置为WARNING. 您可以使用parentlevel属性以及logger对象上的getEffectiveLevel方法进行检查:

Which means, you immediately end up at the root logger to determine the effective log level; it is set to WARNING as per the root logger's default. You can check this with the parent and level properties and the getEffectiveLevel method on the logger object:

logThis = get_logger()
print(logThis.parent)               # <RootLogger root (WARNING)>
print(logThis.level)                # 0 (= NOTSET)
print(logThis.getEffectiveLevel())  # 30 (= WARNING) from root logger

要让记录器自行处理所需级别以上的消息,只需通过get_logger函数中的logger.setLevel(level)在记录器上进行设置即可.

To have your logger handle the messages on and above the desired level itself, simply set it on the logger via logger.setLevel(level) in your get_logger function.

这篇关于Python:如何在python使用记录模块中创建和使用自定义记录器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆