首页 > 其他 > 详细

日志和关键字查找

时间:2019-06-26 12:35:38      阅读:95      评论:0      收藏:0      [点我收藏+]
造日志脚本
def
timestamp_to_str(timestamp=None,format=%Y-%m-%d %H:%M:%S): ‘‘‘时间戳转格式化好的时间,如果没有传时间戳,就获取当前的格式化时间‘‘‘ if timestamp: time_tuple = time.localtime(timestamp) #把时间戳转成时间元组 result = time.strftime(format,time_tuple) #把时间元组转成格式化好的时间 return result else: return time.strftime(format) import time,os l = [ios,android,nginx,tomcat,python,blog,apache,mysql,redis] for i in l: p = os.path.join(logs,i) os.makedirs(p) for j in range(10): t = int(time.time())-86400*j time_str = timestamp_to_str(t,%Y-%m-%d) log_name = %s_%s.log%(i,time_str) abs_file_path = os.path.join(logs,i,log_name) open(abs_file_path,w)
#1、获取到当天的时间戳
#2、再获取到三天前的时间戳
#3、再把文件的日期转成时间戳
#4、如果文件的日期小于三天前的时间戳那么就删除
import os
import time

def str_to_timestamp(str=None,format=%Y-%m-%d %H:%M:%S):
    #格式化好的时间转时间戳的,如果不传格式化好的时间,就返回当前的时间戳
    if str:
        time_tuple = time.strptime(str,format)
        # 把格式化好的时间,转成时间元组
        return int(time.mktime(time_tuple))
    return int(time.time())

def clean_log(path,day=3):
    cur_time = int(time.time())
    three_days_ago = cur_time - 24*60*60*day
    for cur_path,dirs,files in os.walk(path):
        for file_name in files:
            if file_name.endswith(.log):
                file_time = file_name.split(.)[0].split(_)[-1]
                file_time = str_to_timestamp(file_time,format=%Y-%m-%d)
                if file_time<three_days_ago:
                    abs_path = os.path.join(cur_path,file_name)
                    os.remove(abs_path)

# clean_log(‘logs‘)
#1、获取到某个目录下面所有的文件
#2、判断是否以.txt结尾
#3、如果是.txt结尾打开这个文件,读取内容
#4、判断这个关键字是否在文件内容里面
#5、如果在的话 就输出
import os


def find_content(keyword,path):
    if os.path.exists(path):
        for cur_path,dirs,files in os.walk(path):
            for file in files:
                if file.endswith(.txt):
                    abs_path = os.path.join(cur_path,file)
                    with open(abs_path) as f:
                        if keyword in f.read():
                            print(在【%s】这个文件里面有你查找的内容!%abs_path)

    else:
        print(你传入的路径不存在)

 

日志和关键字查找

原文:https://www.cnblogs.com/Dorami/p/11089010.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!