2
import os
import sys
from datetime import timedelta, datetime
import logging

def main():
    today = datetime.dateime.today().strftime('%y-%m-%d')
    logging.basicConfig(filename='Logs/'+today+'.log', level = logging.DEBUG)
    logging.info('Test Log: INFO')
    logging.warning('Test log: WARNING')
    logging.debug('Test log: DEBUG')

    clear_old_logs()

def clear_old_logs():
    today = datetime.date.today()

    last_day_prev_month = today - datetime.timedelta(days=today.day)
    same_day_prev_month = last_day_prev_month.replace(day=today.day)

    test_date = '2018-06-11'
    change_dir = os.open("Logs", os.O_RDONLY)
    change_dir = os.fchdir(change_dir)
    print "Current Directory: %s" % os.getcwd()
    print "Directory contents: %s" %os.listdir(os.getcwd())

    test_file = test_date+'.log'


    print(test_file)
    os.remove(test_file)

if __name__ == '__main__':
    main()

Above is a basic script to log and remove that log file. The issue at hand is trying to remove the files dynamically. The goal is to remove logs that are older than a month, hence the same_day_prev_month. The os.remove() works but Im not sure how to do it dynamically. The method I have tried is below, but its not removing anything.

def clear_old_logs():
    today = datetime.date.today()

    last_day_prev_month = today - datetime.timedelta(days=today.day)
    same_day_prev_month = last_day_prev_month.replace(day=today.day)

    test_date = '2018-06-11'
    change_dir = os.open("Logs", os.O_RDONLY)
    change_dir = os.fchdir(change_dir)

    mylist = os.listdir(os.getcwd())
    #file = same_day_prev_month+'.log' #I commented this out due to testing with the current date
    file = test_date+'.log' #just testing to see if I can remove log files created today with an if
    for logs in mylist:
        if file >= logs:
            os.remove(logs)
        else:
            continue
1
  • Not in Python, but Linux has a service for cleaning old files: man tmpfiles.d. Commented Jun 11, 2018 at 13:16

1 Answer 1

2

The best may be to use python standard rotating logs like mentionned here

Look at the TimedRotatingFileHandler

Sign up to request clarification or add additional context in comments.

1 Comment

Just wondering if this for short term use though vs long term since the biggest interval seems to be a day of the week

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.