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在七牛云平台的应用(一)

七牛云七牛云是国内领先的企业级云服务商。专注于以数据为核心的云计算业务,围绕富媒体场景推出了对象存储、融合CDN、容器云、大数据、深度学习平台等产品,并提供一站式视频云解决方案,同时打造...

浅谈Python黑帽子取代netcat

浅谈Python黑帽子取代netcat

按照各位大佬的博客来,端口连接的命令始终连接不上。 后来问了同学,在开了监听之后: 使用书上的代码连接不能成功,连接的命令改成:nc www.baidu.com 80(同理 监听本地就...

python 常见字符串与函数的用法详解

strip去除空格 s = ' abcd efg ' print(s.strip()) #去除所有空格 print(s.lstrip()) #去除左边空格 print(s.rs...

matplotlib实现热成像图colorbar和极坐标图的方法

matplotlib实现热成像图colorbar和极坐标图的方法

热成像图 %matplotlib inline from matplotlib import pyplot as plt import numpy as np def f(x,...

对pandas写入读取h5文件的方法详解

1、引言 通过参考相关博客对hdf5格式简要介绍。 hdf5在存储的是支持压缩,使用的方式是blosc,这个是速度最快的也是pandas默认支持的。 使用压缩可以提磁盘利用率,节省空间。...