組件名稱 | 對應類名 | 功能描述 |
---|---|---|
日誌器 | Logger | 提供了應用程序可一直使用的接口 |
處理器 | Handler | 將logger建立的日誌記錄發送到合適的目的輸出 |
過濾器 | Filter | 提供了更細粒度的控制工具來決定輸出哪條日誌記錄,丟棄哪條日誌記錄 |
格式器 | Formatter | 決定日誌記錄的最終輸出格式 |
import logging
from logging import handlers
logger = logging.getLogger() #先實例化一個logger對象,先建立一個辦公室app
logger.setLevel(logging.DEBUG) #設置日誌的級別的人
cl = logging.StreamHandler() #負責往控制檯輸出的人
bl = handlers.TimedRotatingFileHandler(filename='a.log',when='S',interval=1,backupCount=5,encoding='utf-8')
# when,按什麼單位
#S 秒
# M 分
# H 小時、
# D 天、
# W 每星期(interval==0時表明星期一)工具
# midnight - roll over at midnight spa
# W{0-6} - roll over on a certain day; 0 - Mondaydebug
fmt = logging.Formatter('%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s')
cl.setFormatter(fmt) #設置控制檯輸出的日誌格式
bl.setFormatter(fmt) #設置文件裏面寫入的日誌格式
logger.addHandler(cl) #把已經調教好的人放到辦公室裏
logger.addHandler(bl) ##把已經調教好的人放到辦公室裏
#指定日誌的格式
logger.debug('我是debug。。。')
logger.warning('我是waring。。。')日誌
日誌格式code
1 %(name)s Name of the logger (logging channel) 2 %(levelno)s Numeric logging level for the message (DEBUG, INFO, 3 WARNING, ERROR, CRITICAL) 4 %(levelname)s Text logging level for the message ("DEBUG", "INFO", 5 "WARNING", "ERROR", "CRITICAL") 6 %(pathname)s Full pathname of the source file where the logging 7 call was issued (if available) 8 %(filename)s Filename portion of pathname 9 %(module)s Module (name portion of filename) 10 %(lineno)d Source line number where the logging call was issued 11 (if available) 12 %(funcName)s Function name 13 %(created)f Time when the LogRecord was created (time.time() 14 return value) 15 %(asctime)s Textual time when the LogRecord was created 16 %(msecs)d Millisecond portion of the creation time 17 %(relativeCreated)d Time in milliseconds when the LogRecord was created, 18 relative to the time the logging module was loaded 19 (typically at application startup time) 20 %(thread)d Thread ID (if available) 21 %(threadName)s Thread name (if available) 22 %(process)d Process ID (if available) 23 %(message)s The result of record.getMessage(), computed just as 24 the record is emitted