Django中的日志系统章

Python日志系统

Django使用logging模块记录日志。Python的日志系统分为4块。分别是:loggershandlersfiltersformatters

  • loggers
  • handlers
  • filtersDjango
  • formatters

logger

logger模块是日志系统的入口,首先处理进入日志系统的消息。每个logger实例都有一个名字,不同名字的loggger实例按不同策略处理日志消息。

import logging

LOG = logging.getLogger('Django')

LOG.debug("This is debug info.")

每个logger实例都有一个默认等级,只有当消息的等级等于或超过默认等级,才会被处理。否则,消息就被丢弃。

  • DEBUG
  • INFO
  • WARNING
  • ERROR
  • CRITICAL

当logger模块接收了消息以后,会传给handler模块。

handler

handler模块决定日志保存在哪里,是在终端打印、保存在本地文件、还是保存在日志服务器。
handler实例也有默认等级,只有当消息的等级等于或超过默认等级,才会被处理。否则,消息就被丢弃。
一个logger实例可以有多个handler实例,每个handler实例处理不同等级的消息。

filter

默认情况下,logger模块只检查消息等级。在消息从logger模块传输到handler模块的过程中,filter模块可以对消息进行高级筛选。
比如,filter实例可以筛选从指定源发出的ERROR消息。
filter实例也可以改变消息的等级,比如,在某些条件下,把ERROR消息降级成WARNING。
filter实例可以与logger实例或handler实例关联,也可以把多个filter实例做成筛选链,做精确筛选。

formatter

formatter模块指定日志的格式。

各个模块关系如下

loggers -> filters -> handlers -> formatters -> [stdio, file, network]

在django中设置日志

在setting.py文件中,配置以下两个变量。

LOGGING_CONFIG = 'logging.config.dictConfig'
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'simple': {
            'format': '[%(process)d] [%(thread)d] %(asctime)s.%(msecs)-3d %(levelname)s %(message)s',
            'datefmt': '%H:%M:%S'
        },
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': '/tmp/webconsole.log',
            'formatter': 'simple',
        },
    },
    'loggers': {
        'Django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

在需要记录LOG的文件中,通过Loggers记录日志。名字为setting.py文件中设置的Logger名字。

import logging
LOG = logging.getLogger('Django')
LOG.warning();

日志格式

参考python日志格式

Attribute name Format Description
args You shouldn’t need to format this yourself. The tuple of arguments merged into msg to produce message, or a dict whose values are used for the merge (when there is only one argument, and it is a dictionary).
asctime %(asctime)s Human-readable time when the LogRecord was created. By default this is of the form ‘2003-07-08 16:49:45,896’ (the numbers after the comma are millisecond portion of the time).
created %(created)f Time when the LogRecord was created (as returned by time.time()).
exc_info You shouldn’t need to format this yourself. Exception tuple (à la sys.exc_info) or, if no exception has occurred, None.
filename %(filename)s Filename portion of pathname.
funcName %(funcName)s Name of function containing the logging call.
levelname %(levelname)s Text logging level for the message ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL').
levelno %(levelno)s Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL).
lineno %(lineno)d Source line number where the logging call was issued (if available).
module %(module)s Module (name portion of filename).
msecs %(msecs)d Millisecond portion of the time when the LogRecord was created.
message %(message)s The logged message, computed as msg % args. This is set when Formatter.format() is invoked.
msg You shouldn’t need to format this yourself. The format string passed in the original logging call. Merged with args to produce message, or an arbitrary object (see Using arbitrary objects as messages).
name %(name)s Name of the logger used to log the call.
pathname %(pathname)s Full pathname of the source file where the logging call was issued (if available).
process %(process)d Process ID (if available).
processName %(processName)s Process name (if available).
relativeCreated %(relativeCreated)d Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.
stack_info You shouldn’t need to format this yourself. Stack frame information (where available) from the bottom of the stack in the current thread, up to and including the stack frame of the logging call which resulted in the creation of this record.
thread %(thread)d Thread ID (if available).
threadName %(threadName)s Thread name (if available).
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本文首发于Gevin的博客 原文链接:Python 日志功能详解 未经 Gevin 授权,禁止转载 软件开发中通过...
    Gevin阅读 4,997评论 1 24
  • 本文章是我大概三年前,在上家单位使用 Python 工作时结合官方文档做的整理。现在 Python 官方文档听说已...
    好吃的野菜阅读 217,465评论 14 232
  • Logging框架主要作用是Python里面处理日志 一.logging模块的组成 loggers :提供应用程...
    YichenWong阅读 1,582评论 1 0
  • 本文翻译自logging howto 基础教程 日志是跟踪软件运行时发生事件的一种手段。Python开发者在代码中...
    大蟒传奇阅读 4,263评论 0 17
  • 自二胎开放以来,产科门诊人流量越居第一,产科也床满为患,连带产后恢复中心也看准商机大肆兴起。 转眼间,我也成为宝妈...
    安然梦阅读 539评论 0 0