Python 2.4.3: ConfigParser.NoSectionError: No section: 'formatters'

旧时模样 提交于 2019-12-03 16:07:12

问题


Trying to use a logging configuration file to implement TimedRotatinigFileHandler.

Just won't take the config file for some reason.

Any suggestions appreciated.


x.py:

import logging
import logging.config
import logging.handlers

logging.config.fileConfig("x.ini")

MyLog = logging.getLogger('x')

MyLog.debug('Starting') 

x.ini:

[loggers]
keys=root

[logger_root]
level=NOTSET
handlers=trfhand

[handlers]
keys=trfhand

[handler_trfhand]
class=handlers.TimedRotatingFileHandler
when=M
interval=1
backupCount=11
formatter=generic
level=DEBUG
args=('/var/log/x.log',)

[formatters]
keys=generic

[formatter_generic]
class=logging.Formatter
format=%(asctime)s %(levelname)s %(message)s
datefmt=

Traceback (most recent call last):
  File "x.py", line 5, in ?
    logging.config.fileConfig("x.ini")
  File "/usr/lib/python2.4/logging/config.py", line 76, in fileConfig
    flist = cp.get("formatters", "keys")
  File "/usr/lib/python2.4/ConfigParser.py", line 511, in get
    raise NoSectionError(section)
ConfigParser.NoSectionError: No section: 'formatters'

Thanks


回答1:


The error message is strictly accurate but misleading.

The reason the "formatters" section is missing, is because the logging module can't find the file you passed to logging.config.fileConfig.

Try using an absolute file path.




回答2:


Yes, @ekhumoro was right. It seems that logging expects an absolute path. Python team should change this error message to something more readable; it just cannot see my file, not because the config file itself is wrong.

I managed to solve this by defining a BASE_DIR variable in a config file and import it as the prefix of the path, just as Django does. And, remember to create the log file's parent dir(s) if they are not created.

I define the path and the logger in config.py:

import os
BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

import logging
import logging.config
logging.config.fileConfig(os.path.join(BASE_DIR, 'utils', 'logger.conf')) # the `logger.conf` locates under 'myproject/utils/'
logger = logging.getLogger("mylog") # 'mylog' should exist in `logger.conf` in the logger part

In other modules:

from config import logger
...

logger.info("Your loggings modules should work now!! - WesternGun")


来源:https://stackoverflow.com/questions/7922602/python-2-4-3-configparser-nosectionerror-no-section-formatters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!