Django中的日志系統(tǒng)章

Python日志系統(tǒng)

Django使用logging模塊記錄日志。Python的日志系統(tǒng)分為4塊。分別是:loggers,handlers,filtersformatters。

  • loggers
  • handlers
  • filtersDjango
  • formatters

logger

logger模塊是日志系統(tǒng)的入口,首先處理進(jìn)入日志系統(tǒng)的消息。每個(gè)logger實(shí)例都有一個(gè)名字,不同名字的loggger實(shí)例按不同策略處理日志消息。

import logging

LOG = logging.getLogger('Django')

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

每個(gè)logger實(shí)例都有一個(gè)默認(rèn)等級(jí),只有當(dāng)消息的等級(jí)等于或超過默認(rèn)等級(jí),才會(huì)被處理。否則,消息就被丟棄。

  • DEBUG
  • INFO
  • WARNING
  • ERROR
  • CRITICAL

當(dāng)logger模塊接收了消息以后,會(huì)傳給handler模塊。

handler

handler模塊決定日志保存在哪里,是在終端打印、保存在本地文件、還是保存在日志服務(wù)器。
handler實(shí)例也有默認(rèn)等級(jí),只有當(dāng)消息的等級(jí)等于或超過默認(rèn)等級(jí),才會(huì)被處理。否則,消息就被丟棄。
一個(gè)logger實(shí)例可以有多個(gè)handler實(shí)例,每個(gè)handler實(shí)例處理不同等級(jí)的消息。

filter

默認(rèn)情況下,logger模塊只檢查消息等級(jí)。在消息從logger模塊傳輸?shù)絟andler模塊的過程中,filter模塊可以對(duì)消息進(jìn)行高級(jí)篩選。
比如,filter實(shí)例可以篩選從指定源發(fā)出的ERROR消息。
filter實(shí)例也可以改變消息的等級(jí),比如,在某些條件下,把ERROR消息降級(jí)成WARNING。
filter實(shí)例可以與logger實(shí)例或handler實(shí)例關(guān)聯(lián),也可以把多個(gè)filter實(shí)例做成篩選鏈,做精確篩選。

formatter

formatter模塊指定日志的格式。

各個(gè)模塊關(guān)系如下

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

在django中設(shè)置日志

在setting.py文件中,配置以下兩個(gè)變量。

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文件中設(shè)置的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).
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 本文首發(fā)于Gevin的博客 原文鏈接:Python 日志功能詳解 未經(jīng) Gevin 授權(quán),禁止轉(zhuǎn)載 軟件開發(fā)中通過...
    Gevin閱讀 5,128評(píng)論 1 24
  • 本文章是我大概三年前,在上家單位使用 Python 工作時(shí)結(jié)合官方文檔做的整理?,F(xiàn)在 Python 官方文檔聽說已...
    好吃的野菜閱讀 218,059評(píng)論 14 232
  • Logging框架主要作用是Python里面處理日志 一.logging模塊的組成 loggers :提供應(yīng)用程...
    YichenWong閱讀 1,618評(píng)論 1 0
  • 本文翻譯自logging howto 基礎(chǔ)教程 日志是跟蹤軟件運(yùn)行時(shí)發(fā)生事件的一種手段。Python開發(fā)者在代碼中...
    大蟒傳奇閱讀 4,359評(píng)論 0 17
  • 自二胎開放以來,產(chǎn)科門診人流量越居第一,產(chǎn)科也床滿為患,連帶產(chǎn)后恢復(fù)中心也看準(zhǔn)商機(jī)大肆興起。 轉(zhuǎn)眼間,我也成為寶媽...
    安然夢(mèng)閱讀 591評(píng)論 0 0

友情鏈接更多精彩內(nèi)容