限制Python日志文件 [英] Limit Python log file

查看:132
本文介绍了限制Python日志文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python3(Ubuntu 14.04)写出日志文件.我想限制日志文件的大小,因此选择了RotatingFileHandler.另外,我不想旋转日志文件(.log变成.log.1,依此类推)-我只想限制日志文件的大小.

I'm using Python3 (Ubuntu 14.04) to write out a log file. I want to limit the size of the log file and so chose RotatingFileHandler. Additionally, I don't want to rotate the log files (.log becomes .log.1 and so on) - I just want to limit the size of the log file.

我尝试像这样使用RotatingFileHandler:

filehandler = logging.handlers.RotatingFileHandler( "app.log", "a", 1000, 0, None, True )
logging.basicConfig( format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s", level = logging.DEBUG, handlers = [ filehandler ] )

我发现日志文件继续增长,并且从未被截断或包装"到极限.

What I'm finding is the log file continues to grow and is never truncated or "wrapped" at the limit.

我本以为设置backupCount = 0会导致在写入之前检查日志文件的大小,并且是否有足够的空间容纳日志消息,请将其写入,否则清空文件并写出消息.

I would have thought setting backupCount = 0 would cause the log file size to be checked before writing and if there's room for the log message, write it, otherwise empty the file and write out the message.

有什么想法吗?

预先感谢

伯恩迈斯特.

推荐答案

如果您查看

If you have a look at the source code of the RotatingFileHandler, you will see that a backupCount of 0 just closes and then reopens the log's stream. Here is a modified version that does what you want, discarding the old file:

import os
import logging
import logging.handlers


class TruncatedFileHandler(logging.handlers.RotatingFileHandler):
    def __init__(self, filename, mode='a', maxBytes=0, encoding=None, delay=0):
        super(TruncatedFileHandler, self).__init__(
            filename, mode, maxBytes, 0, encoding, delay)

    def doRollover(self):
        """Truncate the file"""
        if self.stream:
            self.stream.close()
        dfn = self.baseFilename + ".1"
        if os.path.exists(dfn):
            os.remove(dfn)
        os.rename(self.baseFilename, dfn)
        os.remove(dfn)
        self.mode = 'w'
        self.stream = self._open()

这里是使用方法:

filehandler = TruncatedFileHandler("app.log", "w", 1000)
logging.basicConfig(
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    level=logging.DEBUG, handlers=[filehandler])

logger = logging.getLogger('spam_application')

for i in range(100):
    logger.debug("a log line, number: %s", i)

并证明其有效

❯❯❯ python3.4 main.py
❯❯❯ cat app.log*
2014-06-11 11:50:44,871 - spam_application - DEBUG - a log line, number: 91
2014-06-11 11:50:44,872 - spam_application - DEBUG - a log line, number: 92
2014-06-11 11:50:44,872 - spam_application - DEBUG - a log line, number: 93
2014-06-11 11:50:44,872 - spam_application - DEBUG - a log line, number: 94
2014-06-11 11:50:44,872 - spam_application - DEBUG - a log line, number: 95
2014-06-11 11:50:44,872 - spam_application - DEBUG - a log line, number: 96
2014-06-11 11:50:44,872 - spam_application - DEBUG - a log line, number: 97
2014-06-11 11:50:44,872 - spam_application - DEBUG - a log line, number: 98
2014-06-11 11:50:44,872 - spam_application - DEBUG - a log line, number: 99

这篇关于限制Python日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