python日志logging记录,过期自动删除

python日志logging记录,过期自动删除

python使用logging库可以简单明了的格式化输出log到终端或文件。
when 是一个字符串的定义如下:
“S”: Seconds
“M”: Minutes
“H”: Hours
“D”: Days
“W”: Week day (0=Monday)
“midnight”: Roll over at midnight
使用下面方法把log输出到终端:

import logging

LOG_FORMAT = "[%(asctime)s][%(levelname)s]: %(message)s"
level = logging.INFO
logging.basicConfig(level=level, format=LOG_FORMAT)

log.info('test')
log.warning('test')
log.error('test')

通过TimedRotatingFileHandler可以把输出重定向到文件,它会对比文件最后修改时间和当前时间,如果比设置的时候大,则会把当前文件加时间后缀备份,然后,新建一个进行Log。

import logging
from logging.handlers import TimedRotatingFileHandler
import time

def log_config():
    LOG_FORMAT = "[%(asctime)s][%(levelname)s]: %(message)s"
    fname=time.strftime("news_%Y%m%d.log", time.localtime())
    level = logging.INFO
    logging.basicConfig(level=level, format=LOG_FORMAT)
    
    #创建TimedRotatingFileHandler对象,每天生成一个文件
    log_file_handler = TimedRotatingFileHandler(filename='test.log', when="D", interval=1, backupCount=3)
    # 设置日志打印格式
    formatter = logging.Formatter(LOG_FORMAT)
    log_file_handler.setFormatter(formatter)
    logging.getLogger('').addHandler(log_file_handler)

def main():
	try:
		10/0
	except:
		logging.error('divider error.', exc_info=True)

如果对log文件的大小有要求,则可以使用RotatingFileHander对log的文件大小进行限制。

import logging
from logging.handlers import RotatingFileHandler

def log_config():
    LOG_FORMAT = "[%(asctime)s][%(levelname)s]: %(message)s"
    fname=time.strftime("news_%Y%m%d.log", time.localtime())
    level = logging.INFO
    logging.basicConfig(level=level, format=LOG_FORMAT)
    
    #创建RotatingFileHandler对象,满1MB为一个文件,共备份3个文件
    log_file_handler = RotatingFileHandler(filename='test.log', maxBytes=1024*1024, backupCount=3)
    # 设置日志打印格式
    formatter = logging.Formatter(LOG_FORMAT)
    log_file_handler.setFormatter(formatter)
    logging.getLogger('').addHandler(log_file_handler)
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值