Python好用的日志模块

一个比较好用的日志模块——————基于文件大小切分,只保留固定个数日志文件

import os
import logging
import logging.handlers


def init_logger(log_file):
    dir_path = os.path.dirname(log_file)
    try:
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)
    except Exception as e:
        pass
        
	# maxBytes:规定每个日志的最大容量
	# backupCount:规定日志格式,超过就会复写之前的日志文件
    handler = logging.handlers.RotatingFileHandler(log_file, maxBytes=64 * 1024 * 1024, backupCount=10)
    fmt = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s'
    formatter = logging.Formatter(fmt)
    handler.setFormatter(formatter)
    logger_instance = logging.getLogger('logs')
    logger_instance.addHandler(handler)
    logger_instance.setLevel(logging.DEBUG)
    return logger_instance


mylog = init_logger('/home/result.log')

猜你喜欢

转载自blog.csdn.net/qq_36355119/article/details/82801633
今日推荐