python 如何對(duì)logging日志封裝
作者:做夢(mèng)的人(小姐姐)出處:https://www.cnblogs.com/chongyou/
因?yàn)樽罱谧銎脚_(tái),發(fā)現(xiàn)有同事,使用django封裝了日志模塊,看樣子很簡(jiǎn)單,準(zhǔn)備自己?jiǎn)为?dú)做了一個(gè)日志封裝模板,對(duì)于python不熟練的我,封裝部分參考了多個(gè)博主的內(nèi)容,形成自己的日志模塊,內(nèi)容如下:
封裝部分
創(chuàng)建一個(gè)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('')# 設(shè)置輸出的等級(jí)LEVELS = {’NOSET’: logging.NOTSET, ’DEBUG’: logging.DEBUG, ’INFO’: logging.INFO, ’WARNING’: logging.WARNING, ’ERROR’: logging.ERROR, ’CRITICAL’: logging.CRITICAL}# 創(chuàng)建文件目錄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)# 設(shè)置輸出格式formatter = logging.Formatter(’[%(asctime)s] [%(levelname)s] %(message)s’, ’%Y-%m-%d %H:%M:%S’)rotatingFileHandler.setFormatter(formatter)# 控制臺(tái)句柄console = logging.StreamHandler()console.setLevel(logging.NOTSET)console.setFormatter(formatter)# 添加內(nèi)容到日志句柄中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.調(diào)用模塊
創(chuàng)建另外一個(gè)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')
結(jié)果展示:
1.控制臺(tái)輸出

2.日志文件展示
創(chuàng)建目錄

日志文件的寫入

以上就是python 如何對(duì)logging日志封裝的詳細(xì)內(nèi)容,更多關(guān)于python logging日志封裝的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. IntelliJ IDEA安裝插件的方法步驟2. php模擬實(shí)現(xiàn)斗地主發(fā)牌3. 理解PHP5中static和const關(guān)鍵字4. spring acegi security 1.0.0 發(fā)布5. vue 使用localstorage實(shí)現(xiàn)面包屑的操作6. MyBatis中的JdbcType映射使用詳解7. Vuex localStorage的具體使用8. Python random庫(kù)使用方法及異常處理方案9. .Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟10. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)

網(wǎng)公網(wǎng)安備