Python logging日志库空间不足问题解决
作者:冷冰若水 时间:2021-08-24 15:59:17
项目中使用的日志库是使用python官方库logging封装的,但是居然一直么有设置日志自动滚动,经常会受到告警说哪台机器磁盘空间又满,清理一下,于是研究一下,解决这个问题。
参考:https://docs.python.org/2/library/logging.handlers.html
TimedRotatingFileHandler有三个参数很关键
when、interval、backupCount
when指定滚动依据的单位,可选的有天、小时、分钟、秒等;interval指定间隔多少个when之后滚动日志;而backupCount指定最多保留多少个日志。
所以结合这三个参数就可以实现我要的目的了,让日志随时间滚动,同时限制总的日志个数。
demo:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import time
import logging
import logging.handlers
if __name__ == '__main__':
if len(sys.argv) != 2:
print('Usage:%s log_name' % (sys.argv[0]))
sys.exit(0)
log_dir = './log'
log_name = sys.argv[1]
logger = logging.getLogger(log_name)
logger.setLevel(logging.DEBUG)
# init handler
formatter = logging.Formatter('%(message)s')
file_time_handler = logging.handlers.TimedRotatingFileHandler(
os.path.join(log_dir, log_name), "M", 1, 5)
file_time_handler.setFormatter(formatter)
file_time_handler.setLevel(logging.DEBUG)
logger.addHandler(file_time_handler)
while True:
time.sleep(1)
logger.info('Hello world %s' % (time.strftime("%Y/%M/%d-%H:%m:%S")))
结果:
可以看到最上面的一条记录记录就被滚掉了。
666
来源:https://www.cnblogs.com/lit10050528/p/10799381.html
标签:Python,logging,日志
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
基于Python制作flappybird游戏的详细步骤
2023-07-29 10:08:29
![](https://img.aspxhome.com/file/2023/2/60292_0s.jpg)
另类读写:ACCESS中Field对象的标题属性
2008-11-28 16:47:00
找不到类型或命名空间名称“Server”(是否缺少 using 指令或程序集引用?)
2023-07-07 21:50:15
懒人必备Python代码之自动发送邮件
2022-08-31 20:17:41
![](https://img.aspxhome.com/file/2023/3/88913_0s.png)
Django 用户登陆访问限制实例 @login_required
2021-05-26 07:31:22
举例讲解Python面向对象编程中类的继承
2022-02-09 02:59:14
解决bootstrap导航栏navbar在IE8上存在缺陷的方法
2023-09-03 10:55:07
![](https://img.aspxhome.com/file/2023/0/56080_0s.gif)
Python Django框架设计模式详解
2021-01-16 12:52:40
![](https://img.aspxhome.com/file/2023/4/72864_0s.jpg)
Python实现壁纸下载与轮换
2022-07-01 19:19:19
asp使用模板生成静态页面方法详解
2007-09-24 12:29:00
SQL Server数据在不同数据库中的应用
2008-12-24 15:34:00
Python imgaug库安装与使用教程(图片加模糊光雨雪雾等特效)
2021-06-23 10:07:16
![](https://img.aspxhome.com/file/2023/5/93695_0s.png)
Python3网络爬虫之使用User Agent和代理IP隐藏身份
2022-03-05 13:13:07
![](https://img.aspxhome.com/file/2023/5/79625_0s.png)
9个Web设计中常见的可用性错误[译]
2009-03-11 20:25:00
![](https://img.aspxhome.com/file/UploadPic/20093/11/01-10s.jpg)
由浅入深讲解python中的yield与generator
2022-08-14 06:26:11
python判断所输入的任意一个正整数是否为素数的两种方法
2022-02-26 12:43:14
一段ASP的HTTP_REFERER判断代码
2011-03-25 10:41:00
在HTML中,常见的URL有多种表示方式:
2009-07-28 12:18:00
Python操作MongoDB数据库PyMongo库使用方法
2023-03-16 00:13:14
Python中GIL的使用详解
2022-02-08 13:36:30