如何在Django App中通用设置记录器类

时间:2018-06-22 17:44:01

标签: python django logging

我有一个记录器,如果在调用logger.debug时未提供log_line,则只会添加log_line

class UrlLogger(logging.Logger):
    def _log(self, level, msg, args, exc_info=None, extra=None):
        if extra is None:
            extra = {'log_line':' '}
        super(UrlLogger, self)._log(level, msg, args, exc_info, extra)

我大约需要添加20个不同的模块

logging.setLoggerClass(UrlLogger)

如何在设置中将此设置为默认值?

我的设置当前如下所示:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(name)s %(asctime)s %(module)s %(process)d %(thread)d %(pathname)s@%(lineno)s: %(message)s'
        },
        'simple': {
            'format': '[%(levelname)8s] [%(asctime)s] %(module)10s/%(filename)s:%(log_line)s - %(message)s',
            'datefmt': '%d-%m-%Y %H:%M:%S'
        },
    },

    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'level': LOG_LEVEL,
            'formatter': 'simple'
        },
    },
    'loggers': {
        '': {
            'level': LOG_LEVEL,
            'handlers': ['console'],
            'class': ['UrlLogger'],
    },

如您所见,我尝试在此处进行设置,但由于我仍然遇到错误,因此我认为这不起作用。

Message: 'Not Found: %s'
Arguments: ('/tool_job_list/1/1fa119372de6/job/check/jexecution/report',)
--- Logging error ---
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/logging/__init__.py", line 992, in emit
    msg = self.format(record)
  File "/usr/local/lib/python3.6/logging/__init__.py", line 838, in format
    return fmt.format(record)
  File "/usr/local/lib/python3.6/logging/__init__.py", line 578, in format
    s = self.formatMessage(record)
  File "/usr/local/lib/python3.6/logging/__init__.py", line 547, in formatMessage
    return self._style.format(record)
  File "/usr/local/lib/python3.6/logging/__init__.py", line 391, in format
    return self._fmt % record.__dict__
KeyError: 'log_line'

当前端对django后端进行失败的API调用(错误的uri)时,会发生此错误。我以为失败的api调用会在不使用我的UrlLogger的情况下记录错误(否则,除非Logger类中存在错误,否则不会出现关键错误)。

我在这里做什么错了?

0 个答案:

没有答案