如何限制python中的日志文件大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24505145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to limit log file size in python
提问by imp
I am using windows 7 and python 2.7. I want to limit my log file size to 5MB. My app, when it starts, writes to log file, and then the app terminates. When my app starts again, it will write in same log file. So app is not continuously running. App initiates, processes and terminates.
我正在使用 Windows 7 和 python 2.7。我想将我的日志文件大小限制为 5MB。我的应用程序在启动时写入日志文件,然后应用程序终止。当我的应用程序再次启动时,它将写入相同的日志文件。所以应用程序没有持续运行。应用程序启动、处理和终止。
My code for logging is:
我的日志记录代码是:
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("*************************************************")
I tried with RotatingFileHandlerbut it didn't work
我尝试使用RotatingFileHandler但它没有用
logging.handlers.RotatingFileHandler(logFile, mode='a', maxBytes=5*1024*1024, backupCount=2, encoding=None, delay=0)
So, how can I enforce a file size limit in python?
那么,如何在 python 中强制执行文件大小限制?
采纳答案by Shadow9043
Lose basicConfig()
and try this:
输了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")
This works on my machine
这适用于我的机器
回答by AmitE
When you use logging.basicConfigwith a file, the log is attached with a file handler to handle writing to the file. afterwards you created another file handler to the same file with logging.handlers.RotatingFileHandler
当您对文件使用logging.basicConfig时,日志会附加一个文件处理程序来处理对文件的写入。之后,您使用logging.handlers.RotatingFileHandler为同一文件创建了另一个文件处理程序
Now, once a rotate is needed, RotatingFileHandler is trying to remove the old file but it can't becuase there is an open file handler
现在,一旦需要旋转, RotatingFileHandler 会尝试删除旧文件,但不能因为有一个打开的文件处理程序
this can be seen if you look directly at the log file handlers -
如果您直接查看日志文件处理程序,就可以看到这一点 -
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>]