Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6916129
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T09:33:45+00:00 2026-05-27T09:33:45+00:00

Can anyone suggest a way in python to do logging with: log rotation every

  • 0

Can anyone suggest a way in python to do logging with:

  • log rotation every day
  • compression of logs when they’re rotated
  • optional – delete oldest log file to preserve X MB of free space
  • optional – sftp log files to server

Thanks for any responses,
Fred

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T09:33:45+00:00Added an answer on May 27, 2026 at 9:33 am
    • log rotation every day: Use a TimedRotatingFileHandler
    • compression of logs: Set the encoding='bz2' parameter. (Note this “trick” will only work for Python2. ‘bz2’ is no longer considered an encoding in Python3.)
    • optional – delete oldest log file to preserve X MB of free space.
      You could (indirectly) arrange this using a RotatingFileHandler. By setting the maxBytes parameter, the log file will rollover when it reaches a certain size. By setting the backupCount parameter, you can control how many rollovers are kept. The two parameters together allow you to control the maximum space consumed by the log files. You could probably subclass the TimeRotatingFileHandler to incorporate this behavior into it as well.

    Just for fun, here is how you could subclass TimeRotatingFileHandler. When you run the script below, it will write log files to /tmp/log_rotate*.

    With a small value for time.sleep (such as 0.1), the log files fill up quickly, reach the maxBytes limit, and are then rolled over.

    With a large time.sleep (such as 1.0), the log files fill up slowly, the maxBytes limit is not reached, but they roll over anyway when the timed interval (of 10 seconds) is reached.

    All the code below comes from logging/handlers.py. I simply meshed TimeRotatingFileHandler with RotatingFileHandler in the most straight-forward way possible.

    import time
    import re
    import os
    import stat
    import logging
    import logging.handlers as handlers
    
    
    class SizedTimedRotatingFileHandler(handlers.TimedRotatingFileHandler):
        """
        Handler for logging to a set of files, which switches from one file
        to the next when the current file reaches a certain size, or at certain
        timed intervals
        """
    
        def __init__(self, filename, maxBytes=0, backupCount=0, encoding=None,
                     delay=0, when='h', interval=1, utc=False):
            handlers.TimedRotatingFileHandler.__init__(
                self, filename, when, interval, backupCount, encoding, delay, utc)
            self.maxBytes = maxBytes
    
        def shouldRollover(self, record):
            """
            Determine if rollover should occur.
    
            Basically, see if the supplied record would cause the file to exceed
            the size limit we have.
            """
            if self.stream is None:                 # delay was set...
                self.stream = self._open()
            if self.maxBytes > 0:                   # are we rolling over?
                msg = "%s\n" % self.format(record)
                # due to non-posix-compliant Windows feature
                self.stream.seek(0, 2)
                if self.stream.tell() + len(msg) >= self.maxBytes:
                    return 1
            t = int(time.time())
            if t >= self.rolloverAt:
                return 1
            return 0
    
    
    def demo_SizedTimedRotatingFileHandler():
        log_filename = '/tmp/log_rotate'
        logger = logging.getLogger('MyLogger')
        logger.setLevel(logging.DEBUG)
        handler = SizedTimedRotatingFileHandler(
            log_filename, maxBytes=100, backupCount=5,
            when='s', interval=10,
            # encoding='bz2',  # uncomment for bz2 compression
        )
        logger.addHandler(handler)
        for i in range(10000):
            time.sleep(0.1)
            logger.debug('i=%d' % i)
    
    demo_SizedTimedRotatingFileHandler()
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Can anyone suggest a way of getting version information into a Web Service? (VB.NET)
Can anyone suggest a suitable way of figuring out a pieces allowable moves on
Can anyone suggest the best way to display a Textblock (with a text such
Can anyone suggest the best way to offer a file for download within a
Can anyone please suggest a way to replace back-slash '\' with slash '/' in
Can anyone suggest a way of stripping tab characters ( \ts ) from a
can anyone suggest me way to display all records in MySQL table within a
Can anyone suggest a way of rotating text by any angle without using something
Can anyone suggest way to trace the mobile tower signals in android. Tracing means
Can anyone suggest a way to get the MVC templates installed without running the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.