# -*- coding: utf-8 -*-
import os
import logging
from logging import handlers
def Logger(filename):
fmt = '%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'
format_str = logging.Formatter(fmt) # 设置日志记录格式
log_path = "log_path" # 日志文件记录路径
log_file = os.path.join(log_path, filename) + ".log"
logger = logging.getLogger()
# 避免日志重复
if logger.hasHandlers():
logger.handlers = []
logger.setLevel(logging.DEBUG) # 设置日志记录级别
# 按照时间自动分割日志文件
# th = handlers.TimedRotatingFileHandler(filename=log_file, when="midnight", backupCount=5)
# backupCount是备份文件的个数,如果超过这个个数,就会自动删除,
# when是间隔的时间单位,单位有以下几种:
# S 秒
# M 分
# H 小时、
# D 天、
# W 每星期(interval==0时代表星期一)
# midnight 每天凌晨
# 以日志文件的大小(maxBytes)进行划分,当日志文件达到记录的上限时新建一个日志文件,备份的日志数量(backupCount)如果超过这个个数,就会自动删除
th = handlers.RotatingFileHandler(filename=log_file, maxBytes=50000000, backupCount=10)
th.setFormatter(format_str) # 设置文件里写入的格式
sh = logging.StreamHandler() # 往屏幕上输出
sh.setFormatter(format_str) # 设置屏幕上显示的格式
logger.addHandler(sh) # 把对象加到logger里
logger.addHandler(th)
return logger
if __name__ == '__main__':
log = Logger('dd')
log.debug('debug')
log.info('info')
log.warning('warning')
log.error('错误')
log.critical('critical')
python,logging-日志记录
于 2021-11-18 14:21:19 首次发布