如何在python中限制日志文件大小

时间:2014-07-01 07:55:03

标签: python logging filehandler log-files

我使用的是Windows 7和python 2.7。 我想将日志文件大小限制为5MB。 我的应用程序在启动时写入日志文件,然后应用程序终止。 当我的应用程序再次启动时,它将写入相同的日志文件。因此app不会持续运行。 应用程序启动,处理和终止。

我的日志记录代码是:

import logging
import logging.handlers
logging.basicConfig(filename=logfile.log, level="info", format='%(asctime)s %(levelname)s %(funcName)s(%(lineno)d) %(message)s')
logging.info("*************************************************")

我尝试使用 RotatingFileHandler ,但它没有工作

logging.handlers.RotatingFileHandler(logFile, mode='a', maxBytes=5*1024*1024, backupCount=2, encoding=None, delay=0)

那么,如何在python中强制实施文件大小限制?

3 个答案:

答案 0 :(得分:40)

丢失basicConfig并试试这个:

import logging
from logging.handlers import RotatingFileHandler

log_formatter = logging.Formatter('%(asctime)s %(levelname)s %(funcName)s(%(lineno)d) %(message)s')

logFile = 'C:\\Temp\\log'

my_handler = RotatingFileHandler(logFile, mode='a', maxBytes=5*1024*1024, 
                                 backupCount=2, encoding=None, delay=0)
my_handler.setFormatter(log_formatter)
my_handler.setLevel(logging.INFO)

app_log = logging.getLogger('root')
app_log.setLevel(logging.INFO)

app_log.addHandler(my_handler)

while True:
    app_log.info("data")

这适用于我的机器

答案 1 :(得分:12)

logging.basicConfig 与文件一起使用时,日志附带一个文件处理程序来处理对文件的写入。 之后你用同一个文件创建了另一个文件处理程序 logging.handlers.RotatingFileHandler

现在,一旦需要旋转,RotatingFileHandler正在尝试删除旧文件,但它不能因为有一个打开的文件处理程序

如果直接查看日志文件处理程序,可以看到这一点 -

import logging
from logging.handlers import RotatingFileHandler

log_name = 'c:\\log.log'
logging.basicConfig(filename=log_name)
log = logging.getLogger()
handler = RotatingFileHandler(name,maxBytes=1024,backupCount=1)
log.addHandler(handler)


[<logging.FileHandler object at 0x02AB9B50>, <logging.handlers.RotatingFileHandler object at 0x02AC1D90>]

答案 2 :(得分:1)

要使用BasicConfig和RotatingFileHandler,请在BasicConfig中将RotatingFileHandler添加为Handler。

main.py:

import logging

rfh = logging.handlers.RotatingFileHandler(
    filename='foo.log', 
    mode='a',
    maxBytes=5*1024*1024,
    backupCount=2,
    encoding=None,
    delay=0
)

logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s %(name)-25s %(levelname)-8s %(message)s",
    datefmt="%y-%m-%d %H:%M:%S",
    handlers=[
        rfh
    ]
)

logger = logging.getLogger('main')

logger.debug("test")

other.py

import logging

class Other():
    def __init(self):
        self.logger = logging.getLogger('other')
        self.logger.info("test2")

“测试”将被标记为“ main”写入foo.log

“ test2”将被标记为'other'写入foo.log

相关问题