Python Forum
How to limit the fie size in logging.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to limit the fie size in logging.
#1
Hi All,

How to limit the file size and should start to write into a new file in logging. Much appreciated your help/suggestions on this. Thanks a lot.

Regards,
Maiya
Reply
#2
Use a RotatingFileHandler, here an example copied and pasted from the famous Mouse vs Python blog.
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=5)
    logger.addHandler(handler)
    
    for i in range(10):
        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)
Reply
#3
logging_file   = 'test.log'
logging_format = '%(asctime)s: [%(levelname)s] [{}] %(message)s'.format(self.action)
        
logging.basicConfig(
    filename = '{}'.format(logging_file),
    format   = '{}'.format(logging_format),
    level    = logging.DEBUG
)
This is my code, here I need to limit the file size and rotate the file. How to do the same sir. Much appreciated for your help on this. Thank you.

Regards,
Maiya
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Tkinter Entry size limit vman44 3 6,662 Dec-22-2022, 06:58 AM
Last Post: vman44
  How to rotate log and limit the size maiya 0 1,751 Aug-29-2020, 12:41 AM
Last Post: maiya
  size of set vs size of dict zweb 0 2,139 Oct-11-2019, 01:32 AM
Last Post: zweb
  Restrict / Limit variable size mln4python 4 7,160 Aug-13-2019, 07:17 AM
Last Post: mln4python
  CSV file created is huge in size. How to reduce the size? pramoddsrb 0 10,478 Apr-26-2018, 12:38 AM
Last Post: pramoddsrb

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020