尝试记录语句时,为什么会出现此“ AttributeError”异常?

时间:2019-09-18 08:08:09

标签: python-3.x logging

我已经在python中创建了一个自定义记录器,以控制日志的格式和输出。但是,每当我尝试记录某些内容时,我都会得到一个AttributeError: 'function' object has no attribute 'level'

这是自定义Logger类:

import sys
import logging


class Logger:
    def __init__(self, name, level, output_path):
        self.name = name
        self.level = level
        self.output_path = output_path

    def get_custom_logger(self):
        formatter = self._get_custom_formatter()
        logger = logging.getLogger(self.name)
        logger.setLevel(self.level)
        logger.addHandler(self._get_file_handler)
        logger.addHandler(self._get_stream_handler)
        return logger

    def _get_file_handler(self, formatter):
        file_handler = logging.FileHandler(self.output_path, mode='a')
        file_handler.setFormatter(formatter)
        return file_handler

    def _get_stream_handler(self, formatter):
        stream_handler = logging.StreamHandler(stream=sys.stdout)
        stream_handler.setFormatter(formatter)
        return stream_handler

    def _get_custom_formatter(self):
        format = '[%(levelname)-4s] - %(asctime)s - ' + self.name + ' - %(message)s'
        date_format = '%Y-%m-%d %H:%M:%S'
        return logging.Formatter(fmt=format, datefmt=date_format)

每当我尝试log.info时都会出现问题。例如:

logger = Logger(__name__, logging.INFO, log_file)
log = logger.get_custom_logger()
log.info('Something')

在堆栈跟踪下面:

File "cart_worker.py", line 29, in callback
    log.info('Received {0}'.format(body))
  File "/usr/lib/python3.6/logging/__init__.py", line 1308, in info
    self._log(INFO, msg, args, **kwargs)
  File "/usr/lib/python3.6/logging/__init__.py", line 1444, in _log
    self.handle(record)
  File "/usr/lib/python3.6/logging/__init__.py", line 1454, in handle
    self.callHandlers(record)
  File "/usr/lib/python3.6/logging/__init__.py", line 1515, in callHandlers
    if record.levelno >= hdlr.level:
AttributeError: 'function' object has no attribute 'level'

0 个答案:

没有答案