49

我正在使用 Windows 7 和 python 2.7。我想将我的日志文件大小限制为 5MB。我的应用程序在启动时写入日志文件,然后应用程序终止。当我的应用程序再次启动时,它将写入同一个日志文件。所以应用程序不会连续运行。应用程序启动、处理和终止。

我的日志记录代码是:

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 中强制执行文件大小限制?

4

3 回答 3

80

丢失basicConfig()并使用RotatingFileHandler

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")
于 2014-07-01T08:09:00.453 回答
19

当您将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(log_name, maxBytes=1024, backupCount=1)
log.addHandler(handler)


[<logging.FileHandler object at 0x02AB9B50>, <logging.handlers.RotatingFileHandler object at 0x02AC1D90>]
于 2015-06-16T16:09:35.547 回答
10

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

主要.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")

其他.py

import logging

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

“test”将被写入带有标签“main”的foo.log

“test2”将被写入带有标签“其他”的 foo.log

于 2020-08-05T14:47:19.657 回答