简体   繁体   English

Python的logging.config.dictConfig()是否应用记录器的配置设置?

[英]Does Python's logging.config.dictConfig() apply the logger's configuration settings?

I've been trying to implement a basic logger that writes to a file in Python 3.5, loading the settings from a JSON config file. 我一直在尝试实现一个基本的记录器,该记录器可以在Python 3.5中写入文件,并从JSON配置文件中加载设置。 I'll show my code first; 我将首先显示我的代码;

log_config.json

{
    "version": 1,
    "disable_existing_loggers": "false",
    "logging": {
        "formatters": {
            "basic": {
                "class": "logging.Formatter",
                "style": "%",
                "datefmt": "%I:%M:%S",
                "format": "[%(asctime)] %(levelname:<8s): (name:<4s): %(message)"
            }
        },

        "handlers": {
            "file": {
                "class": "logging.handlers.FileHandler",
                "level": "DEBUG",
                "formatter": "basic",
                "filename": "test.log",
                "mode": "a",
                "encoding": "utf-8"
            }
        },

        "loggers": { },

        "root": {
            "handlers": ["file"],
            "level": "DEBUG"
        }
    }
}

And logger.py 还有logger.py

import json
import logging
import logging.config

logging.basicConfig()
with open("log_config.json", "r") as fd:
    logging.config.dictConfig(json.load(fd))

logger = logging.getLogger()  # Returns the "root" logger
print(logger.getEffectiveLevel())  # Check what level of messages will be shown

logger.debug("Test debug message")
logger.info("Test info message")
logger.warn("Test warning message")
logger.error("Test error message")
logger.critical("Test critical message")

When run with python3 logger.py produces the output (in the terminal); 当使用python3 logger.py运行时, python3 logger.py产生输出(在终端中);

30
WARNING:root:Test warning message
ERROR:root:Test error message
CRITICAL:root:Test critical message

First; 第一; Looking at Python's logging levels . 查看Python的日志记录级别 30 is the default logging level of 'WARNING'. 30是默认的日志记录级别“警告”。 This contradicts the setting for both of the level properties I set in the handler and the root logger. 这与我在处理程序和根记录器中设置的两个level属性的设置相矛盾。 It seems the JSON is incorrect or I have missed a function call to apply it. 似乎JSON不正确,或者我错过了应用它的函数调用。

Second; 第二; This thread makes me think that although I load the config with the call of dictConfig() , I still need to apply it to the logging with further calls in my logger.py file. 该线程使我认为,尽管我使用dictConfig()调用加载了配置,但仍需要通过logger.py文件中的进一步调用将其应用于日志记录。 It seems a bit redundant that you have the config and then have to verbosely apply each setting anyway. 拥有配置,然后无论如何都要冗长地应用每个设置,似乎有点多余。

Additionally; 另外; When I tried using the Configuration file format it worked as I thought it would. 当我尝试使用配置文件格式时,它按照我的预期工作。 Namely; 即; loading the file with one function call and being able to make logging calls straight away. 通过一个函数调用加载文件,并能够立即进行日志记录调用。 This is confusing, because why would the older fileConfig() call used with this format offer a more streamlined functionality than dictConfig() with JSON or YAML? 这是令人困惑的,因为与使用JSON或YAML的dictConfig()相比,与此格式一起使用的较早的fileConfig()调用为什么会提供更简化的功能?

Ultimately, I'm a bit confused and would like to figure this out. 最终,我有点困惑,想解决这个问题。 I appreciate your time and help. 感谢您的宝贵时间和帮助。

EDIT: From Alex.P's comment, I added the following handler to log_config.json and changed the handler the root to it. 编辑:从Alex.P的评论中,我将以下处理程序添加到log_config.json并将其根更改为该处理程序。

"console": {
            "class": "logging.StreamHandler",
            "level": "DEBUG",
            "formatter": "basic",
            "stream": "ext://sys.stdout"
        },

Checking the output, it is the same as above. 检查输出,与上面相同。

Ah, I figured out what was wrong. 啊,我找出了问题所在。 Turns out it was the JSON. 原来是JSON。 From this example which I was basing my work off of, it has an extra logging property in the JSON, which encapsulates all the loggers, handlers etc. 这个基于我的工作的示例中,它在JSON中具有一个额外的logging属性,该属性封装了所有记录器,处理程序等。

Removing that property and having the hierarchy more like a YAML file (which I also tested, and got working correctly), it works as expected. 删除该属性并使层次结构更像是YAML文件(我也对其进行了测试,并且可以正常工作),它可以按预期工作。 I could even remove the extra call to basicConfig in my logger.py . 我甚至可以删除的额外通话basicConfiglogger.py

Final JSON; 最终JSON;

{
    "version": 1,
    "disable_existing_loggers": "false",
    "formatters": {
        "basic": {
            "class": "logging.Formatter",
            "datefmt": "%I:%M:%S",
            "format": "%(asctime)s %(levelname)s %(name)s %(message)s"
        }
    },

    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "level": "DEBUG",
            "formatter": "basic",
            "stream": "ext://sys.stdout"
        },
        "file": {
            "class": "logging.FileHandler",
            "level": "DEBUG",
            "formatter": "basic",
            "filename": "test.log",
            "mode": "w",
            "encoding": "utf-8"
        }
    },

    "loggers": { },

    "root": {
        "handlers": ["console", "file"],
        "level": "DEBUG"
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 logging.config.dictConfig似乎不起作用 - logging.config.dictConfig does not seem to work 如果我调用logging.config.dictConfig,记录器将在初始化后发生更改 - logger is changing after init if I call logging.config.dictConfig 配置日志记录在python中使用logging.config.dictConfig时出错 - Error when config logging use logging.config.dictConfig in python Python 使用 logging.config.dictConfig 以 {} 格式记录 - Python logging with {} format using logging.config.dictConfig logging.config.dictConfig 的完整示例在哪里? - Where is a complete example of logging.config.dictConfig? Python日志dictConfig中的常见日志记录器设置 - Common logger settings in Python logging dictConfig 带有 logging.config.dictConfig 的 JSON 日志格式器 - JSON-log-formatter with logging.config.dictConfig 如何通过 logging.config.dictConfig - FileHandler 指定 namer &amp; rotator - How to specify namer & rotator through logging.config.dictConfig - FileHandler 在日志文件名中包含日期并创建特定大小的日志文件,同时使用 `logging.config.dictConfig()` 在 python 中保留最后 3 个日志文件 - Including date in the log file name & creating log files of certain size while keeping last 3 log files in python with `logging.config.dictConfig()` 哪个模块应该包含logging.config.dictConfig(my_dictionary)? my_dictionary怎么样? - Which module should contain logging.config.dictConfig(my_dictionary)? What about my_dictionary?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM