栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python获取nginx日志信息

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python获取nginx日志信息

简介:项目中需要进行对nginx的信息做一些监控和获取,需求内容有:统计访问量、统计接口请求量、异常状态请求量,并嵌入至夜莺监控系统中,通过夜莺监控大盘展示出来。如果大家用不到夜莺,我已经把监控内容也都输出到了一个日志文件当中了,大家可以自行进行监控或处理

配置文件config.py

#!encoding=utf-8
'''
    作者:陈浩
    更新日期:2022.5.5
    名称:配置nginx路径
'''

#配置access日志的绝对路径
access = '/usr/local/nginx/logs/access.log'

代码:analyse_nginx.py

#!/usr/bin/python3
#!encoding=utf-8
'''
    作者:陈浩
    更新日期:2022.5.6
    名称:采集nginx相关信息
'''

import os
import os.path
import config
import traceback
import logging
import sys

logging.basicConfig(level=logging.DEBUG, filename=os.path.abspath(os.path.dirname(__file__)) + '/nginx.log',
                    filemode='a', format='%(asctime)s - %(levelname)s: %(message)s')
class Analyse:
    """采集nginx日志并获取其相关信息的类"""
    def __init__(self, Path, access):
        '''初始化nginx日志的方法'''
        try:
            self.Path = os.path.dirname(Path)
            self.access = os.path.getsize(access)
            self.access_path = access
            logging.info("初始化{}目录".format(self.Path))
        except Exception as e:
            logging.error("路径{}错误或不存在,请检查".format(access))

        if self.access > 10737418240:
            logging.error("access日志体积过大,为了保证服务器的正常运行,python将无法为您分析")
            logging.error("当前access.log日志大小为:{}G,最大限制为10G".format(self.access / 1024 / 1024 / 1024))
            sys.exit()
        else:
            logging.info("初始化{0}日志文件,当前日志大小为{1}b".format(access, self.access))

    def execute_time(func):
        from time import time
        def wrapper(*args, **kwargs):
            start = time()
            func_return = func(*args, **kwargs)
            end = time()
            logging.warning(f'{func.__name__}()方法执行的时间为: {end - start}s')
            return func_return
        return wrapper

    @execute_time
    def get_ipUV(self):
        '''统计访问量'''
        logging.info("进入'统计访问量'的方法")
        try:
            data = []
            with open(self.access_path, 'r') as access_logs:
                for access_log in access_logs:
                    data.append(access_log.split()[0])
            ipUV = len(set(data))
            logging.warning("已采集--监控项名称:【统计IP访问量个数】 采集的nginx路径:'{0}' IP个数:{1}".format(self.access_path, ipUV))
            print('nginx_analyse,access="{0}" ipuv={1}'.format(self.access_path, ipUV))
        except Exception as e:
            logging.error("执行统计访问量方法报错n%s"%traceback.format_exc())

    @execute_time
    def get_api(self):
        '''统计接口'''
        logging.info("进入'统计接口请求'的方法")
        try:
            datas = []
            with open(self.access_path, 'r') as access_logs:
                for access_log in access_logs:
                    datas.append(access_log.split()[6])
            data_get = []
            data_post = []
            for data in datas:
                if '"GET' in data:
                    data_get.append(data)
                elif '"POST' in data:
                    data_post.append(data)
            logging.warning("已采集---监控项名称:【接口的get请求量与post请求量】 采集的nginx日志路径:'{0}' GET请求量:{1}".format(self.access_path, len(data_get)))
            logging.warning("已采集---监控项名称:【接口的get请求量与post请求量】 采集的nginx日志路径:'{0}' POST请求量:{1}".format(self.access_path, len(data_post)))
            print('nginx_analyse,access="{0}" get={1}'.format(self.access_path, len(data_get)))
            print('nginx_analyse,access="{0}" post={1}'.format(self.access_path, len(data_post)))
        except Exception as e:
            logging.error("执行统计接口请求方法报错n%s"%traceback.format_exc())

    @execute_time
    def get_error(self):
        '''异常统计'''
        logging.info("进入'异常统计'的方法")
        try:
            datas = []
            with open(self.access_path, 'r') as access_logs:
                for access_log in access_logs:
                    datas.append(access_log.split()[10])
            error_data = []
            for error in datas:
                if error > '400':
                    error_data.append(error)
            logging.warning("已采集---监控项名称:【异常统计】 采集的nginx日志路径:'{0}' 异常出现的次数(包含400、403、404、500、502、503):{1}".format(
                    self.access_path, len(error_data)))
            print('nginx_analyse,access="{0}" error={1}'.format(self.access_path, len(error_data)))
        except Exception as e:
            logging.error("执行异常统计的方法报错n%s"%traceback.format_exc())

if __name__ == '__main__':
    '''主程序'''
    analyse = Analyse(config.access, config.access)
    analyse.get_ipUV()
    analyse.get_api()
    analyse.get_error()

运行方式:立即运行或者使用shell中的while定时执行都可以

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/932278.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号