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