Nginx 流量统计分析

2023-05-16

目录

  • 程序简介
  • 输出结果
  • 环境
  • 程序要求
  • 例子
  • 代码

程序简介

通过分析nginx日志,统计出nginx流量(统计nginx日志中 $body_bytes_sent 字段),能自定义时间间隔,默认时间间隔为5分钟,单位为分钟。

输出结果

开始时间 结束时间 分割线 统计流量
2019-11-23 03:26:00 2019-11-23 04:26:00 <=> 2.04M
2019-11-23 04:27:43 2019-11-23 05:27:43 <
=> 895.05K
2019-11-23 05:28:25 2019-11-23 06:28:25 <=> 1.88M
2019-11-23 06:33:08 2019-11-23 07:33:08 <
=> 1.29M
2019-11-23 07:37:28 2019-11-23 08:37:28 <=========> 1.16M

环境

python3+
需要安装python argparse
目前只支持nginx 日志

程序要求

nginx日志格式要求,第四个字段为 [$time_local] 和 第7个字段为 $body_bytes_sent 或者 $bytes_sent

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent $request_time "$http_referer" '
                  '$host DIRECT/$upstream_addr $upstream_http_content_type '
                  '"$http_user_agent" "$http_x_forwarded_for"';

body_bytes_sent:发送给客户端的字节数,不包括响应头的大小

bytes_sent:发送给客户端的字节数
注意:nginx日志中间不能有空行,否则程序读取不到空行后面的日志

例子

# 分析 nginx access.log 日志,以 1小时 切割,统计每小时产生的流量
$ ./nginx_large_file_flow_analysis3.py -f /var/log/nginx/access.log -m 60

代码

#!/usr/bin/python3
#-*-coding=utf-8-*-

#-----------------------------------------------------------------------------
# 注意:日志中间不能有空行,否则程序读取不到空行后面的日志
#-----------------------------------------------------------------------------

import time
import os
import sys
import argparse

class displayFormat():
    def format_size(self, size):
        # 格式化流量单位
        KB = 1024  # KB -> B  B是字节
        MB = 1048576  # MB -> B
        GB = 1073741824  # GB -> B
        TB = 1099511627776  # TB -> B
        if size >= TB:
            size = str("%.2f" % (float(size / TB)) ) + 'T'
        elif size < KB:
            size = str(size) + 'B'
        elif size >= GB and size < TB:
            size = str("%.2f" % (float(size / GB))) + 'G'
        elif size >= MB and size < GB:
            size = str("%.2f" % (float(size / MB))) + 'M'
        else:
            size = str("%.2f" % (float(size / KB))) + 'K'
        return size

    def execut_time(self):
        # 输出脚本执行的时间
        print('\n')
        print("Script Execution Time: %.3f second" % time.clock())

class input_logfile_sort():
    # 内存优化
    __slots__ = ['read_logascii_dict', 'key']

    def __init__(self):
        self.read_logascii_dict = {}
        self.key = 1

    def logascii_sortetd(self, logfile):
        with open(logfile, 'r') as f:
            while 1:
                    list_line = f.readline().split()
                    try:
                        if not list_line:
                            break
                        timeArray = time.strptime(list_line[3].strip('['), "%d/%b/%Y:%H:%M:%S")
                        timeStamp_start = int(time.mktime(timeArray))
                        list_line1 = [timeStamp_start, list_line[9]]
                        # 生成字典
                        self.read_logascii_dict[self.key] = list_line1
                        self.key += 1
                    except ValueError:
                        continue
                    except IndexError:
                        continue
        sorted_list_ascii = sorted(self.read_logascii_dict.items(), key=lambda k: (k[1][0]))
        return sorted_list_ascii
        # out [(4, [1420686592, '1024321222']), (3, [1449544192, '10243211111'])]

