python - python中动态删除日志文件

标签 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()

上面是记录和删除该日志文件的基本脚本。当前的问题是尝试动态删除文件。目标是删除超过一个月的日志,因此是same_day_prev_month。 os.remove() 可以工作,但我不知道如何动态地执行它。我尝试过的方法如下,但它没有删除任何内容。

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

最佳答案

最好的可能是使用 python 标准旋转日志,如提到的 here

查看 TimedRotatingFileHandler

关于python - python中动态删除日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50798335/

相关文章:

Python如何遍历列表并比较其中找到的字符串列表

python - 赛马节目模拟

python - Google 趋势 - 配额限制 - IP 地址更改器

python - 我如何在Python中手动管理内存?

python - 在两个相关类中使用继承的最佳方式是什么

python - 使用 STDOUT 作为 openvpn auth-user-pass 的输入

python - 从 python 套接字服务器获取一些响应

python - pytest:是否可以从代码中启用标记?

python - Tensorflow 展示模型总结

Python使用数据系列作为输入函数