【问题标题】:Django - Custom logging handler class can't be picked upDjango - 无法拾取自定义日志记录处理程序类
【发布时间】:2020-04-15 03:26:04
【问题描述】:

我正在开发一个 Django 应用程序(Django 2.0.7、Python 3.7、Windows 10、PyCharm),我需要编写一个自定义日志处理程序,以便将日志消息存储到数据库中。

当我尝试运行应用程序时出现此错误:

pydev debugger: process 27148 is connecting

Connected to pydev debugger (build 192.6817.19)
pydev debugger: process 28448 is connecting

Unhandled exception in thread started by <_pydev_bundle.pydev_monkey._NewThreadStartupWithTrace object at 0x000001F1C52AD648>
Traceback (most recent call last):
  File "C:\Program Files\Python\lib\logging\config.py", line 387, in resolve
    found = getattr(found, frag)
AttributeError: module 'Inmobiliaria.inmobiliaria.utils.logs' has no attribute 'handlers'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files\Python\lib\logging\config.py", line 562, in configure
    handler = self.configure_handler(handlers[name])
  File "C:\Program Files\Python\lib\logging\config.py", line 712, in configure_handler
    klass = self.resolve(cname)
  File "C:\Program Files\Python\lib\logging\config.py", line 389, in resolve
    self.importer(used)
  File "C:\Users\facun\Desktop\DEV\forreal\backend\Inmobiliaria\inmobiliaria\utils\logs\handlers.py", line 2, in <module>
    from Inmobiliaria.inmobiliaria.services.application_log_services import create_application_log
  File "C:\Users\facun\Desktop\DEV\forreal\backend\Inmobiliaria\inmobiliaria\services\application_log_services.py", line 1, in <module>
    from Inmobiliaria.inmobiliaria.models import Applicationlog
  File "C:\Users\facun\Desktop\DEV\forreal\backend\Inmobiliaria\inmobiliaria\models.py", line 9, in <module>
    UserModel = get_user_model()
  File "C:\Users\facun\Envs\for-real\lib\site-packages\django\contrib\auth\__init__.py", line 194, in get_user_model
    return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False)
  File "C:\Users\facun\Envs\for-real\lib\site-packages\django\apps\registry.py", line 192, in get_model
    self.check_apps_ready()
  File "C:\Users\facun\Envs\for-real\lib\site-packages\django\apps\registry.py", line 127, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm 2019.2.2\helpers\pydev\_pydev_bundle\pydev_monkey.py", line 747, in __call__
    ret = self.original_func(*self.args, **self.kwargs)
  File "C:\Users\facun\Envs\for-real\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\facun\Envs\for-real\lib\site-packages\django\core\management\commands\runserver.py", line 112, in inner_run
    autoreload.raise_last_exception()
  File "C:\Users\facun\Envs\for-real\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception
    raise _exception[1]
  File "C:\Users\facun\Envs\for-real\lib\site-packages\django\core\management\__init__.py", line 327, in execute
    autoreload.check_errors(django.setup)()
  File "C:\Users\facun\Envs\for-real\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\facun\Envs\for-real\lib\site-packages\django\__init__.py", line 19, in setup
    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
  File "C:\Users\facun\Envs\for-real\lib\site-packages\django\utils\log.py", line 73, in configure_logging
    logging_config_func(logging_settings)
  File "C:\Program Files\Python\lib\logging\config.py", line 799, in dictConfig
    dictConfigClass(config).configure()
  File "C:\Program Files\Python\lib\logging\config.py", line 570, in configure
    '%r' % name) from e
ValueError: Unable to configure handler 'db_handler'

到目前为止,这是我的代码:

----settings.py(LOGGING dict的处理程序部分)----

'handlers': {
        'debug_file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'Logs/DebugTest.log',
        },
        'info_file': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'maxBytes': 1024*1024*10,  # 10MB
            'backupCount': 10,
            'filename': 'Logs/InfoTest.log',
            'formatter': 'verbose',
        },
        'db_handler': {
            'level': 'INFO',
            'class': 'Inmobiliaria.inmobiliaria.utils.logs.handlers.DatabaseHandler',
            'formatter': 'verbose',
        },
    },

----handlers.py----

import logging
from Inmobiliaria.inmobiliaria.services.application_log_services import create_application_log


class DatabaseHandler(logging.Handler):
    """
    Logging handler that inserts log messages into the database
    """
    def __init__(self):
        logging.Handler.__init__(self)

    def emit(self, record):
        msg: logging.LogRecord = self.format(record)
        ret_val = create_application_log(msg.msg, msg.levelname, msg.thread, msg.process, msg.filename, msg.lineno, msg.created)
        print(ret_val)

这个 handlers.py 文件位于

Inmobiliaria
    inmobiliaria
        utils
            logs
                handlers.py <-----

我希望你能帮助我。

非常感谢!

【问题讨论】:

    标签: python django logging handler python-3.7


    【解决方案1】:

    此错误是由先有鸡还是先有蛋的问题引起的。如果我理解正确,处理程序正在使用 django 模型登录到数据库。所有 django 模型都需要加载设置并初始化 django 应用程序才能使用。但是必须在加载应用程序之前初始化日志记录。为了解决这个问题,您必须删除处理程序对模型的依赖,例如,在 django 模型之外创建一个连接并插入它。或者,您可以通过将模型设为本地导入来尝试延迟导入模型的使用。

    【讨论】:

    • 谢谢!!!你说的对。我已经通过直接连接到数据库来解决它。我有一个问题(我不是一位经验丰富的开发人员):与数据库建立这种外部连接而不是使用模型是一种好习惯吗?
    • 是的,只要您只将它用于插入,然后将模型用于其他一切,它应该没问题。唯一的技巧是在与数据库通信失败/异常的情况下必须关闭和/或重新打开连接。
    【解决方案2】:

    我有同样的问题,我发现在 def 函数中导入 django 模型可能会起作用,就像:

        def emit(self, record):
            from mylogs.models import MysqlLogs
            log = MysqlLogs()
            log.desc = record.msg
            log.save()
    

    【讨论】:

    • 这并不能真正回答问题。如果您有其他问题,可以点击 进行提问。要在此问题有新答案时收到通知,您可以follow this question。一旦你有足够的reputation,你也可以add a bounty 来引起更多的关注这个问题。
    猜你喜欢
    • 2011-10-20
    • 1970-01-01
    • 2020-05-27
    • 2022-11-16
    • 2011-03-08
    • 1970-01-01
    • 2016-07-20
    • 2021-09-27
    • 1970-01-01
    相关资源
    最近更新 更多