【问题标题】:How does Django logging workDjango 日志记录是如何工作的
【发布时间】:2018-02-14 09:16:08
【问题描述】:

我想在我的实时 Django 站点上实现日志记录,这样我就可以看到错误,所以我只是在我的本地开发服务器上练习使用它。

我在设置中添加了这段代码:

LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
    'console': {
        'class': 'logging.StreamHandler',
    },
   'file': {
       'level': 'DEBUG',
       'class': 'logging.FileHandler',
       'filename': 'log.django',
   },
},
'loggers': {
    'django': {
        'handlers': ['console','file'],
        'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),
    },
},
}

当我启动开发服务器时,它返回了这个:

Performing system checks...

System check identified no issues (0 silenced).
(0.009) 
            SELECT name, type FROM sqlite_master
            WHERE type in ('table', 'view') AND NOT name='sqlite_sequence'
            ORDER BY name; args=None
(0.000) SELECT "django_migrations"."app", "django_migrations"."name" FROM "django_migrations"; args=()
February 14, 2018 - 08:38:57
Django version 1.11.8, using settings 'draft1.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

但这并没有告诉我任何信息或显示错误。我希望能够追溯或记录所有错误。否则我无法在我的实时服务器中看到我的 Django 代码中的错误。

【问题讨论】:

  • 但是...您没有任何错误,甚至还没有任何请求。
  • 好的,所以我刚刚发起了一个错误的请求。它以很难破译的 SQL 格式返回错误代码。有什么方法可以简单地复制普通的 Django DEBUG = True 回溯?如果不使用日志记录,它无论如何都会显示回溯,但在我的实时 Django 服务器上它不会。
  • 我不明白您所说的“SQL 格式”错误代码是什么意思。
  • 例如这是错误代码中的一个 sn-p(它很长):False, '', '2018-02-14 09:22:34.850650', '1', 'news', False, 0, 8546, 2) (0.001) SELECT "post_postscore"."id", "post_postscore"."user_id", "post_postscore"."post_id", "post_postscore"."upvotes", "post_postscore"."downvotes" FROM "post_postscore" WHERE "post_postscore"."post_id" = 2; args=(2,)
  • 这段代码就是这样做的;您将所有内容都记录到控制台和“log.django”文件中,您应该在其中看到所有回溯。

标签: python django logging


【解决方案1】:

我也在使用 django 日志记录,并将该日志存储在这样的数据库中。

settings.py

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s %(user)s'
        },
        'simple': {
            'format': '%(levelname)s %(asctime)s %(message)s'
        },
    },
    'handlers': {
        'db_log': {
            'level': 'DEBUG',
            'class': 'Log.db_log_handler.DatabaseLogHandler',
        },
    },
    'loggers': {
        'db': {
            'handlers': ['db_log'],
            'level': 'DEBUG',
        }
    }
}

这是我的Log.db_log_handler.py

import logging
import traceback
import platform

class DatabaseLogHandler(logging.Handler):
    def emit(self, record):
        trace = None
        from Log.models import SystemLog
        if record.exc_info:
            trace = traceback.format_exc()

        SystemLog.objects.create(
            logger_name = record.name,
            level = record.levelno,
            msg = record.getMessage(),
            thread=record.threadName,
            module=record.module,
            process=record.processName,
            trace= trace,            
            pathname = record.pathname,
            system = platform.system(),
            machine = platform.machine(),
            dist = platform.dist(),
            line_no = record.lineno,
            func_name = record.funcName
        )


class RequestUserFilter(logging.Filter):
    def filter(self, record):
        record.user = record.request.user
        return True

SystemLog models.py

LOG_LEVELS = (
    (logging.NOTSET, _('NotSet')),
    (logging.DEBUG, _('Debug')), #10
    (logging.INFO, _('Info')), #20
    (logging.WARNING, _('Warning')), #30    
    (logging.ERROR, _('Error')), #40
    (logging.FATAL, _('Fatal')), #50
)
class SystemLog(models.Model):
    logger_name = models.CharField(max_length=100)
    level = models.PositiveSmallIntegerField(choices=LOG_LEVELS, default=logging.ERROR, db_index=True)
    msg = models.TextField()
    trace = models.TextField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    process = models.TextField(blank=True, null=True)
    thread = models.TextField(blank=True, null=True)
    module = models.TextField(blank=True, null=True)
    pathname = models.TextField(blank=True, null=True)
    system = models.TextField(blank=True, null=True)
    machine = models.TextField(blank=True, null=True)
    dist = models.TextField(blank=True, null=True)
    line_no = models.IntegerField(blank=True, null=True)
    func_name = models.TextField(blank=True, null=True)


    def __str__(self):
        return self.msg

我希望它会有所帮助。

【讨论】:

    猜你喜欢
    • 2011-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多