Python 定时提取实时日志的程序

小灰灰 2022-05-22 06:52 150阅读 0赞

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

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

  1. #!/usr/local/bin/python
  2. # coding:utf-8
  3. import fileinput
  4. import time
  5. import os
  6. target_file = 'user.log'
  7. init_flag = True # 初次加载程序
  8. time_kick = 5
  9. record_count = 0
  10. while True:
  11. print '当前读到了', record_count
  12. #没有日志文件,等待
  13. if not os.path.exists(target_file):
  14. print 'target_file not exist'
  15. time.sleep(time_kick)
  16. continue
  17. try:
  18. ip = '10.10.1.100'
  19. easytime = time.strftime('%Y%m%d_%H%M%S', time.localtime())
  20. file_name = '%s_user_%s.log' % (ip,easytime)
  21. f_w = open(file_name, 'w')
  22. if init_flag:
  23. #读取整个文件
  24. for eachline in fileinput.input(target_file):
  25. print eachline
  26. f_w.write(eachline)
  27. record_count += 1
  28. init_flag = False
  29. else:
  30. #如果总行数小于当前行,那么认为文件更新了,从第一行开始读。
  31. total_count = os.popen('wc -l %s' % target_file).read().split()[0]
  32. total_count = int(total_count)
  33. if total_count < record_count:
  34. record_count = 0
  35. for eachline in fileinput.input(target_file):
  36. line_no = fileinput.filelineno()
  37. if line_no > record_count:
  38. print eachline
  39. f_w.write(eachline)
  40. record_count += 1
  41. f_w.close()
  42. except:
  43. pass
  44. time.sleep(time_kick)

发表评论

表情:
评论列表 (有 0 条评论,150人围观)

还没有评论,来说两句吧...

相关阅读

    相关 程序接入实时

    小程序上线后如果需要查看console日志是没有办法的,需要接入实时日志。如果是原生的小程序可根据官方文档《[实时日志][Link 1]》来操作。我自己的项目是事业`mpvue