“()”在python日志配置中做什么

2024-10-03 21:34:57 发布

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

我在uvicorn's源代码中看到了python dict日志配置

在这方面,他们将格式化程序定义为

{
    "default": {
        "()": "uvicorn.logging.DefaultFormatter",
        "fmt": "%(levelprefix)s %(asctime)s %(message)s",
        "datefmt": "%Y-%m-%d %H:%M:%S",

    },
    "access": {
        "()": "uvicorn.logging.AccessFormatter",
        "fmt": '%(levelprefix)s %(asctime)s :: %(client_addr)s - "%(request_line)s" %(status_code)s',
        "use_colors": True
    },
}

另外,我们可以看到,他们将一个空的记录器(不确定该怎么称呼它)定义为

"": {"handlers": ["default"], "level": "INFO"},
^^^^ - see, Empty key

这是我的问题

  1. 在python logger的格式化程序部分中,"()"做什么
  2. 在python logger的部分中,""做什么

Tags: defaultmessageaccess源代码loggingloggerdict程序定义
1条回答
网友
1楼 · 发布于 2024-10-03 21:34:57

此字典用于配置使用^{}的日志记录

"()"键表示需要自定义实例化[source]:

In all cases below where a ‘configuring dict’ is mentioned, it will be checked for the special '()' key to see if a custom instantiation is required. If so, the mechanism described in User-defined objects below is used to create an instance; otherwise, the context is used to determine what to instantiate.

对于OP问题中的格式化程序配置,"()"表示应该使用这些类来实例化Formatter

我在字典的loggers部分没有看到空字符串,但下面是related docs

loggers - the corresponding value will be a dict in which each key is a logger name and each value is a dict describing how to configure the corresponding Logger instance.

The configuring dict is searched for the following keys:

  • level (optional). The level of the logger.
  • propagate (optional). The propagation setting of the logger.
  • filters (optional). A list of ids of the filters for this logger.
  • handlers (optional). A list of ids of the handlers for this logger.

The specified loggers will be configured according to the level, propagation, filters and handlers specified.

因此loggers字典中的""键将实例化名为""的记录器,如logging.getLogger("")


出于各种原因,可以使用自定义日志格式化程序uvicorn使用自定义格式化程序to log different levels in different colors。Python日志记录手册在记录消息时使用了example of using a custom formatter to use UTC times而不是本地时间

import logging
import time

class UTCFormatter(logging.Formatter):
    converter = time.gmtime

LOGGING = {
    ...
    'formatters': {
        'utc': {
            '()': UTCFormatter,
            'format': '%(asctime)s %(message)s',
        },
        'local': {
            'format': '%(asctime)s %(message)s',
        }
    },
    ...
}

if __name__ == '__main__':
    logging.config.dictConfig(LOGGING)
    logging.warning('The local time is %s', time.asctime())

这是输出。注意,在第一行中,使用UTC时间而不是本地时间,因为使用了UTCFormatter

2015-10-17 12:53:29,501 The local time is Sat Oct 17 13:53:29 2015
2015-10-17 13:53:29,501 The local time is Sat Oct 17 13:53:29 2015

相关问题 更多 >