如何使用Python3实时操作处理日志文件

其他教程   发布日期:2025年03月30日   浏览次数:340

这篇文章主要讲解了“如何使用Python3实时操作处理日志文件”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“如何使用Python3实时操作处理日志文件”吧!

一、简单的实时文件处理(单一文件)

假设我们要实时读取的日志的路径为: /data/mongodb/shard1/log/pg.csv

那么我们可以在python文件中使用shell脚本命令tail -F 进行实时读取并操作

代码如下:

  1. import re
  2. import codecs
  3. import subprocess
  4. def pg_data_to_elk():
  5. p = subprocess.Popen('tail -F /data/mongodb/shard1/log/pg.csv', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,) #起一个进程,执行shell命令
  6. while True:
  7. line = p.stdout.readline() #实时获取行
  8. if line: #如果行存在的话
  9. xxxxxxxxxxxx
  10. your operation

简单解释一下subprocess模块:

subprocess允许你生成新的进程,连接到它们的 input/output/error 管道,并获取它们的返回(状态)码。

subprocess.Popen介绍

该类用于在一个新的进程中执行一个子程序。

subprocess.Popen的构造函数

  1. class subprocess.Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None,
  2. preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=False,
  3. startup_info=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=())

参数说明:

  • args: 要执行的shell命令,可以是字符串,也可以是命令各个参数组成的序列。当该参数的值是一个字符串时,该命令的解释过程是与平台相关的,因此通常建议将args参数作为一个序列传递。

  • stdin, stdout, stderr: 分别表示程序标准输入、输出、错误句柄。

  • shell: 该参数用于标识是否使用shell作为要执行的程序,如果shell值为True,则建议将args参数作为一个字符串传递而不要作为一个序列传递。

二、复杂的实时文件处理(不断产生新文件)

如果日志会在满足一定条件下产生新的日志文件,比如log1.csv已经到了20M,那么则会写入log2.csv,这样一天下来大概有1000多个文件,且不断产生新的,那么如何进行实时获取呢?

思路如下:

在实时监听(tail -F)中加入当前文件的大小判定,如果当前文件大小大于20M,那么跳出实时监听,获取新的日志文件。(如果有其他判定条件也是这个思路,只不过把当前文件大小的判定换成你所需要的判定)

代码如下:

  1. import re
  2. import os
  3. import time
  4. import codecs
  5. import subprocess
  6. from datetime import datetime
  7. path = '/home/liao/python/csv'
  8. time_now_day = datetime.now.strftime('%Y-%m-%d')
  9. def get_file_size(new_file):
  10. fsize = os.path.getsize(new_file)
  11. fsize = fsize/float(1024*1024)
  12. return fsize
  13. def get_the_new_file():
  14. files = os.listdir(path)
  15. files_list = list(filter(lambda x:x[-4:]=='.csv' and x[11:21]==time_now_day, files))
  16. files_list.sort(key=lambda fn:os.path.getmtime(path + '/' + fn) if not os.path.isdir(path + '/' + fn) else 0)
  17. new_file = os.path.join(path, files_list[-1])
  18. return new_file
  19. def pg_data_to_elk():
  20. while True:
  21. new_file = get_the_new_file()
  22. p = subprocess.Popen('tail -F {0}'.format(new_file), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,) #起一个进程,执行shell命令
  23. while True:
  24. line = p.stdout.readline() #实时获取行
  25. if line: #如果行存在的话
  26. if get_file_size(new_file) > 20: #如果大于20M,则跳出循环
  27. break
  28. xxxxxxxxxxxx
  29. your operation
  30. time.sleep(3)

以上就是如何使用Python3实时操作处理日志文件的详细内容,更多关于如何使用Python3实时操作处理日志文件的资料请关注九品源码其它相关文章!