以下代碼實現的是將logging日志記錄模塊重新封裝為可通過簡單的傳參就能實現日志記錄、但文件大小限制以及文件存儲的個數。並會自動格式化文件時間戳
myLogger.py
from datetime import datetime
import logging
from logging.handlers import RotatingFileHandler
import os
def getInstance(fileName=None, fileSize=1024*1024, maxNums=10):
logger = logging.getLogger()
basePath = "logs/" + str(datetime.today().date())
if not os.path.exists(basePath):
os.makedirs(basePath)
fileName = f"{
basePath}/{
'log' if fileName is None else fileName}"
fileName += str(datetime.now().strftime("%H%M%S")) + ".log"
# log文件句柄設置
# logFileHandler = logging.FileHandler(fileName, mode="a")
fmt = '%(asctime)s %(filename)s:%(lineno)s %(levelname)s\t - %(message)s'
formatter = logging.Formatter(fmt)
# logFileHandler.setFormatter(formatter)
# log文件大小及時間設置
logFileRotateHandler = RotatingFileHandler(fileName, "a", fileSize, maxNums)
logFileRotateHandler.setFormatter(formatter)
logger.addHandler(logFileRotateHandler)
# logger.addHandler(logFileHandler)
logger.setLevel(logging.INFO)
logger.info("")
logger.info("******************************")
logger.info("init log: " + str(fileName))
return logger
文件模塊的使用
import myLogger
logger = myLogger.getInstance("log-warn")
logger.warn("hello wan log")