Python中logging日志记录到文件及自动分割的操作代码

2020-10-09 0 572

日志作为项目开发和运行中必备组件,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\')

Python中logging日志记录到文件及自动分割的操作代码

为了测试方便,我们将时间间隔设为秒(按秒自动命名分割文件),多运行几次后,会按照配置文件数量将多余的日志文件自动删除,保留如上图中的日志文件。

原文链接:https://beltxman.com/3195.html,若无特殊说明本站内容为行星带原创,未经同意禁止转载!

总结

到此这篇关于Pythonlogging日志记录到文件及自动分割的文章就介绍到这了,更多相关python logging日志记录内容请搜索自学编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持自学编程网!

遇见资源网 Python Python中logging日志记录到文件及自动分割的操作代码 http://www.ox520.com/26693.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务