使用带有彩色日志的logging

5
我正在尝试创建一个json配置文件,并使用coloredlogs库进行彩色输出,以便用logging.config.dictConfig()进行加载。
然而,我遇到了以下错误:
Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\logging\config.py", line 538, in configure
    formatters[name])
  File "C:\Program Files\Python36\lib\logging\config.py", line 669, in configure_formatter
    result = c(fmt, dfmt, style)
  File "C:\Program Files\Python36\lib\site-packages\coloredlogs\__init__.py", line 834, in __init__
    self.level_styles = self.nn.normalize_keys(DEFAULT_LEVEL_STYLES if level_styles is None else level_styles)
  File "C:\Program Files\Python36\lib\site-packages\coloredlogs\__init__.py", line 1111, in normalize_keys
    return dict((self.normalize_name(k), v) for k, v in value.items())
AttributeError: 'str' object has no attribute 'items'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File ".\sci.py", line 205, in <module>
    main()
  File ".\sci.py", line 180, in main
    logging.config.dictConfig(json.load(json_config))
  File "C:\Program Files\Python36\lib\logging\config.py", line 795, in dictConfig
    dictConfigClass(config).configure()
  File "C:\Program Files\Python36\lib\logging\config.py", line 541, in configure
    'formatter %r: %s' % (name, e))
ValueError: Unable to configure formatter 'colored': 'str' object has no attribute 'items'

我的配置文件如下:

{
    "version": 1,
    "disable_existing_loggers": true,

    "formatters": {
        "colored": {
            "class": "coloredlogs.ColoredFormatter",
            "datefmt": "%H:%M:%S",
            "format": "%(asctime)s %(module)-16s: %(levelname)-8s %(message)s"
        }
    },

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

    "loggers": {
    },

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

coloredlogs在使用logging.config.dictConfig()时的文档实际上是不存在的。

1个回答

6

安装了coloredlogs模块后,

$ pip install coloredlogs

您可以配置控制台输出的颜色。通常情况下,这是通过类似以下方式来实现的:
coloredlogs.install(level='DEBUG', logger=logger)

在你的代码中。

然而,如果你想使用coloredlogs和字典配置一起使用,你需要创建一个特定的格式化程序,如下所示:

import logging.config

logging.config.dictConfig(my_logging_dict)
logger = logging.getLogger(__name__)

my_logging_dict = {
    'version': 1,
    'disable_existing_loggers': True,   # set True to suppress existing loggers from other modules
    'loggers': {
        '': {
           'level': 'DEBUG',
           'handlers': ['console', 'file'],
        },
    },
    'formatters': {
        'colored_console': {
           '()': 'coloredlogs.ColoredFormatter', 
           'format': "%(asctime)s - %(name)s - %(levelname)s - %(message)s", 
           'datefmt': '%H:%M:%S'
        },
        'format_for_file': {
           'format': "%(asctime)s :: %(levelname)s :: %(funcName)s in %(filename)s (l:%(lineno)d) :: %(message)s", 
           'datefmt': '%Y-%m-%d %H:%M:%S'
        },
    'handlers': {
        'console': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',
            'formatter': 'colored_console',
            'stream': 'ext://sys.stdout'
        },
        'file': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'formatter': 'format_for_file',
            'filename': log_file,
            'maxBytes': 500000,
            'backupCount': 5
        }
    },
}

如何为日志格式化程序创建用户定义对象在日志文档中有描述。请注意,上面的代码片段只是我正在使用的配置示例。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接