Python 日志记录配置,如 Java log4j

问题描述 投票:0回答:1

我是一名 Java 开发人员,已经过渡到 Python 3 开发。我需要在我的 Python 应用程序中配置日志记录,我想以类似于我在 Java 中配置 log4j 的方式来完成它。理想情况下,我希望我的 Python 日志记录配置文件采用 YAML 格式。我该怎么做?

python python-3.x logging configuration log4j
1个回答
0
投票

我无法找到这个问题的全面答案。我最终弄明白了,并将在这里分享我的解决方案。

我的 YAML 格式的日志记录配置文件是这样的(我没有记录到文件,所以我把那部分注释掉了):

---
version: 1
disable_existing_loggers: False

# -------------------------------------------------------------------------------------------------
# Define format of output logs (named 'simple').
formatters:
    #simple:
    #    format: "XXX %(asctime)s - %(name)s - %(levelname)s - %(message)s"
    console_formatter:
        format: "%(asctime)s | %(levelname)8s | %(name)50s | %(funcName)50s | %(message)s"

# -------------------------------------------------------------------------------------------------
# REFERENCE: https://docs.python.org/3/library/logging.handlers.html
handlers:

    ## Create rotating file handler using 'simple' format.
    #file_handler:
    #    class: logging.handlers.RotatingFileHandler
    #    level: INFO
    #    formatter: simple
    #    filename: jims-fantastic-log-file.log
    #    maxBytes: 10485760 # 10MB
    #    backupCount: 5
    #    encoding: utf8

    # Create console handler
    console_handler:
        class: logging.StreamHandler
        formatter: console_formatter

# -------------------------------------------------------------------------------------------------
# The 'root' logger (parent of all other loggers) is treated as a special case in the logging configuration.
# Any settings for the root logger become the default settings for all other loggers.
# You can override those defaults by providing a configuration for any loggers that need one.
root:
    level: WARN
    # handlers: [file_handler, console_handler]
    handlers: [console_handler]

# Provider logger-specific configuration below.
# Must like log4j in Java, logger names are treated as a hierarchy. The developer will typically use their module
# names as logger names, so the top-level package is the 'parent' and all the subpackages are the 'children'.
loggers:

    mypackage:
        level: INFO
        propagate: False
        handlers: [console_handler]

    mypackage.childpkg1:
        level: WARNING
        propagate: False
        handlers: [console_handler]

    mypackage.childpkg2:
        level: DEBUG
        propagate: False
        handlers: [console_handler]

这是我为在我的应用程序中初始化日志记录而定义的微型类。它只是加载 YAML 文件:

import logging
import logging.config
import yaml


class LoggingUtils:

    def __init__(self):
        pass

    @staticmethod
    def configure_logging(path_to_logging_config_yaml_file: str):
        # Initialize the logger once as the application starts up.
        with open(path_to_logging_config_yaml_file, 'rt') as f:
            config = yaml.safe_load(f.read())
        logging.config.dictConfig(config)

        # Get an instance of the logger and use it to write a log!
        # Note: Do this AFTER the config is loaded above or it won't use the config.
        logger = logging.getLogger(__name__)
        logger.info("Configured the logger!")

参考我学这个的教程:

© www.soinside.com 2019 - 2024. All rights reserved.