How to limit log file size in python

后端 未结 3 2163
栀梦
栀梦 2020-12-05 02:23

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 aga

3条回答
  •  孤城傲影
    2020-12-05 02:52

    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")
    

提交回复
热议问题