温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python实现定时提取实时日志程序

发布时间:2020-10-13 10:38:35 来源:脚本之家 阅读:140 作者:墨飏韶年 栏目:开发技术

本文实例为大家分享了python定时提取实时日志的具体代码,供大家参考,具体内容如下

这是一个定时读取 实时日志文件的程序。目标文件是target_file. 它是应用程序实时写入的。

我要做的是,每个5秒钟,提取一次该日志文件中的内容,然后生成另一个文件,最后把这些文件都汇总。

#!/usr/local/bin/python 
# coding:utf-8 
 
import fileinput 
import time 
import os 
 
target_file = 'user.log' 
init_flag = True # 初次加载程序 
time_kick = 5 
 
record_count = 0 
 
while True: 
 print '当前读到了', record_count 
 #没有日志文件,等待 
 if not os.path.exists(target_file): 
 print 'target_file not exist' 
 time.sleep(time_kick) 
 continue 
 
 try: 
 ip = '10.10.1.100' 
 easytime = time.strftime('%Y%m%d_%H%M%S', time.localtime()) 
 file_name = '%s_user_%s.log' % (ip,easytime) 
 f_w = open(file_name, 'w') 
 if init_flag: 
  #读取整个文件 
  for eachline in fileinput.input(target_file): 
  print eachline 
  f_w.write(eachline) 
  record_count += 1 
 
  init_flag = False 
 else: 
  #如果总行数小于当前行,那么认为文件更新了,从第一行开始读。 
  total_count = os.popen('wc -l %s' % target_file).read().split()[0] 
  total_count = int(total_count) 
  if total_count < record_count: 
  record_count = 0 
 
  for eachline in fileinput.input(target_file): 
  line_no = fileinput.filelineno() 
  if line_no > record_count: 
   print eachline 
   f_w.write(eachline) 
   record_count += 1 
 
 f_w.close() 
 except: 
 pass 
 time.sleep(time_kick) 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI