【问题标题】:Using logging with coloredlogs使用带彩色日志的日志记录
【发布时间】:2020-01-30 14:03:00
【问题描述】:

我正在尝试创建一个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"
    }
}

关于使用coloredlogslogging.config.dictConfig() 的文档实际上是不存在的。

【问题讨论】:

    标签: python-3.x logging colors config


    【解决方案1】:

    安装coloredlogs module后用

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

    logging docu 中描述了如何为日志格式化程序创建用户定义的对象。请注意,上面的代码 sn -p 只是我正在使用的配置示例。

    【讨论】:

      猜你喜欢
      • 2013-10-22
      • 1970-01-01
      • 2017-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-26
      • 2023-03-11
      相关资源
      最近更新 更多