Python 2.4.3: ConfigParser.NoSectionError: 没有节: 'formatters

23 投票
2 回答
34556 浏览
提问于 2025-04-17 05:08

我在尝试使用一个日志配置文件来实现 TimedRotatingFileHandler

但是不知道为什么,它就是不接受这个配置文件。

如果有任何建议,我会很感激。


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'

谢谢

2 个回答

5

没错,@ekhumoro说得对。看起来logging需要一个绝对路径。 Python团队应该把这个错误信息改得更容易理解一些;它只是找不到我的文件,并不是因为配置文件本身有问题。

我通过在配置文件中定义一个BASE_DIR变量来解决这个问题,然后像Django那样把它作为路径的前缀来使用。还有,记得如果日志文件的父目录还没创建的话,要先创建它们。

我在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

在其他模块中:

from config import logger
...

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

这个错误信息虽然说得很准确,但可能会让人感到困惑。

之所以“格式化器”这一部分缺失,是因为日志模块找不到你传给 logging.config.fileConfig 的那个文件。

你可以试试用一个绝对路径来指定文件。

撰写回答