afmulone
afmulone

Reputation: 177

Python3 logging yaml configuration

I am new in python. I am trying to import logging configuration defined in yaml. I obtain error:

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'

I import configuration using:

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

My configuration is:

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]

I use python 3.6.4. Thanks

Upvotes: 14

Views: 22092

Answers (1)

ZhouQuan
ZhouQuan

Reputation: 1067

According to definition: fileConfig Reads the logging configuration from a configparser-format file. What you supply is yaml-format file.

So You could parse your yaml file to dict obj and then supply it to 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)

Upvotes: 29

Related Questions