python脚本记日志

        1、使用RotatingFileHandler,可以实现日志按大小回滚(设置,最多备份几个日志文件,每个日志文件最大值):

import logging

from logging.handlers import RotatingFileHandler # 按文件大小回滚handler

def main():
    logger = logging.getLogger(__name__)
    logger.setLevel(level=logging.INFO)
    # 定义一个RotatingFileHandler,最多备份3个日志文件,每个日志文件最大1K
    rHandler = RotatingFileHandler("log.txt", maxBytes=1 * 1024, backupCount=3)
    rHandler.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    rHandler.setFormatter(formatter)
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    console.setFormatter(formatter)
    logger.addHandler(rHandler)
    logger.addHandler(console)

参考:

https://www.cnblogs.com/lidabo/p/17078766.html

你可能感兴趣的:(python)