user20929302
user20929302

Reputation: 403

Dynamically remove log files in python

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

Upvotes: 2

Views: 2346

Answers (1)

DFE
DFE

Reputation: 136

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

Look at the TimedRotatingFileHandler

Upvotes: 2

Related Questions