How to limit log file size in python

后端 未结 3 2168
栀梦
栀梦 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:51

    When you use logging.basicConfig with a file, the log is attached with a file handler to handle writing to the file. afterwards you created another file handler to the same file with 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

    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)
    
    
    [, ]
    

提交回复
热议问题