Python3 日志 yaml 配置

afm*_*one 4 configuration logging yaml python-3.x

我是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'
Run Code Online (Sandbox Code Playgroud)

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

logging.config.fileConfig('conf/logging.yaml')
Run Code Online (Sandbox Code Playgroud)

我的配置是:

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]
Run Code Online (Sandbox Code Playgroud)

我使用 python 3.6.4。谢谢

Zho*_*uan 12

根据定义: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)
Run Code Online (Sandbox Code Playgroud)

  • 请注意,您必须安装“pyyaml”才能正常工作。 (8认同)