How to limit log file size in python

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

    To use BasicConfig and RotatingFileHandler, add RotatingFileHandler as Handler in BasicConfig.

    main.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

    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'

    "test2" will be written into foo.log with the tag 'other'

提交回复
热议问题