class log_partition():
    display_format = displayFormat()
    def __init__(self):
        self.size1 = 0
        self.j = 0

    def time_format(self, time_stamps_start, time_stamps_end):
        time_start = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time_stamps_start))
        time_end = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time_stamps_end))
        print(time_start + ' -- ' + time_end + ' ' * 6 + '<=========>' + ' ' * 6 + self.display_format.format_size(self.size1))

    def log_pr(self, stored_log, times):
        time_stamps_start = stored_log[0][1][0]
        time_stamps_end = time_stamps_start + times
        lines = len(stored_log)
        for line in stored_log:
            self.j += 1
            if int(line[1][0]) <= time_stamps_end:
                try:
                    self.size1 = self.size1 + int(line[1][1])
                    if self.j == lines:
                        self.time_format(time_stamps_start, time_stamps_end)
                except ValueError:
                    continue
            else:
                try:
                    self.time_format(time_stamps_start, time_stamps_end)
                    self.size1 = 0
                    self.size1 = self.size1 + int(line[1][1])
                    time_stamps_start = int(line[1][0])
                    time_stamps_end = time_stamps_start + times
                    if self.j == lines:
                        self.time_format(time_stamps_start, time_stamps_end)
                except ValueError:
                    continue

class Main():
    #主调函数
    def main(self):
        parser = argparse.ArgumentParser(
            description="Nginx flow analysis, Supported file types ascii text.")
        parser.add_argument('-f', '--file',
                            dest='file',
                            nargs='?',
                            help="log file input.")
        parser.add_argument('-m', '--minute',
                            dest='minute',
                            default=5,
                            nargs='?',
                            type=int,
                            help="Nginx separation time,Default 5 min.")
        args = parser.parse_args()

        Input_sorted_log = input_logfile_sort()
        display_format1 = displayFormat()
        times = args.minute * 60
        for type in os.popen("""file {}""".format(args.file)):
            file_type = type.strip().split()[1]
        if file_type.lower() == 'ascii':
            logascii_analysis = log_partition()
            logascii_analysis.log_pr(Input_sorted_log.logascii_sortetd(args.file), times)
            print('\033[1;32;40m')
            display_format1.execut_time()
            print('\033[0m')
        else:
            print('\033[1;32;40m')
            print("Supported file types ascii text.")
            print("Example: python3 {} -f nginxlogfile -m time".format(sys.argv[0]))
            print('\033[0m')

if __name__ == '__main__':
    main_obj = Main()
    main_obj.main()

转载自:https://www.yp14.cn/2019/11/23/Nginx-%E6%B5%81%E9%87%8F%E7%BB%9F%E8%AE%A1%E5%88%86%E6%9E%90/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Nginx 流量统计分析 的相关文章

