1. 程式人生 > 程式設計 >python 如何對logging日誌封裝

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 logging
import logging.handlers
import os
import 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):
pass
else:
os.mkdir(logs_dir)
# 修改log儲存位置
timestamp=time.strftime("%Y-%m-%d",time.localtime())
logfilename='%s.txt' % timestamp
logfilepath=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 : Description
import logging
logger = 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.控制檯輸出

python 如何對logging日誌封裝

2.日誌檔案展示

建立目錄

python 如何對logging日誌封裝

日誌檔案的寫入

python 如何對logging日誌封裝

以上就是python 如何對logging日誌封裝的詳細內容,更多關於python logging日誌封裝的資料請關注我們其它相關文章!