Python日志系統(tǒng)
Django使用logging模塊記錄日志。Python的日志系統(tǒng)分為4塊。分別是:loggers,handlers,filters和formatters。
- 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). |