python 日誌滾動 分檔案
阿新 • • 發佈:2018-11-16
import logging from logging.handlers import RotatingFileHandler import datetime import os def main(): logger = logging.getLogger(__name__) logger.setLevel(level=logging.INFO) # 定義一個RotatingFileHandler,最多備份3個日誌檔案,每個日誌檔案最大1K dir=str(datetime.date.today()) rHandler =RotatingFileHandler(dir+"log.txt", maxBytes=1 * 1024*30, backupCount=1024) rHandler.setLevel(logging.INFO) log_fmt = '%(asctime)s\tFile \"%(filename)s\",line %(lineno)s\t%(levelname)s: %(message)s' log_fmt ='%(asctime)s - %(name)s - %(levelname)s - %(message)s' formatter = logging.Formatter('%(asctime)s|%(name)-12s: %(levelname)-8s %(message)s') rHandler.setFormatter(log_fmt) rHandler.suffix = "%Y-%m-%d_%H-%M-%S.log" console = logging.StreamHandler() console.setLevel(logging.INFO) console.setFormatter(formatter) logger.addHandler(rHandler) logger.addHandler(console) for i in range(1024): logger.info("Start print log") logger.debug("Do something") logger.warning("Something maybe fail.") logger.info("Finish") if __name__ == '__main__': main()