python 如何對logging日志封裝
作者:做夢的人(小姐姐)出處:https://www.cnblogs.com/chongyou/
因為最近在做平臺,發現有同事,使用django封裝了日志模塊,看樣子很簡單,準備自己單獨做了一個日志封裝模板,對于python不熟練的我,封裝部分參考了多個博主的內容,形成自己的日志模塊,內容如下:
封裝部分
創建一個logutil2的py文件
#!/usr/bin/env python# -*- coding: utf-8 -*-# @Author: zhangjun# @Date : 2018/7/26 9:20# @Desc : Description import loggingimport logging.handlersimport osimport time class logs(object): def __init__(self):self.logger = logging.getLogger('')# 設置輸出的等級LEVELS = {’NOSET’: logging.NOTSET, ’DEBUG’: logging.DEBUG, ’INFO’: logging.INFO, ’WARNING’: logging.WARNING, ’ERROR’: logging.ERROR, ’CRITICAL’: logging.CRITICAL}# 創建文件目錄logs_dir='logs2'if os.path.exists(logs_dir) and os.path.isdir(logs_dir): passelse: os.mkdir(logs_dir)# 修改log保存位置timestamp=time.strftime('%Y-%m-%d',time.localtime())logfilename=’%s.txt’ % timestamplogfilepath=os.path.join(logs_dir,logfilename)rotatingFileHandler = logging.handlers.RotatingFileHandler(filename =logfilepath, maxBytes = 1024 * 1024 * 50, backupCount = 5)# 設置輸出格式formatter = logging.Formatter(’[%(asctime)s] [%(levelname)s] %(message)s’, ’%Y-%m-%d %H:%M:%S’)rotatingFileHandler.setFormatter(formatter)# 控制臺句柄console = logging.StreamHandler()console.setLevel(logging.NOTSET)console.setFormatter(formatter)# 添加內容到日志句柄中self.logger.addHandler(rotatingFileHandler)self.logger.addHandler(console)self.logger.setLevel(logging.NOTSET) def info(self, message):self.logger.info(message) def debug(self, message):self.logger.debug(message) def warning(self, message):self.logger.warning(message) def error(self, message):self.logger.error(message)
2.調用模塊
創建另外一個py文件
#!/usr/bin/env python# -*- coding: utf-8 -*-# @Author: zhangjun# @Date : 2018/7/26 9:21# @Desc : Descriptionimport logginglogger = logging.getLogger(__name__)import logutil2 if __name__ == ’__main__’: logger=logutil2.logs() logger.info('this is info') logger.debug('this is debug') logger.error('this is error') logger.warning('this is warning')
結果展示:
1.控制臺輸出
2.日志文件展示
創建目錄
日志文件的寫入
以上就是python 如何對logging日志封裝的詳細內容,更多關于python logging日志封裝的資料請關注好吧啦網其它相關文章!
相關文章:
