Django如何记录工作

时间:2018-02-14 09:16:09

标签: python django logging

我想实现对我的实时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代码中的错误。

1 个答案:

答案 0 :(得分:0)

我也使用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

我希望它会有所帮助。