在为我创建的python脚本创建日志系统的过程中,我想每周清理一次数据,但我不确定最好的方法。下面是我创建实际记录项目所需的所有代码。
import logging
logger = logging.getLogger('Python Script Logger')
logger.setLevel(logging.INFO)
# Create a file handler
handler = logging.FileHandler('My_Test_Log.log')
handler.setLevel(logging.INFO)
# Create a logging format
formatter = logging.Formatter('%(asctime)s - Line: %(lineno)d - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
#add the handlers to the logger
logger.addHandler(handler)
logger.info('-----------------------------')
logger.info('Creating New Entry')
我所拥有的是这样的东西,但是当我调用该函数时,没有任何行被删除。逻辑是它打开旧的日志文件,并打开一个新文件,并将任何不包含我要删除的时间戳的行写入新文件。
def clear_logs():
date_array = ['2018-06-12']
with open('My_Test_log.log') as old_file, open('My_New_Test.log', 'w') as new_file:
for line in old_file:
if not any(date in line for date in date_array):
new_file.write(line)
我的日志文件中的某些行如下所示:
2018-06-12 15:55:41,554 - Line:144 - ERROR - Error inserting row
2018-06-12 15:55:41,603 - Line:144 - ERROR - Error inserting row
2018-06-13 08:58:54,492 - Line:30 - INFO - -----------------------------
2018-06-13 08:58:54,493 - Line:31 - INFO - Creating New Entry
2018-06-13 08:58:54,493 - Line:205 - WARNING - Invalid argument provided
答案 0 :(得分:0)
回答我发现的工作。基本上这背后的想法是打开文件,读取,存储然后关闭。然后再次打开作为写入选项,并在一行中搜索您要查找的文本行,并删除它是否是您所拥有的。这将清除您要删除的任何行。
my_file = open(log_file, "r")
lines = my_file.readlines()
my_file.close()
my_file = open(log_file, "w")
my_array= ['fill','this','with','what','you','wish','to','remove']
for line in lines:
for item in my_array:
if item in line:
pass
else:
my_file.write(line)
my_file.close()