使用有色日志记录

时间:2017-08-02 15:51:03

标签: python-3.x logging colors config

我正在尝试创建一个json配置文件,使用logging.config.dictConfig()库加载coloredlogs以获得彩色输出。

我收到以下错误:

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"
    }
}

关于coloredlogslogging.config.dictConfig()一起使用的文档几乎不存在。

1 个答案:

答案 0 :(得分:2)

使用

安装coloredlogs module
$ pip install coloredlogs

您可以将控制台输出配置为彩色。通常这是通过类似

来完成的
coloredlogs.install(level='DEBUG', logger=logger)

代码。

但是,如果要将有色日志与字典配置一起使用 你需要创建一个这样的特定格式化程序:

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
        }
    },
}

logging docu中介绍了如何为记录格式化程序创建用户定义的对象。请注意,上面的代码段只是我正在使用的配置的一个示例。