简体   繁体   English

Python 2.4.3:ConfigParser.NoSectionError:没有部分:'formatters'

[英]Python 2.4.3: ConfigParser.NoSectionError: No section: 'formatters'

Trying to use a logging configuration file to implement TimedRotatinigFileHandler . 尝试使用日志记录配置文件来实现TimedRotatinigFileHandler

Just won't take the config file for some reason. 由于某种原因,不会采取配置文件。

Any suggestions appreciated. 任何建议赞赏。


x.py: x.py:

import logging
import logging.config
import logging.handlers

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

MyLog = logging.getLogger('x')

MyLog.debug('Starting') 

x.ini: 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 谢谢

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 . 缺少“formatters”部分的原因是因为日志记录模块找不到您传递给logging.config.fileConfig的文件。

Try using an absolute file path. 尝试使用绝对文件路径。

Yes, @ekhumoro was right. 是的,@ yehumoro是对的。 It seems that logging expects an absolute path. 似乎logging需要绝对路径。 Python team should change this error message to something more readable; Python团队应该将此错误消息更改为更具可读性的内容; 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. 我设法通过在配置文件中定义BASE_DIR变量并将其作为路径的前缀导入来解决这个问题,就像Django一样。 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 : 我在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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM