平时创建的项目或者脚本,运行时间久了难免会产生一堆日志或者日志文件很大。不记录日志怕出问题无从排查,记录日志又担心浪费空间,因此项目开发的时候就应该重视日志管理。
下面介绍下使用python logging handlers模块管理日志的过程。
python 自带模块,不用安装
logging.handlers.RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)
import time
import logging
import logging.handlers
# logging初始化工作
logging.basicConfig()
logger = logging.getLogger('script')
logger.setLevel(logging.INFO)
# 添加TimedRotatingFileHandler
timefilehandler = logging.handlers.TimedRotatingFileHandler(
"test.log", #日志路径
when='S', # S秒 M分 H时 D天 W周 按时间切割 测试选用S
interval=1, # 多少天切割一次
backupCount=7 # 保留多少天
)
# 设置后缀名称,跟strftime的格式一样
timefilehandler.suffix = "%Y-%m-%d_%H-%M-%S.log"
formatter = logging.Formatter('%(asctime)s|%(name)s | %(levelname)s | %(message)s')
timefilehandler.setFormatter(formatter)
logger.addHandler(timefilehandler)
for i in range(10):
logger.info("log test")
time.sleep(1)
logging.handlers.TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False)
import time
import logging
import logging.handlers
# logging初始化工作
logging.basicConfig()
logger = logging.getLogger('script')
logger.setLevel(logging.INFO)
# 添加TimedRotatingFileHandler
timefilehandler = logging.handlers.TimedRotatingFileHandler(
"test.log", #日志路径
maxBytes=50000, #文件到达的大小
backupCount=7 #保留多少份
)
# 设置切割后文件名称,跟strftime的格式一样
timefilehandler.suffix = "%Y-%m-%d_%H-%M-%S.log"
formatter = logging.Formatter('%(asctime)s|%(name)s | %(levelname)s | %(message)s')
timefilehandler.setFormatter(formatter)
logger.addHandler(timefilehandler)
for i in range(10):
logger.info("log test")
time.sleep(1)
参数配置
You can use the when to specify the type of interval. The list of possible values is below. Note that they are not case sensitive.
Value |
Type of interval |
If/how atTime is used |
---|---|---|
|
Seconds |
Ignored |
|
Minutes |
Ignored |
|
Hours |
Ignored |
|
Days |
Ignored |
|
Weekday (0=Monday) |
Used to compute initial rollover time |
|
Roll over at midnight, if atTime not specified, else at time atTime |
Used to compute initial rollover time |
https://docs.python.org/3.6/library/logging.handlers.html