python实现定时提取实时日志程序
作者:墨飏韶年 时间:2023-03-03 22:31:24
本文实例为大家分享了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)
来源:https://blog.csdn.net/weixin_37887248/article/details/80727560
标签:python,提取日志
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
保护SQL服务器的安全 用户识别问题
2008-12-24 15:26:00
![](https://img.aspxhome.com/file/UploadPic/200812/20081225122629996.jpg)
Django框架中方法的访问和查找
2022-07-23 16:31:35
Python timeit模块原理及使用方法
2023-09-22 08:19:18
Python实现从url中提取域名的几种方法
2022-03-14 12:55:30
跟老齐学Python之变量和参数
2023-01-12 22:23:31
Python3.5字符串常用操作实例详解
2023-08-31 00:25:53
![](https://img.aspxhome.com/file/2023/8/62608_0s.png)
thinkphp 多表 事务详解
2023-07-08 05:43:36
Keras多线程机制与flask多线程冲突的解决方案
2023-09-12 02:10:51
pandas Dataframe实现批量修改值的方法
2022-12-19 21:52:59
![](https://img.aspxhome.com/file/2023/2/77692_0s.png)
用javascript实现的汉字简繁转换功能
2008-05-04 13:15:00
Python pywifi ERROR Open handle failed问题及解决
2021-01-16 03:54:28
Asp生成RSS的类_给网站加上RSS
2011-04-19 11:06:00
Opera下cloneNode的bug
2007-11-23 11:40:00
解析Oracle 8i/9i的计划稳定性
2010-07-26 13:09:00
小结下dom节点操作
2011-03-08 10:33:00
Python 2/3下处理cjk编码的zip文件的方法
2022-08-05 17:53:40
使用python Django做网页
2023-11-22 03:35:26
![](https://img.aspxhome.com/file/2023/2/63892_0s.png)
通过js获取div的background-image属性
2023-08-23 06:07:23
使用 prometheus python 库编写自定义指标的方法(完整代码)
2021-03-03 06:03:58
使用Python解决常见格式图像读取nii,dicom,mhd
2021-11-14 23:36:59