Python中logging日志记录到文件及自动分割的操作代码
作者:行星带 时间:2022-09-08 12:33:33
日志作为项目开发和运行中必备组件,python提供了内置的logging模块来完成这个工作;借助 TimedRotatingFileHandler
可以按日期自动分割日志,自动保留日志文件数量等,下面是对日志的一个简单封装和测试。
import logging
import os
from logging import handlers
class Logger(object):
# 日志级别关系映射
level_relations = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL
}
def __init__(self,
filename,
level='info',
when='D',
back_count=3,
fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):
f_dir, f_name = os.path.split(filename)
os.makedirs(f_dir, exist_ok=True) # 当前目录新建log文件夹
self.logger = logging.getLogger(filename)
format_str = logging.Formatter(fmt) # 设置日志格式
self.logger.setLevel(self.level_relations.get(level)) # 设置日志级别
sh = logging.StreamHandler() # 往屏幕上输出
sh.setFormatter(format_str) # 设置屏幕上显示的格式
th = handlers.TimedRotatingFileHandler(filename=filename, when=when, backupCount=back_count,
encoding='utf-8') # 往文件里写入指定间隔时间自动生成文件的Handler
# 实例化TimedRotatingFileHandler
# interval是时间间隔,backupCount是备份文件的个数,如果超过这个个数,就会自动删除,when是间隔的时间单位,单位有以下几种:
# S 秒
# M 分
# H 小时
# D 天
# 'W0'-'W6' 每星期(interval=0时代表星期一:W0)
# midnight 每天凌晨
th.setFormatter(format_str) # 设置文件里写入的格式
self.logger.addHandler(sh) # 把对象加到logger里
self.logger.addHandler(th)
# 测试
if __name__ == '__main__':
logger = Logger('./logs/2020/app.log', 'debug', 'S', 5).logger
logger.debug('debug')
logger.info('info')
logger.warning('警告')
logger.error('报错')
logger.critical('严重')
# 单独记录error
err_logger = Logger('./logs/2020/error.log', 'error', 'S', 3).logger
err_logger.error('错误 error')
为了测试方便,我们将时间间隔设为秒(按秒自动命名分割文件),多运行几次后,会按照配置文件数量将多余的日志文件自动删除,保留如上图中的日志文件。
原文链接:https://beltxman.com/3195.html,若无特殊说明本站内容为行星带原创,未经同意禁止转载!
来源:https://beltxman.com/3195.html
标签:python,logging,日志记录,自动分割
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
提高asp程序访问速度的方法
2008-10-23 16:37:00
Python查询IP地址归属完整代码
2022-10-18 16:39:07
ASP MSSQL存储过程的实现小例
2011-04-06 11:02:00
解析:校对确定 较为复杂的一些特殊情况
2008-12-17 16:54:00
Python利用Redis计算经纬度距离案例
2021-03-05 04:51:35
Python使用monkey.patch_all()解决协程阻塞问题
2021-05-11 17:27:19
Python接口自动化之cookie、session应用详解
2023-02-02 11:10:35
![](https://img.aspxhome.com/file/2023/4/105764_0s.jpg)
phpstorm断点调试方法图文详解
2023-05-30 01:06:40
![](https://img.aspxhome.com/file/2023/9/55259_0s.jpg)
SQL中JOIN和UNION区别、用法及示例介绍
2012-08-21 10:47:22
关于H1的位置
2008-04-30 12:20:00
python 实现dict转json并保存文件
2022-04-17 10:24:17
20行Python代码实现视频字符化功能
2023-01-08 21:17:02
![](https://img.aspxhome.com/file/2023/4/103674_0s.gif)
Navicat for MySQL 与 MySQL-Front比较
2009-02-12 17:33:00
![](https://img.aspxhome.com/file/UploadPic/20092/2009218192314499.jpg)
python定时任务timeloop库用法实例详解
2023-12-21 19:34:53
![](https://img.aspxhome.com/file/2023/9/99689_0s.png)
Python模块结构与布局操作方法实例分析
2021-11-26 10:49:31
pygame外星人入侵小游戏超详细开发流程
2021-06-15 05:15:47
![](https://img.aspxhome.com/file/2023/9/75909_0s.png)
Micropython固件使用Pico刷固件并配置VsCode开发环境的方法
2022-09-21 16:22:14
![](https://img.aspxhome.com/file/2023/2/103222_0s.jpg)
关于Tensorflow中的tf.train.batch函数的使用
2023-11-04 19:49:54
python对站点数据做EOF且做插值绘制填色图
2023-03-05 03:30:56
![](https://img.aspxhome.com/file/2023/8/93488_0s.png)
python读取并绘制nc数据的保姆级教程
2023-11-23 02:19:24
![](https://img.aspxhome.com/file/2023/9/78559_0s.png)