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

use*_*163 23 python logging config configparser

尝试使用日志配置文件来实现TimedRotatinigFileHandler.

由于某种原因,不会采取配置文件.

任何建议赞赏.


x.py:

import logging
import logging.config
import logging.handlers

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

MyLog = logging.getLogger('x')

MyLog.debug('Starting') 
Run Code Online (Sandbox Code Playgroud)

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=
Run Code Online (Sandbox Code Playgroud)
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'
Run Code Online (Sandbox Code Playgroud)

谢谢

ekh*_*oro 74

错误消息严格准确但有误导性.

缺少"formatters"部分的原因是因为日志记录模块找不到您传递给的文件logging.config.fileConfig.

尝试使用绝对文件路径.


Wes*_*Gun 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
Run Code Online (Sandbox Code Playgroud)

在其他模块中:

from config import logger
...

logger.info("Your loggings modules should work now!! - WesternGun")
Run Code Online (Sandbox Code Playgroud)