Python 实时获取任务请求对应的Nginx日志的方法

栗子
栗子
发布时间:2026-10-14| 5人浏览过
原创

本文介绍如何利用Python自动化获取Nginx访问日志以判断任务执行状态。通过结合subprocess调用tail命令与多线程机制,实时捕获特定特征内容。文中详细分析了直接grep过滤无法获取日志的原因,并针对proc.communicate超时及timeout参数设置过小导致的二次获取失败问题提供了实践建议,旨在提升运维与测试效率。

需求描述

在项目需求的测试环节中,需要向Nginx服务器发送各类用例请求,随后查看对应的Nginx日志,判断是否存在特征内容,以此来判断任务是否执行成功。为了提升效率,需要将这一过程实现自动化。

实践环境

Python 3.6.5

代码设计与实现


#!/usr/bin/env python
# -*- coding:utf-8 -*-


'''
@CreateTime: 2021/06/26 9:05
@Author : shouke
'''


import time
import threading
import subprocess
from collections import deque


def collect_nginx_log():
    global nginx_log_queue
    global is_tasks_compete
    global task_status


    args = 'tail -0f /usr/local/openresty/nginx/logs/access.log'
    while task_status != 'req_log_got':
        with subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, universal_newlines = True) as proc:
            log_for_req = ''
            outs, errs = '', ''

            try:
                outs, errs = proc.communicate(timeout=2)
            except subprocess.TimeoutExpired:
                print('获取nginx日志超时,正在重试')
                proc.kill()
                try:
                    outs, errs = proc.communicate(timeout=5)
                except subprocess.TimeoutExpired:
                    print('获取nginx日志超时,再次超时,停止重试')
                    break
            finally:
                for line in outs.split('\n'):
                    flag = '\"client_ip\":\"10.118.0.77\"' # 特征
                    if flag in line: # 查找包含特征内容的日志
                        log_for_req += line

                if task_status == 'req_finished':
                    nginx_log_queue.append(log_for_req)
                    task_status = 'req_log_got'



def run_tasks(task_list):
    '''
    运行任务
    :param task_list 任务列表
    '''

    global nginx_log_queue
    global is_tasks_compete
    global task_status


    for task in task_list:
        thread = threading.Thread(target=collect_nginx_log,
                                    name="collect_nginx_log")
        thread.start()
        time.sleep(1) # 执行任务前,让收集日志线程先做好准备

        print('正在执行任务:%s' % task.get('name'))

        # 执行Nginx任务请求
        # ...

        task_status = 'req_finished'
        time_to_wait = 0.1
        while task_status != 'req_log_got': # 请求触发的nginx日志收集未完成
            time.sleep(time_to_wait)
            time_to_wait += 0.01
        else:# 获取到用例请求触发的nginx日志
            if nginx_log_queue:
                nginx_log = nginx_log_queue.popleft()
                task_status = 'req_ready'
                # 解析日志
                # do something here
                # ...
            else:
                print('存储请求日志的队列为空')
                # do something here
                # ...


if __name__ == '__main__':
    nginx_log_queue = deque()
    is_tasks_compete = False # 所有任务是否执行完成

    task_status = 'req_ready' # req_ready,req_finished,req_log_got  # 存放执行次任务任务的一些状态
    print('###########################任务开始###########################')

    tast_list = [{'name':'test_task', 'other':'...'}]
    run_tasks(tast_list)

    is_tasks_compete = True

    current_active_thread_num = len(threading.enumerate())
    while current_active_thread_num != 1:
        time.sleep(2)
        current_active_thread_num = len(threading.enumerate())
    print('###########################任务完成###########################')

注意:

1、上述代码为啥不一步到位,直接 tail -0f /usr/local/openresty/nginx/logs/access.log | grep "特征内容"呢?这是因为这样做无法获取到Nginx的日志

2、实践时发现,第一次执行proc.communicate(timeout=2)获取日志时,总是无法获取,会超时,需要二次获取,并且timeout设置太小时(实践时尝试过设置为1秒),也会导致第二次执行时无法获取Nginx日志。

到此这篇关于Python 实时获取任务请求对应的Nginx日志的文章就介绍到这了,更多相关Python获取Nginx日志内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。