1

我正在尝试创建自己的日志处理程序,它扩展了 logging.Handler

import logging
from logging import Handler

class DBHandler(Handler,object):
    model = None
    def __init__(self, model):
        super(DBHandler, self).__init__(self)
        mod = __import__(model)
        components = name.split('.')
        for comp in components[1:]:
            mod = getattr(mod, comp)
        self.model = mod

    def emit(self,record):
        log_entry = self.model(level=record.levelname, message=record.msg)
        log_entry.save()

这是日志配置:

'search_log':{
    'level': 'INFO',
    'class': 'logger.handlers.DBHandler',
    'model': 'logger.models.SearchLog',
    'formatter': 'verbose',
     }

但是我收到以下错误,请参阅stacktrace:

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/james/virtualenv/hydrogen/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line
    utility.execute()
  File "/home/james/virtualenv/hydrogen/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 382, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/james/virtualenv/hydrogen/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 252, in fetch_command
    app_name = get_commands()[subcommand]
  File "/home/james/virtualenv/hydrogen/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 101, in get_commands
    apps = settings.INSTALLED_APPS
  File "/home/james/virtualenv/hydrogen/local/lib/python2.7/site-packages/django/utils/functional.py", line 184, in inner
    self._setup()
  File "/home/james/virtualenv/hydrogen/local/lib/python2.7/site-packages/django/conf/__init__.py", line 42, in _setup
    self._wrapped = Settings(settings_module)
  File "/home/james/virtualenv/hydrogen/local/lib/python2.7/site-packages/django/conf/__init__.py", line 135, in __init__
    logging_config_func(self.LOGGING)
  File "/usr/lib/python2.7/logging/config.py", line 777, in dictConfig
    dictConfigClass(config).configure()
  File "/usr/lib/python2.7/logging/config.py", line 575, in configure
    '%r: %s' % (name, e))
ValueError: Unable to configure handler 'search_log': Level not an integer or a valid string: <logger.handlers.DBHandler object at 0x2df1710>

我一直在查看 python 日志记录源代码,但无法弄清楚我做错了什么

4

2 回答 2

2

问题出在这一行:

super(DBHandler, self).__init__(self)

self如果您使用super这种方式,您不应该通过。您self有效地传递了两次,并且logging模块试图将第二次解释self为日志记录级别。

于 2012-09-17T03:02:38.133 回答
0

我通过将 level='Debug' 更改为 level=30 python 3.9.0 解决了同样的问题

"级别不是整数或有效字符串:'%r%' 级别

于 2021-09-20T13:02:12.650 回答