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

yipeiwu_com6年前Python基础

本文实例为大家分享了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) 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python自动化测试Eclipse+Pydev 搭建开发环境

Python自动化测试Eclipse+Pydev 搭建开发环境

Python自动化测试 Eclipse+Pydev 搭建开发环境 C#之所以容易让人感兴趣,是因为安装完Visual Studio, 就可以很简单的直接写程序了,不需要做如何配置。 对新...

Python字符串切片操作知识详解

一:取字符串中第几个字符 print "Hello"[0] 表示输出字符串中第一个字符 print "Hello"[-1] 表示输出字符串中最后一个字符 二:字符串分割 print...

python中日期和时间格式化输出的方法小结

本文实例总结了python中日期和时间格式化输出的方法。分享给大家供大家参考。具体分析如下: python格式化日期时间的函数为datetime.datetime.strftime();...

python实现数据图表

python实现数据图表

平时压力测试,生成一些数据后分析,直接看 log 不是很直观,前段时间看到公司同事分享了一个绘制图表python 模块 : plotly, 觉得很实用,利用周末时间熟悉下。 plotl...

深入了解Python中pop和remove的使用方法

Python关于删除list中的某个元素,一般有两种方法,pop()和remove()。 remove() 函数用于移除列表中某个值的第一个匹配项。 remove()方法语法: list...