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

发布时间:2023-04-21 17:33:13 作者:iii
来源:亿速云 阅读:102

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

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

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

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

代码如下:

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

简单解释一下subprocess模块:

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

subprocess.Popen介绍

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

subprocess.Popen的构造函数

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

参数说明:

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

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

思路如下:

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

代码如下:

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

感谢各位的阅读,以上就是“如何使用Python3实时操作处理日志文件”的内容了,经过本文的学习后,相信大家对如何使用Python3实时操作处理日志文件这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

推荐阅读:
  1. Python3 对文件操作
  2. Python3 日志模块

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python3

上一篇:如何使用Python的pyttsx3库将文字转为音频

下一篇:Python怎么快速入门

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》