python日誌模塊
阿新 • • 發佈:2018-09-27
filepath 每天 一個 ini level 技術分享 ror logfile hand
python的日誌模塊使用logging,如果想要輸出符合自己的預期,需要重新定義,廢話不多說,直接貼代碼。
# encoding: utf -8 from logging.handlers import TimedRotatingFileHandler import logging import os import datetime #調用方法log.debug(‘logname.log‘,‘輸出內容‘) path=os.path.abspath(‘‘) class log(): def __init__(self): if os.path.isdir(‘%s\\log‘%path): #創建log文件夾 pass else: os.mkdir(‘%s\\log‘%path) def debug(self,logname,kwarg): logFilePath = ‘%s\\log\\%s‘%(path,logname) logger = logging.getLogger("yourName") logger.setLevel(logging.DEBUG) handler = TimedRotatingFileHandler(logFilePath, when="midnight", interval=1, backupCount=20) formatter = logging.Formatter(‘%(asctime)s %(levelname)s %(message)s‘) handler.setFormatter(formatter) logger.addHandler(handler) logger.debug(‘%s‘%(kwarg)) logger.removeHandler(handler) def error(self,logname,kwarg): logFilePath = ‘%s\\log\\%s‘%(path,logname) logger = logging.getLogger("yourName") logger.setLevel(logging.ERROR) handler = TimedRotatingFileHandler(logFilePath, when="midnight", interval=1, backupCount=20) formatter = logging.Formatter(‘%(asctime)s %(levelname)s %(message)s‘) handler.setFormatter(formatter) logger.addHandler(handler) logger.error(‘%s‘%(kwarg)) logger.removeHandler(handler)
handler = TimedRotatingFileHandler(logFilePath, when="midnight", interval=1, backupCount=20) 定義寫入日誌的策略:
1.每天一個日誌文件。
2.超過20個,刪除最早生成的日誌。
formatter = logging.Formatter(‘%(asctime)s %(levelname)s %(message)s‘) 定義日誌輸出的格式
輸出日誌:
log().debug(‘test.log‘,‘Hello World...‘)
python日誌模塊