【问题标题】:Python3 logging yaml configurationPython3 记录 yaml 配置
【发布时间】:2018-08-07 07:17:15
【问题描述】:

我是 python 新手。我正在尝试导入 yaml 中定义的日志记录配置。 我得到错误:

Traceback (most recent call last):
  File "D:/python_3/db_interact/dbInteract.py", line 200, in <module>
    logging.config.fileConfig('conf/logging.yaml')
  File "C:\Programs\Python\Python36\lib\logging\config.py", line 74, in fileConfig
    cp.read(fname)
  File "C:\Programs\Python\Python36\lib\configparser.py", line 697, in read
    self._read(fp, filename)
  File "C:\Programs\Python\Python36\lib\configparser.py", line 1080, in _read
    raise MissingSectionHeaderError(fpname, lineno, line)
configparser.MissingSectionHeaderError: File contains no section headers.
file: 'conf/logging.yaml', line: 1
'version: 1\n'

我使用以下方式导入配置:

logging.config.fileConfig('conf/logging.yaml')

我的配置是:

version: 1
disable_existing_loggers: true
formatters:
  simple:
    format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers:
  console:
    class: logging.StreamHandler
    level: INFO
    formatter: simple
    stream: ext://sys.stdout
  file:
    class: logging.FileHandler
    level: DEBUG
    filename: logs/dbInteract.log
loggers:
  simpleExample:
    level: DEBUG
    handlers: [console]
    propagate: no
root:
  level: DEBUG
  handlers: [console,file]

我使用 python 3.6.4。 谢谢

【问题讨论】:

    标签: python-3.x logging configuration yaml


    【解决方案1】:

    根据定义:fileConfig 从 configparser-format 文件中读取日志记录配置。您提供的是 yaml 格式文件。

    因此,您可以将 yaml 文件解析为 dict obj,然后将其提供给 logging.config.dictConfig(config):

    import logging.config
    import yaml
    
    with open('./test.yml', 'r') as stream:
        config = yaml.load(stream, Loader=yaml.FullLoader)
    
    logging.config.dictConfig(config)
    

    【讨论】:

    • 请注意,您必须安装 pyyaml 才能正常工作。
    猜你喜欢
    • 2011-02-20
    • 2023-03-31
    • 1970-01-01
    • 2018-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 2022-01-09
    相关资源
    最近更新 更多