PYTHON 除錯(DEBUG)專用LOG函數 [顯示檔案/行數/函數 等相關位置]
PYTHON 除錯(DEBUG)專用LOG函數 [顯示檔案/行數/函數 等相關位置]
資料來源: https://www.cnblogs.com/java20130722/p/3206780.html
Code
logger.py 文件
#!/usr/bin/python
# coding: utf-8
import logging
import logging.handlers
from logging import *
from datetime import *
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
rht = logging.handlers.TimedRotatingFileHandler("reindex_out.log", 'D')
fmt = logging.Formatter("%(asctime)s %(pathname)s %(filename)s %(funcName)s %(lineno)s \
%(levelname)s - %(message)s", "%Y-%m-%d %H:%M:%S")
rht.setFormatter(fmt)
logger.addHandler(rht)
debug = logger.debug
info = logger.info
warning = logger.warn
error = logger.error
critical = logger.critical
测试脚本
#!/usr/bin/env python
# coding utf-8
from logger import *
import sys
import os
info("log from logger info")
debug("this is from test.py")
print 'current dir is ' + os.getcwd()
format: 指定輸出的格式和內容,format可以輸出很多有用信息,如上例所示:
%(levelno)s: 打印日誌級別的數值 %(levelname)s: 打印日誌級別名稱 %(pathname)s: 打印當前執行程序的路徑,其實就是sys.argv[0] %(filename)s: 打印當前執行程序名 %(funcName)s: 打印日誌的當前函數 %(lineno)d: 打印日誌的當前行號 %(asctime)s: 打印日誌的時間 %(thread)d: 打印線程ID %(threadName)s: 打印線程名稱 %(process)d: 打印進程ID %(message)s: 打印日誌信息
datefmt: 指定時間格式,同time.strftime()
level: 設置日誌級別,默認為logging.WARNING
| 級別 | 對應的值 |
|---|---|
| CRITICAL | 50 |
| ERROR | 40 |
| WARNING | 30 |
| INFO | 20 |
| DEBUG | 10 |
| NOTSET | 0 |
可以給日誌對象(Logger Instance)設置日誌級別,低於該級別的日誌消息將會被忽略,也可以給Hanlder設置日誌級別,對於低於該級別的日誌消息, Handler也會忽略。