简体   繁体   English

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

[英]How to limit log file size in python

I am using windows 7 and python 2.7.我正在使用 Windows 7 和 python 2.7。 I want to limit my log file size to 5MB.我想将我的日志文件大小限制为 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.应用程序启动、处理和终止。

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

Lose basicConfig() and use RotatingFileHandler :失去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")

When you use logging.basicConfig with a file, the log is attached with a file handler to handle writing to the file.当您文件使用logging.basicConfig时,日志会附加一个文件处理程序来处理对文件的写入。 afterwards you created another file handler to the same file with logging.handlers.RotatingFileHandler之后,您使用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>]

To use BasicConfig and RotatingFileHandler, add RotatingFileHandler as Handler in BasicConfig.要使用 BasicConfig 和 RotatingFileHandler,请在 BasicConfig 中添加 RotatingFileHandler 作为 Handler。

main.py:主要.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其他.py

import logging

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

"test" will be written into foo.log with the tag 'main' “test”将被写入带有标签“main”的 foo.log

"test2" will be written into foo.log with the tag 'other' “test2”将被写入带有标签“other”的 foo.log

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM