python-3.x - Python3 日志 yaml 配置

标签 python-3.x logging configuration yaml

我是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。
谢谢

最佳答案

根据定义: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)

关于python-3.x - Python3 日志 yaml 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49012123/

相关文章:

python - 使用括号python创建对象

python-3.x - Microsoft Speech to Text Python SDK SPXERR_INVALID_HEADER 问题

python - Airflow + python 日志记录模块不写入日志文件

c# - 为不同的 Web 应用程序共享相同的配置设置

go - 如何为多个环境和突变的组合生成配置

binding - 组织 Guice 绑定(bind)配置的解决方案

python - 如何减少字符分隔字符串的大小?

python-3.x - 计算文本中不包括缩进的空格数

java - log4j:WARN 找不到记录器的附加程序。 Log4j 1.2.17 jar

python - Sentry 、乌鸦和 Django celery