Python - Handler不检测自定义处理程序类

时间:2013-09-03 10:28:15

标签: python logging

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

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 个答案:

答案 0 :(得分:2)

您的sys.path需要包含project/confs目录,否则您将无法导入custom_handler模块。确保是这种情况后再试一次。

更新:我不确定log.py是设置路径的地方。没有一种正确的方法可以做到这一点 - 有各种关于如何设置Python项目的教程。