Django-无法获取自定义日志处理程序类

问题描述 投票:1回答:1

我正在开发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字典的处理程序部分)----

'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个回答
1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.