效果:
有詳細的時間,日誌級別,文件,行數
同時輸出日誌到控制檯和指定文件,方便我們實時觀察,也方便掛機運行程序後回溯問題!
1在項目根目錄創建common文件夾,在common文件夾中創建log_utils.py
將下列內容拷貝到log_utils.py
'''
@Description:
@Author: jorian
@Date: 2020-06-25 00:03:18
'''
# coding: utf-8
import logging.handlers
import logging
import os
import sys
# 提供日誌功能
class logFactory():
def __init__(self,name):
# 初始化logger
self.log = logging.getLogger(name)
# 設置日誌文件保存路徑,common同級目錄中的logs文件夾
self.logpath = os.path.abspath(os.path.join(os.getcwd(), "logs"))
if not os.path.exists(self.logpath):
os.makedirs(self.logpath)
# 日誌文件的絕對路徑
self.logname = os.path.join(self.logpath, 'app.log')
#print(f"日誌保存路徑{logpath}")
# 設置日誌文件容量,轉換爲字節
self.logsize = 1024*1024*int(8) # 8M
# 設置日誌文件保存個數
self.lognum = int(3)
# 日誌格式,可以根據需要設置
self.fmt = logging.Formatter('[%(asctime)s]-[%(levelname)s]-[%(filename)s]-[line:%(lineno)d]: %(message)s', '%Y-%m-%d %H:%M:%S')
# 日誌輸出到文件,設置日誌名稱,大小,保存個數,編碼
self.handle1 = logging.handlers.RotatingFileHandler(self.logname, maxBytes=self.logsize, backupCount=self.lognum,encoding='utf-8')
self.handle1.setFormatter(self.fmt)
self.log.addHandler(self.handle1)
# 日誌輸出到屏幕,便於實時觀察
self.handle2 = logging.StreamHandler(stream=sys.stdout)
self.handle2.setFormatter(self.fmt)
self.log.addHandler(self.handle2)
# 設置日誌等級,這裏設置爲INFO,表示只有INFO級別及以上的會打印
self.log.setLevel(logging.INFO)
# 日誌接口,可根據需要定義更多接口
@classmethod
def info(cls, msg):
cls.log.info(msg)
return
@classmethod
def warning(cls, msg):
cls.log.warning(msg)
return
@classmethod
def error(cls, msg):
cls.log.error(msg)
return
@classmethod
def debug(cls, msg):
cls.log.debug(msg)
return
3.在需要使用的地方導入並初始化一個logger,然後輸出日誌,例子如下:
'''
@Description:
@Author: jorian
@Date: 2020-06-25 01:57:44
'''
from common.log_utils import logFactory
loggger = logFactory("test").log
def test():
loggger.info("test log info")
loggger.debug("test log debug")
loggger.error("test log error")
loggger.warning("test log warn")
if __name__ == '__main__':
test()
結果:
細心的同學不要誤會工具出錯,沒有debug是因爲debug等級太低,我們設置的日誌等級是info,所以只打info及以上的日誌