Python - 处理程序无法检测到自定义处理程序类

4

我正在尝试登录一个文件并维护一个配置文件,如下所示的目录结构和以下文件内容。

HERE/
|--WORKSPACE/
|   |-- PROJECT/
|   |   |-- project/
|   |   |   |-- confs/
|   |   |   |   |-- __init__.py
|   |   |   |   |-- custom_handler.py
|   |   |   |   |-- log.ini
|   |   |   |-- log.py

log.py:

import os
import logging.config

logging.raiseExceptions = True
curr_dir = os.path.dirname(os.path.realpath(__file__))
CONFIG = os.path.join(curr_dir, 'confs/log.ini')

logging.config.fileConfig(CONFIG)

log.ini:

[loggers]
keys=file

[logger_file]
handlers=file
level=NOTSET

[formatters]
keys=complex

[formatter_complex]
format=%(asctime)s - %(name)s - %(levelname)s - %(module)s : %(lineno)d - %(message)s

[handlers]
keys=file

[handler_file]
class=custom_handler.TRFileHandler
interval=W2
backupCount=2
formatter=complex
level=WARNING
args=('project.log',)

custom_handler.py:

import os
from logging.handlers import TimedRotatingFileHandler

curr_dir = os.path.dirname(os.path.realpath(__file__))
parent_dir = os.path.dirname(curr_dir)
LOGS_DIR = os.path.join(parent_dir, 'logs')


class TRFileHandler(TimedRotatingFileHandler):
    def __init__(self, file_name):
        if not os.path.isdir(LOGS_DIR):
            os.makedirs(LOGS_DIR)
        super(TRFileHandler, self).__init__(os.sep.join(LOGS_DIR, file_name))

当我运行以下命令时,会出现相应的错误。看起来像是一个Python路径问题。但我不确定。它在“confs”目录层级下的Python文件中可以正常工作。
~HERE$ python WORKSPACE/PROJECT/project/log.py

Traceback (most recent call last):
  File "WORKSPACE/PROJECT/project/log.py", line 8, in <module>
    logging.config.fileConfig(CONFIG)
  File "/usr/lib/python2.7/logging/config.py", line 78, in fileConfig
    handlers = _install_handlers(cp, formatters)
  File "/usr/lib/python2.7/logging/config.py", line 153, in _install_handlers
    klass = _resolve(klass)
  File "/usr/lib/python2.7/logging/config.py", line 88, in _resolve
    found = __import__(used)
ImportError: No module named custom_handler
1个回答

2
您的 sys.path 需要包含 project/confs 目录,否则您将无法导入 custom_handler 模块。请确保这是正确的情况后再试一次。
更新:我不确定是否在 log.py 中设置路径。没有一种正确的方法来做这件事 - 有各种各样的教程可以用来设置 Python 项目。

是的,它确实解决了问题。但是,我还有一个与此相关的疑问。考虑到可能会有多个这样的包或目录,哪种方法才是正确的呢?我们可以使用 init.py 吗?目前我已经在 log.py 中添加了以下内容:sys.path.append(os.path.dirname(CONFIG)) - Anshu Kumar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接