Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit log file size in python

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 again, it will write in same log file. So app is not continuously running. App initiates, processes and terminates.

My code for logging is:

import logging import logging.handlers logging.basicConfig(filename=logfile.log, level="info", format='%(asctime)s %(levelname)s %(funcName)s(%(lineno)d) %(message)s') logging.info("*************************************************") 

I tried with RotatingFileHandler but it didn't work

logging.handlers.RotatingFileHandler(logFile, mode='a', maxBytes=5*1024*1024, backupCount=2, encoding=None, delay=0) 

So, how can I enforce a file size limit in python?

like image 514
imp Avatar asked Jul 01 '14 07:07

imp


People also ask

How do I limit the file size of a log in Linux?

To limit the size of /var/log/syslog , you have to edit the /etc/rsyslog. d/50-default. conf , and set a fixed log size.


1 Answers

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") 
like image 167
Shadow9043 Avatar answered Sep 28 '22 21:09

Shadow9043