python - 如何避免 Python 中臃肿的日志文件?
问题描述
我的脚本每 5 秒执行一次。错误记录到文件中。这意味着,如果出现错误,日志文件每 5 秒就会因相同的错误而膨胀。
while True:
try:
i_might_fail() # As long as this line fails...
except Exception as ex:
logger.error(ex) # ... the log file gets bloated
time.sleep(5)
终止脚本是不可能的。它必须每 5 秒重试一次。
我正在寻找一个日志功能来忽略 x 分钟的相同异常:
logger.ignore_duplicates_for(10, 'minutes')
任何想法?提前致谢!
解决方案
这个特性可以这样实现:
import logging
import time
import datetime
logger = logging.getLogger(__file__)
TIMEDELTA = datetime.timedelta(seconds=5)
def error_without_duplicates(self, msg, *args, **kwargs):
if not hasattr(self, 'msg_cache'):
self.msg_cache = {}
str_msg = str(msg)
now = datetime.datetime.utcnow()
if str_msg not in self.msg_cache:
self.error(msg, *args, **kwargs)
self.msg_cache[str_msg] = now
elif now - self.msg_cache[str_msg] > TIMEDELTA:
self.error(msg, *args, **kwargs)
self.msg_cache[str_msg] = now
logging.Logger.error_without_duplicates = error_without_duplicates
while True:
try:
a = 1 /0
except Exception as ex:
logger.error_without_duplicates(ex) # every 5 seconds, not 1
time.sleep(1)
推荐阅读
- python - 如何根据另一列的值移动一列?
- python-3.x - InlineKeyboardButton 和 CallbackData
- excel - 对另一张表的数据进行排序
- python - python脚本上的文件描述符错误,但输出正确
- java - Android Fido2PendingIntent().launchPendingIntent 第一次失败,并连续工作
- javascript - SweetAlert2 获取上一步的值
- reactjs - 如何在 Reactjs 中使用 Zebradatepicker?
- java - 过滤可能为空的 SQL 行
- cassandra - cassandra where 子句,来自 udt 的一个字段
- swift - SwiftUI,如何翻译带有计时器样式的文本?