logging的dictConfig用法

该Python脚本展示了如何使用logging.config.dictConfig进行日志配置,包括定义不同格式的Formatter,设置StreamHandler和FileHandler处理日志输出,以及定义多个级别的日志记录器。脚本最后执行了不同级别的日志消息,显示在控制台和文件中。
#!/usr/bin/env python
# -*- coding:utf-8 -*-


import logging.config

LOGGING_CONFIG = {
    # version - 表示版本,该键值为从1开始的整数。该key必选,除此之外,其它key都是可选。
    "version": 1,
    # formatters - 日志格式化器,其value值为一个字典,该字典的每个键值对都代表一个Formatter
    "formatters": {
        "default": {
            'format': '%(asctime)s %(filename)s %(lineno)s %(levelname)s %(message)s',
        },
        "plain": {
            "format": "%(message)s",
        },
    },
    # handlers - 日志处理器,其value值为一个字典,该字典的每个键值对都代表一个Handler
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "level": "INFO",
            "formatter": "default",
        },
        "console_plain": {
            "class": "logging.StreamHandler",
            "level": logging.INFO,
            "formatter": "plain"
        },
        "file": {
            "class": "logging.FileHandler",
            "level": 20,
            "filename": "./log.txt",
            "formatter": "default",
        }
    },
    # loggers - 日志记录器,其value值为一个字典,该字典的每个键值对都代表一个Handler
    "loggers": {
        "console_logger": {
            "handlers": ["console"],
            "level": "INFO",
            "propagate": False,
        },
        "console_plain_logger": {
            "handlers": ["console_plain"],
            "level": "DEBUG",
            "propagate": False,
        },
        "file_logger": {
            "handlers": ["file"],
            "level": "INFO",
            "propagate": False,
        }
    },
    "disable_existing_loggers": True,
    "root": {
        "handlers": ["console"],
        # 取root level和console的level最严格的日志等级,下面输出为INFO等级
        "level": "DEBUG"
    },
}

# 运行测试
logging.config.dictConfig(LOGGING_CONFIG)
logger = logging.getLogger("console_logger")
logger.debug('debug message')
logger.info('info message')
logger.warning('warning message')
logger.error('error message')
logger.critical('critical message')
logger.info('#######################')
logger = logging.getLogger("root")
logger.debug('debug message')
logger.info('info message')
logger.warning('warning message')
logger.error('error message')
logger.critical('critical message')

输出:

E:\pythonPrj\common\venv\Scripts\python.exe E:/pythonPrj/common/dictconfig.py
2023-07-10 01:31:56,597 dictconfig.py 68 INFO info message
2023-07-10 01:31:56,597 dictconfig.py 69 WARNING warning message
2023-07-10 01:31:56,597 dictconfig.py 70 ERROR error message
2023-07-10 01:31:56,597 dictconfig.py 71 CRITICAL critical message
2023-07-10 01:31:56,597 dictconfig.py 72 INFO #######################
2023-07-10 01:31:56,597 dictconfig.py 75 INFO info message
2023-07-10 01:31:56,597 dictconfig.py 76 WARNING warning message
2023-07-10 01:31:56,597 dictconfig.py 77 ERROR error message
2023-07-10 01:31:56,597 dictconfig.py 78 CRITICAL critical message

Process finished with exit code 0
`DictConfig` 是 Python `logging` 模块中用于配置日志系统的一种方式,通过字典形式来定义日志的各项配置。 ### 定义 `DictConfig` 允许使用字典结构来配置日志系统,该字典可以定义日志系统的各个组件,如记录器(Logger)、处理器(Handler)、过滤器(Filter)和格式化器(Formatter)等,从而灵活地定制日志的输出行为 [^2]。 ### 使用方法 以下是使用 `DictConfig` 的详细步骤及示例代码: 1. **创建日志配置字典**:配置字典中包含了日志系统的各个组件的详细设置,如记录器的名称、处理器的类型和输出位置、格式化器的格式等。 2. **加载配置字典**:使用 `logging.config.dictConfig()` 函数加载配置字典,将配置应用到日志系统中。 3. **获取记录器**:使用 `logging.getLogger()` 函数获取指定名称的记录器,通过记录器来记录日志。 示例代码如下: ```python import logging import logging.config # 日志配置字典 log_config = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s' } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'standard', 'level': 'DEBUG' } }, 'loggers': { 'my_logger': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False } } } # 加载配置字典 logging.config.dictConfig(log_config) # 获取记录器 logger = logging.getLogger('my_logger') # 记录日志 logger.debug('This is a debug message') logger.info('This is an info message') logger.warning('This is a warning message') logger.error('This is an error message') logger.critical('This is a critical message') ``` ### 应用场景 - **项目日志管理**:在一个项目中,日志模块非常重要,通过 `DictConfig` 可以灵活配置日志的输出位置、格式和级别,方便追踪异常错误的位置和详细信息,为解决问题提供帮助 [^2]。 - **复杂日志需求**:当项目需要对不同模块、不同级别或不同类型的日志进行差异化处理时,`DictConfig` 可以方便地实现这些复杂的日志配置需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值