如何限制python日志记录文件的大小?

时间:2020-09-29 20:48:23

标签: python logging

请考虑以下示例代码:

import logging
import time
from logging.handlers import RotatingFileHandler
#----------------------------------------------------------------------
def create_rotating_log(path):
    """
    Creates a rotating log
    """    
    logger = logging.getLogger("Rotating Log")
    logger.setLevel(logging.INFO)

    # add a rotating handler
    handler = RotatingFileHandler(path, maxBytes=20,
                                      backupCount=1)
    logger.addHandler(handler)

    for i in range(20):
        logger.info("This is test log line %s" % i)
        time.sleep(1.5)
    
#----------------------------------------------------------------------
if __name__ == "__main__":
    log_file = "test.log"
    create_rotating_log(log_file)

脚本用backupCount=1完成后,它将创建两个文件test.logtest.log.1,其中第一个文件包含:

This is test log line 19

和第二个conatins:

This is test log line 18

我不需要任何备份文件,我也想限制日志文件的大小。因此,当我设置backupCount=0时,记录器仅将日志文件中的每一行附加在日志文件的大小上,就好像没有限制。这是test.logbackupCount=0的内容:

This is test log line 0
This is test log line 1
This is test log line 2
This is test log line 3
This is test log line 4
This is test log line 5
This is test log line 6
This is test log line 7
This is test log line 8
This is test log line 9
This is test log line 10
This is test log line 11
This is test log line 12
This is test log line 13
This is test log line 14
This is test log line 15
This is test log line 16
This is test log line 17
This is test log line 18
This is test log line 19

0 个答案:

没有答案