随机推荐

  • java中用FTPClient,执行到ftp.storeFile(fileName, inputFile);无反应

    package com aa test import cn hutool core util StrUtil import com nuctech platform tip constant TipConstant import lombo
  • SpringMVC拦截去之HandlerInterceptorAdapter的使用

    定义 HandlerInterceptorAdapter是SpringMVC中的拦截器 xff0c 它是用于拦截URL请求的 xff0c 主要是为了请求的预处理和后续处理 使用方法 编写代码 我们只需要自定义一个拦截器去继承HandlerI
  • EKF之雅克比矩阵(一)

    扩展卡尔曼滤波 EKF EKF之雅克比矩阵 文章目录 扩展卡尔曼滤波 EKF 前言一 什么是线性化 xff1f 二 雅克比矩阵1 矩阵的几何含义2 非线性矩阵与基底的关系3 雅克比矩阵 三 工程中雅克比矩阵如何应用总结 前言 一般的卡尔曼滤
  • Java数据结构与算法-程序员十大常用算法[day13]

    程序员十大常用算法 文章目录 程序员十大常用算法二分查找算法 非递归 分治算法分治算法最佳实践 汉诺塔 动态规划算法KMP算法KMP算法简介KMP实现 贪心算法普利姆算法克鲁斯卡尔算法分析克鲁斯卡尔算法分析 迪杰斯特拉算法弗洛伊德算法回溯算
  • SNMP测试

    SNMP测试 测试环境 xff1a Solaris10 10 10 128 89 Linux xff1a 10 10 151 8 windows 测试方案 xff1a 1 本地测试 2 远程测试 配置文件 xff1a 修改环境变量 在sol
  • apex编译错误解决方案

    这里写自定义目录标题 apex编译错误解决方案 csrc mlp cpp 123 3 note in expansion of macro AT DISPATCH FLOATING TYPES AND HALF AT DISPATCH FL
  • Javaweb项目实践MVC入门到精通

    Javaweb项目实践MVC入门到精通 目标配置环境实体模型 user Dao的实现实体模型 ModelViewController xff1a 转发任务 xff0c 路由器的功能安全sql注入常见问题 目标 这个目标是写一个MVC模型 通
  • C++ 铪铪铪铪 烫烫烫 屯屯屯

    VS中 xff0c Debug模式下 xff0c 对于未初始化的内存 xff1a 1 xff09 若为栈内存 xff0c 默认为一连串 烫烫烫 xff0c 0xcc 2 xff09 若为堆内存 xff0c 默认为一连串 屯屯屯 xff0c
  • git常用操作命令

    目录 git删除push到远程服务器的commit用户名和邮箱撤销add操作commit message写错了删除已经上传的文件添加文件追踪 git删除push到远程服务器的commit span class token comment 会
  • 魔方矩阵

    看到魔方矩阵 xff0c 好奇 xff0c 好玩儿 xff0c 正好赶上周五 xff0c 就来放松一下 xff0c 总结一下几种魔方矩阵的规律 xff0c 并写一下C 43 43 实现过程 定义 xff1a 平面魔方的一般定义 xff1a
  • 样条插值曲线类型及其优缺点说明

    Spline Types This page gives a breakdown of each spline type how to use each one and the advantages disadvantages of eac
  • caffe layer层详解

    1 基本的layer定义 xff0c 参数 1 基本的layer定义 xff0c 参数 如何利用caffe定义一个网络 xff0c 首先要了解caffe中的基本接口 xff0c 下面分别对五类layer进行介绍 Vision Layers
  • caffe编译中的python问题

    问题 usr include boost python detail wrap python hpp 50 23 fatal error pyconfig h No such file or directory 解决方案 make clea
  • latex图像注释位置

    latex图像注释的位置在左边 不知道谁把模板里的 usepackage caption 给注释掉了
  • pytorch pretrained model

    pytorch pretrained model two methods method 1 比较大小 self span class token punctuation span model span class token operato
  • nodejs之minimist中间件使用

    minimist是nodejs的命令行参数解析工具 xff0c 因其简单好用 xff0c 轻量等特性 xff0c 所以用户使用较多 特性 xff1a short options long options Boolean 和 Number类型
  • RNA-seq 保姆教程:差异表达分析(一)

    介绍 RNA seq 目前是测量细胞反应的最突出的方法之一 RNA seq 不仅能够分析样本之间基因表达的差异 xff0c 还可以发现新的亚型并分析 SNP 变异 本教程 1 将涵盖处理和分析差异基因表达数据的基本工作流程 xff0c 旨在
  • 腾讯、阿里云服务器安装java全流程(yum安装java超简单详细版)

    有些服务器中自带了java xff0c 但不是你想要的版本的话 xff0c 可以先卸载掉 xff0c 然后更换想要的ava版本 因为是有网环境 xff0c 可以使用yum安装 无网环境可以参考我写的另一篇文章 xff1a linux无网环境
  • 某个牛人做WINDOWS系统文件详解

    某个牛人做WINDOWS系统文件详解 超牛 很详细介绍WINDOWS系统文件用途 想各位保存一份以后说定会有用 A ACCESS CHM Windows帮助文件 ACCSTAT EXE 辅助状态指示器 ADVAPI32 DLL 高级Win3
  • Nginx 流量统计分析

    目录 程序简介输出结果环境程序要求例子代码 程序简介 通过分析nginx日志 xff0c 统计出nginx流量 xff08 统计nginx日志中 body bytes sent 字段 xff09 xff0c 能自定义时间间隔 xff0c 默