logging.handlers:如何在时间或 maxBytes 后滚动?
我确实在日志记录方面遇到了一些困难。我想在一段时间后以及达到一定大小后滚动日志。
一段时间后的翻转由 TimedRotatingFileHandler
, 达到特定日志大小后进行翻转由
RotatingFileHandler
< /a>.
但 TimedRotatingFileHandler
没有属性 maxBytes
并且 RotatingFileHandler
在一定时间后无法旋转。 我还尝试将两个处理程序添加到记录器中,但结果是日志记录加倍。
我错过了什么吗?
我还研究了logging.handlers的源代码。我尝试子类化 TimedRotatingFileHandler
并重写方法 shouldRollover()
来创建一个具有这两种功能的类:
class EnhancedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):
def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None, delay=0, utc=0, maxBytes=0):
""" This is just a combination of TimedRotatingFileHandler and RotatingFileHandler (adds maxBytes to TimedRotatingFileHandler) """
# super(self). #It's old style class, so super doesn't work.
logging.handlers.TimedRotatingFileHandler.__init__(self, filename, when='h', interval=1, backupCount=0, encoding=None, delay=0, utc=0)
self.maxBytes=maxBytes
def shouldRollover(self, record):
"""
Determine if rollover should occur.
Basically, see if the supplied record would cause the file to exceed
the size limit we have.
we are also comparing times
"""
if self.stream is None: # delay was set...
self.stream = self._open()
if self.maxBytes > 0: # are we rolling over?
msg = "%s\n" % self.format(record)
self.stream.seek(0, 2) #due to non-posix-compliant Windows feature
if self.stream.tell() + len(msg) >= self.maxBytes:
return 1
t = int(time.time())
if t >= self.rolloverAt:
return 1
#print "No need to rollover: %d, %d" % (t, self.rolloverAt)
return 0
但是像这样,日志会创建一个备份,然后被覆盖。看来我还必须重写方法 doRollover()
这并不那么容易。
还有其他想法如何创建一个记录器,在一定时间后以及达到一定大小后滚动文件吗?
I do struggle with the logging a bit. I'd like to roll over the logs after certain period of time and also after reaching certain size.
Rollover after a period of time is made by TimedRotatingFileHandler
,
and rollover after reaching certain log size is made by RotatingFileHandler
.
But the TimedRotatingFileHandler
doesn't have the attribute maxBytes
and the RotatingFileHandler
can not rotate after a certain period of time.
I also tried to add both handlers to logger, but the result was doubled logging.
Do I miss something?
I also looked into source code of logging.handlers
. I tried to subclass TimedRotatingFileHandler
and override the method shouldRollover()
to create a class with capabilities of both:
class EnhancedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):
def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None, delay=0, utc=0, maxBytes=0):
""" This is just a combination of TimedRotatingFileHandler and RotatingFileHandler (adds maxBytes to TimedRotatingFileHandler) """
# super(self). #It's old style class, so super doesn't work.
logging.handlers.TimedRotatingFileHandler.__init__(self, filename, when='h', interval=1, backupCount=0, encoding=None, delay=0, utc=0)
self.maxBytes=maxBytes
def shouldRollover(self, record):
"""
Determine if rollover should occur.
Basically, see if the supplied record would cause the file to exceed
the size limit we have.
we are also comparing times
"""
if self.stream is None: # delay was set...
self.stream = self._open()
if self.maxBytes > 0: # are we rolling over?
msg = "%s\n" % self.format(record)
self.stream.seek(0, 2) #due to non-posix-compliant Windows feature
if self.stream.tell() + len(msg) >= self.maxBytes:
return 1
t = int(time.time())
if t >= self.rolloverAt:
return 1
#print "No need to rollover: %d, %d" % (t, self.rolloverAt)
return 0
But like this the log creates one backup and the gets overwritten. Seems like I have to override also method doRollover()
which is not so easy.
Any other idea how to create a logger which rolls the file over after certain time and also after certain size reached?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
因此,我对 TimedRotatingFileHandler 做了一个小修改,以便能够在时间和大小之后进行翻转。我必须修改
__init__
、shouldRollover
、doRollover
和getFilesToDelete
(见下文)。这是结果,当我设置when='M',interval=2,backupCount=20,maxBytes=1048576时:可以看到前四个日志在达到1MB大小后滚动,而最后一次滚动发生在两个之后分钟。到目前为止,我还没有测试删除旧日志文件,所以它可能不起作用。
该代码对于 backupCount>=1000 肯定不起作用。我在文件名末尾仅附加三位数字。
这是修改后的代码:
So I made a small hack to
TimedRotatingFileHandler
to be able to do rollover after both, time and size. I had to modify__init__
,shouldRollover
,doRollover
andgetFilesToDelete
(see below). This is the result, when I set up when='M', interval=2, backupCount=20, maxBytes=1048576:You can see that first four logs were rolled over after reaching size of 1MB, while the last rollover occurred after two minutes. So far I didn't test deleting of old log files, so it probably doesn't work.
The code certainly will not work for backupCount>=1000. I append just three digits at the end of the file name.
This is the modified code:
如果您确实需要此功能,请基于 TimedRotatingFileHandler 编写自己的处理程序,主要使用时间进行滚动,但将基于大小的滚动合并到现有逻辑中。您已经尝试过此操作,但您需要(至少)重写
shouldRollover()
和doRollover()
方法。第一种方法确定何时滚动,第二种方法关闭当前日志文件,重命名现有文件并删除过时的文件,然后打开新文件。doRollover() 逻辑可能有点棘手,但肯定是可行的。
If you really need this functionality, write your own handler based on TimedRotatingFileHandler to primarily use time for rolling over, but incorporate sized-based rollover into the existing logic. You've tried this, but you need to (at a minimum) override both
shouldRollover()
anddoRollover()
methods. The first method determines when to roll over, the second does the closing of the current log file, renaming existing files and deleting obsolete files, then opening the new file.The
doRollover()
logic may be a little tricky, but certainly doable.这是我使用的:
Here is what I use:
我根据我的用途改编了 Julien 的代码。现在,它会在达到一定日志大小或一段时间后滚动。
I adapted Julien's code for my usage. Now it rollover after reaching certain log size or after a period of time.
从sumid回答开始,我做了一些更改、修复,并与TimedRotatingFileHandler的最新版本合并以及 2024 年的 RotatingFileHandler
。现在:
max_bytes
,它将按添加当前日期和渐进后缀。它被认为是从 000 到 999 的渐进掩码,之后最旧的文件将逐渐被覆盖。如果需要更多日志,请调整
maxBytes
参数或更改代码中的.%03d
出现次数。when='MIDNIGHT'
日志文件将在日期变化时轮换并添加包含以下内容的后缀
前一个日期和渐进标识符。
backupCount=numberOfDays
参数用于设置每个日志文件在文件夹中保留的天数,它被认为是文件的最后一次更改(因此在轮换时)。因此,如果backupCount=30
将删除所有超过 30 天的文件。每个日志文件都会轮换并命名为:
我知道它可以改进,并且肯定包含错误。任何建议表示赞赏。
Starting from sumid answer I made some changes, fixes, and merged with the recent versions of TimedRotatingFileHandler and RotatingFileHandler in 2024.
Now:
max_bytes
, it will rotated byadding current date and a progressive suffix. It is considered a progressive mask from 000 to 999, after that the oldest files will be progressively overwrited. If needed more logs, tune the
maxBytes
parameter or change.%03d
occurrences in the code.when='MIDNIGHT'
the log file willbe rotated at the day change and added a suffix containing the
previous date and a progressive identifier.
backupCount=numberOfDays
parameter is used to set the number of days each log file will maintained in the folder, it is considered the last change of the file (so the moment it was rotated). Hence, ifbackupCount=30
will be deleted all files older than 30 days.Each log file is rotated and named as:
I am aware that it can be improved, and certainly contains errors. Any suggestions are appreciated.