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

查看:63
本文介绍了如何限制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 但它没有用

I tried with RotatingFileHandler but it didn't work

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?

推荐答案

Lose basicConfig() 并使用 RotatingFileHandler:

Lose basicConfig() and use 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")

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

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