Directory Entry Using Python

I have a file Poller.log and it is added to the log data all the time. I want this log file to rotate every day and be limited to 30 days. Thus, the code works well.

Now I want these logs to be rotated to be in a folder (i.e. logs / poller.log.2011-03-04_15-36). Is there any need to direct to where this rotating file should be created?

This python script will be executed by cron.

import logging import logging.handlers LOG_FILENAME = '/home/stackoverflow/snmpdata/poller.log' # Set up a specific logger with our desired output level poll_logger = logging.getLogger('pollerLog') # Add the log message handler to the logger log_rotator = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME, when='d', interval=1, backupCount=30, encoding=None, delay=False, utc=False) poll_logger.addHandler(log_rotator) # Roll over on application start poll_logger.handlers[0].doRollover() 
+4
source share
2 answers

The Python protocol handler does not allow this to be done easily. You can have 2 ways to achieve this:

  • The easiest way is to set LOG_FILENAME already in logs / poller.log, and if you want to access your poller.log elsewhere, use a symbolic link :)

  • Create your own handler starting with TimedRotatingFileHandler and copy / paste doRollover () from the class / usr / lib / python 2.X / logging / handlers.py, TimedRotatingFileHandler. And change:

  dfn = self.baseFilename + "."  + time.strftime (self.suffix, timeTuple) 

to

  dfn = os.path.join ('logs', os.path.basename (self.baseFilename)) + "."  + time.strftime (self.suffix, timeTuple) 
+4
source

If you are not opposed to an additional dependency, you can always use the rollover log module in a twisted form. Twisted has a log module that allows you to log daily, weekly magazines, or even monthly magazines like this.

+2
source

Source: https://habr.com/ru/post/1342252/


All Articles