如何在python中限制日志文件的大小 [英] How to limit log file size in python

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

问题描述

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

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.

我的日志记录代码是:

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

So, how can I enforce a file size limit in python?

推荐答案

丢失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

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

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