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入门教程 python入门神图一张

python入门教程 python入门神图一张

初试牛刀 假设你希望学习Python这门语言,却苦于找不到一个简短而全面的入门教程。那么本教程将花费十分钟的时间带你走入Python的大门。本文的内容介于教程(Toturial)和速查手...

pandas 小数位数 精度的处理方法

控制台打印时显示的2位小数: pd.set_option('precision', 2) 实际修改数据精度: 官例:http://pandas.pydata.org/pandas-...

python基于三阶贝塞尔曲线的数据平滑算法

python基于三阶贝塞尔曲线的数据平滑算法

前言 很多文章在谈及曲线平滑的时候,习惯使用拟合的概念,我认为这是不恰当的。平滑后的曲线,一定经过原始的数据点,而拟合曲线,则不一定要经过原始数据点。 一般而言,需要平滑的数据分为两种:...

利用Python实现颜色色值转换的小工具

利用Python实现颜色色值转换的小工具

先看看Zeplin 的颜色色值显示示例 原有处理方式 因为我会 Python (仅限于终端输入 python 然后当做计算器算,或者用 hex() 函数把十进制转换成十六进制),所...

用Python和MD5实现网站挂马检测程序

一、程序测试复制代码 代码如下:# python check_change.py     Usage: python check_change.py upd...