程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Encapsulate Pythons logging module and import it directly for use

編輯:Python

The following code implements the logging The logging module is repackaged so that logging can be realized through simple parameter transmission 、 But the file size limit and the number of files stored . And will automatically format the file timestamp

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 File handle settings 
# 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 File size and time settings 
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

Use of document module

import myLogger
logger = myLogger.getInstance("log-warn")
logger.warn("hello wan log")

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved