百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

Oracle监听日志分析

moboyou 2025-04-09 13:40 59 浏览

1.把监听日志和脚本放到一个目录

yuyuz-mac:analyze-listenerlog yuyuz$ pwd
/Users/yuyuz/python/analyze-listenerlog
yuyuz-mac:analyze-listenerlog yuyuz$ ls
listener.log	lsnrlog.py

2.执行脚本

yuyuz-mac:analyze-listenerlog yuyuz$ python lsnrlog.py 
提取到的成功时间戳数量: 1920
提取到的失败时间戳数量: 15081
提取到的总时间戳数量: 17001
HTML 文件生成成功
yuyuz-mac:analyze-listenerlog yuyuz$ ls
connection_analysis.html	listener.log			lsnrlog.py

3.查看结果

支持区域放大/查看数据/线图柱图切换

4.代码

import re
from datetime import datetime
from pyecharts import options as opts
from pyecharts.charts import Line, Page


def parse_log(log_text):
    """
    解析日志文本,提取包含CONNECT_DATA字段行的时间戳、SERVICE、HOST和IP,并区分成功和失败连接
    :param log_text: 日志文本
    :return: 成功时间戳列表、失败时间戳列表、总时间戳列表、SERVICE信息列表、HOST信息列表、IP信息列表
    """
    success_timestamps = []
    failure_timestamps = []
    total_timestamps = []
    services = []
    hosts = []
    ips = []
    pattern = r'(\d{2}-[A-Z]{3}-\d{4} \d{2}:\d{2}:\d{2})|(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})'
    service_pattern = r'SERVICE_NAME=(\w+)'
    host_pattern = r'HOST=(\w+)'
    ip_pattern = r'HOST=(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'

    for line in log_text.split('\n'):
        if 'CONNECT_DATA' in line:
            match = re.search(pattern, line)
            if match:
                timestamp_str = match.group(0)
                try:
                    if '-' in timestamp_str[0:3]:
                        timestamp = datetime.strptime(timestamp_str, '%d-%b-%Y %H:%M:%S')
                    else:
                        timestamp = datetime.strptime(timestamp_str, '%Y-%m-%dT%H:%M:%S')
                    total_timestamps.append(timestamp)
                    if line.strip().endswith('0'):
                        success_timestamps.append(timestamp)
                    else:
                        failure_timestamps.append(timestamp)

                    service_match = re.search(service_pattern, line)
                    host_match = re.search(host_pattern, line)
                    ip_match = re.search(ip_pattern, line)

                    service = service_match.group(1) if service_match else None
                    host = host_match.group(1) if host_match else None
                    ip = ip_match.group(1) if ip_match else None

                    services.append((timestamp, service))
                    hosts.append((timestamp, host))
                    ips.append((timestamp, ip))
                except ValueError:
                    print(f"无法解析时间戳: {timestamp_str}")
    print(f"提取到的成功时间戳数量: {len(success_timestamps)}")
    print(f"提取到的失败时间戳数量: {len(failure_timestamps)}")
    print(f"提取到的总时间戳数量: {len(total_timestamps)}")
    return success_timestamps, failure_timestamps, total_timestamps, services, hosts, ips


def count_connections(timestamps, interval):
    """
    统计不同时间间隔的连接数
    :param timestamps: 时间戳列表
    :param interval: 时间间隔,如 'H' 表示小时,'T' 表示分钟,'S' 表示秒
    :return: 时间间隔和对应的连接数
    """
    counts = {}
    for timestamp in timestamps:
        if interval == 'H':
            key = timestamp.replace(minute=0, second=0, microsecond=0).strftime('%Y-%m-%d %H:00:00')
        elif interval == 'T':
            key = timestamp.replace(second=0, microsecond=0).strftime('%Y-%m-%d %H:%M:00')
        elif interval == 'S':
            key = timestamp.replace(microsecond=0).strftime('%Y-%m-%d %H:%M:%S')
        if key in counts:
            counts[key] += 1
        else:
            counts[key] = 1
    return sorted(counts.items())


def count_by_attribute(data, interval, attribute):
    """
    按指定属性统计不同时间间隔的连接数
    :param data: 包含时间戳和属性的元组列表
    :param interval: 时间间隔,如 'H' 表示小时,'T' 表示分钟,'S' 表示秒
    :param attribute: 属性名称
    :return: 以属性为键,时间间隔和对应连接数为值的字典
    """
    counts = {}
    for timestamp, attr in data:
        if attr is None:
            continue
        if interval == 'H':
            key = timestamp.replace(minute=0, second=0, microsecond=0).strftime('%Y-%m-%d %H:00:00')
        elif interval == 'T':
            key = timestamp.replace(second=0, microsecond=0).strftime('%Y-%m-%d %H:%M:00')
        elif interval == 'S':
            key = timestamp.replace(microsecond=0).strftime('%Y-%m-%d %H:%M:%S')
        if attr not in counts:
            counts[attr] = {}
        if key in counts[attr]:
            counts[attr][key] += 1
        else:
            counts[attr][key] = 1
    for attr in counts:
        counts[attr] = sorted(counts[attr].items())
    return counts


def create_line_chart(success_data, failure_data, total_data, interval):
    """
    创建线图
    :param success_data: 成功连接的时间间隔和对应的连接数
    :param failure_data: 失败连接的时间间隔和对应的连接数
    :param total_data: 总连接的时间间隔和对应的连接数
    :param interval: 时间间隔,如 '小时','分钟','秒'
    :return: 线图对象
    """
    x_data = sorted(set([item[0] for item in success_data + failure_data + total_data]))
    success_y_data = [next((item[1] for item in success_data if item[0] == x), 0) for x in x_data]
    failure_y_data = [next((item[1] for item in failure_data if item[0] == x), 0) for x in x_data]
    total_y_data = [next((item[1] for item in total_data if item[0] == x), 0) for x in x_data]

    line = (
        Line(init_opts=opts.InitOpts(bg_color="#f5f5f5", width="100%"))
        .add_xaxis(x_data)
        .add_yaxis(
            series_name=f"成功连接总数/{interval}",
            y_axis=success_y_data,
            label_opts=opts.LabelOpts(is_show=False),
            linestyle_opts=opts.LineStyleOpts(width=2, color="#228B22"),
            symbol="circle",
            symbol_size=6,
            itemstyle_opts=opts.ItemStyleOpts(color="#228B22")
        )
        .add_yaxis(
            series_name=f"失败连接总数/{interval}",
            y_axis=failure_y_data,
            label_opts=opts.LabelOpts(is_show=False),
            linestyle_opts=opts.LineStyleOpts(width=2, color="#FF0000"),
            symbol="circle",
            symbol_size=6,
            itemstyle_opts=opts.ItemStyleOpts(color="#FF0000")
        )
        .add_yaxis(
            series_name=f"总连接数/{interval}",
            y_axis=total_y_data,
            label_opts=opts.LabelOpts(is_show=False),
            linestyle_opts=opts.LineStyleOpts(width=2, color="#FF6347"),
            symbol="circle",
            symbol_size=6,
            itemstyle_opts=opts.ItemStyleOpts(color="#FF6347")
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(
                title=f"连接情况统计/{interval}",
                title_textstyle_opts=opts.TextStyleOpts(font_size=20, color="#333")
            ),
            toolbox_opts=opts.ToolboxOpts(is_show=True),
            xaxis_opts=opts.AxisOpts(
                name=interval,
                axislabel_opts=opts.LabelOpts(rotate=45, font_size=12, color="#666"),
                name_textstyle_opts=opts.TextStyleOpts(font_size=14, color="#333")
            ),
            yaxis_opts=opts.AxisOpts(
                name="连接数",
                axislabel_opts=opts.LabelOpts(font_size=12, color="#666"),
                name_textstyle_opts=opts.TextStyleOpts(font_size=14, color="#333")
            ),
            tooltip_opts=opts.TooltipOpts(trigger="axis"),
            legend_opts=opts.LegendOpts(
                type_="scroll",
                orient="vertical",
                pos_left="right",
                pos_top="middle",
                textstyle_opts=opts.TextStyleOpts(font_size=8, color="#333")
            )
        )
    )
    return line


def create_attribute_line_chart(counts, interval, attribute):
    """
    创建按属性统计的线图
    :param counts: 以属性为键,时间间隔和对应连接数为值的字典
    :param interval: 时间间隔,如 '小时','分钟','秒'
    :param attribute: 属性名称
    :return: 线图对象
    """
    all_x_data = set()
    for data in counts.values():
        for x, _ in data:
            all_x_data.add(x)
    x_data = sorted(all_x_data)

    line = Line(init_opts=opts.InitOpts(bg_color="#f5f5f5", width="100%"))
    line.add_xaxis(x_data)

    for attr, data in counts.items():
        y_data = [next((item[1] for item in data if item[0] == x), 0) for x in x_data]
        line.add_yaxis(
            series_name=f"{attr}/{interval}",
            y_axis=y_data,
            label_opts=opts.LabelOpts(is_show=False),
            linestyle_opts=opts.LineStyleOpts(width=2),
            symbol="circle",
            symbol_size=6
        )

    line.set_global_opts(
        title_opts=opts.TitleOpts(
            title=f"{attribute} 连接情况统计/{interval}",
            title_textstyle_opts=opts.TextStyleOpts(font_size=20, color="#333")
        ),
        toolbox_opts=opts.ToolboxOpts(is_show=True),
        xaxis_opts=opts.AxisOpts(
            name=interval,
            axislabel_opts=opts.LabelOpts(rotate=45, font_size=12, color="#666"),
            name_textstyle_opts=opts.TextStyleOpts(font_size=14, color="#333")
        ),
        yaxis_opts=opts.AxisOpts(
            name="连接数",
            axislabel_opts=opts.LabelOpts(font_size=12, color="#666"),
            name_textstyle_opts=opts.TextStyleOpts(font_size=14, color="#333")
        ),
        tooltip_opts=opts.TooltipOpts(trigger="axis"),
        legend_opts=opts.LegendOpts(
            type_="scroll",
            orient="vertical",
            pos_left="right",
            pos_top="middle",
            textstyle_opts=opts.TextStyleOpts(font_size=8, color="#333")
        )
    )
    return line


def main():
    """
    主函数,从文件读取日志并生成包含多个线图的网页
    """
    try:
        with open('listener.log', 'r', encoding='utf-8') as file:
            log_text = file.read()
        success_timestamps, failure_timestamps, total_timestamps, services, hosts, ips = parse_log(log_text)

        # 统计每小时、每分钟、每秒的成功、失败和总连接数
        intervals = ['H', 'T', 'S']
        interval_names = ['小时', '分钟', '秒']
        page = Page()

        for interval, interval_name in zip(intervals, interval_names):
            hourly_success_data = count_connections(success_timestamps, interval)
            hourly_failure_data = count_connections(failure_timestamps, interval)
            hourly_total_data = count_connections(total_timestamps, interval)
            hourly_chart = create_line_chart(hourly_success_data, hourly_failure_data, hourly_total_data, interval_name)
            page.add(hourly_chart)

        # 按SERVICE、HOST、IP统计并绘制线图
        attributes = [('SERVICE', services), ('HOST', hosts), ('IP', ips)]
        for attribute_name, attribute_data in attributes:
            for interval, interval_name in zip(intervals, interval_names):
                counts = count_by_attribute(attribute_data, interval, attribute_name)
                chart = create_attribute_line_chart(counts, interval_name, attribute_name)
                page.add(chart)

        page.render("connection_analysis.html")

        # 添加版权信息到 HTML 文件
        copyright_info = '
声明:仅用作兴趣爱好和测试使用,请勿商用,不承担任何商业责任。--张宇--
' with open('connection_analysis.html', 'a', encoding='utf-8') as f: f.write(copyright_info) print("HTML 文件生成成功") except FileNotFoundError: print("未找到 listener.log 文件,请确保文件存在。") except Exception as e: print(f"发生错误: {e}") if __name__ == "__main__": main()

相关推荐

python新手学习常见数据类型——数字

Python支持三种不同的数值类型:整型(int)、浮点型(float)、复数(complex)创建数字:a=1b=2.7c=8+4j删除数字:a=1b=2.7c=8+4...

只用一个套路公式,给 Excel 中一列人员设置随机出场顺序

很多同学会觉得Excel单个案例讲解有些碎片化,初学者未必能完全理解和掌握。不少同学都希望有一套完整的图文教学,从最基础的概念开始,一步步由简入繁、从入门到精通,系统化地讲解Excel的各个知...

Excel神技 TIME函数:3秒搞定时间拼接!职场人必学的效率秘籍

你是否经常需要在Excel中手动输入时间,或者从不同单元格拼接时、分、秒?今天我要揭秘一个超实用的Excel函数——TIME函数,它能让你3秒内生成标准时间格式,彻底告别繁琐操作!一、TIME函数基础...

销售算错数被批?97 Excel 数字函数救场,3 步搞定复杂计算

销售部小张被老板当着全部门骂。上季度销售额汇总,他把38652.78算成36852.78,差了1800块。财务对账时发现,整个部门的提成表都得重算。"连个数都算不对,还做什么销售?&...

如何使用Minitab 1分钟生成所需要的SPC数据

打开Minitab,“计算”-“随机数据”-“正太”,因为不好截图,使用的是拍照记录的方式.再要生产的行数中,填写125,可以按照要求,有些客户要求的是100个数据,就可以填写100...

验证码,除了 12306,我还没有服过谁

为了防止暴力注册或爬虫爬取等机器请求,需要验证操作者是人还是机器,便有了验证码这个设计。本文作者主要介绍了如何使用Axure来设计一个动态的图形验证码,一起来学习一下吧。在软件设计中,为了防止暴力...

零基础也能学会的9个Excel函数,小白进阶必备

今天给大家分享一些常用的函数公式,可以有效地解决Excel中办公所需,0基础也可以轻松学会。建议收藏,在需要的时候可以直接套用函数。1、计算排名根据总和,计算学生成绩排名。函数公式=RANK(E2,$...

[office] excel表格数值如何设置_excel表格怎样设置数值

excel表格数值如何设置  因为电子表格应用程序是用来处理数值数据的,所以数值格式可能是工作表中最关键的部分,格式化数值数据的方式由用户决定,但在每个工作簿的工作表之间应使用一致的处理数字的方法。...

Excel最常用的5个函数!会用最后一个才是高手

是不是在处理Excel数据时,面对繁琐的操作烦恼不已?手动操作不仅耗时费力,还容易出错。别担心,表姐这就为你揭秘Excel中几个超实用的函数,让数据处理变得轻松高效!表姐整理了552页《Office从...

新手必会的53个Excel函数_惊呆小伙伴的全套excel函数技能

(新手入门+进阶+新函数)一、新手入门级(24个)1、Sum函数:求和=Sum(区域)2、Average函数:求平均值=Average(区域)3、Count函数:数字个数=Count(区域)4、Cou...

打工人私藏的4个Excel函数秘籍,效率提升3.7%

小伙伴们好啊,今天咱们分享几个常用函数公式的典型应用。合并内容如下图,希望将B列的姓名,按照不同部门合并到一个单元格里。=TEXTJOIN(",",1,IF(A$2:A$15=D2,B...

Excel偷偷更新的8个函数!原来高手都在用这些隐藏技能

领导突然要销售数据,你手忙脚乱筛选到眼花...同事3分钟搞定的报表,你折腾半小时还在填充公式...明明用了VLOOKUP,却总显示#N/A错误...别慌!今天教你的8个动态数组函数,就像给Excel装...

Excel表格随机函数怎么用?讲解三种随机函数在不同场景的应用

excel随机函数,其特点是能够生成一组随机数字,根据不同需求,还能批量生成小数位和整数,及指定行数和列数,或指定区间范围内的数字。这里根据需求,作者设置了三个问题,第1个是随机生成0至1之间的数字...

单纯随机抽样该如何进行?_单纯随机抽样的适用范围及注意事项

在数据分析中,抽样是指从全部数据中选择部分数据进行分析,以发掘更大规模数据集中的有用信息。在收集数据过程中,绝大多数情况下,并不采取普查的方式获取总体中所有样本的数据信息,而是以各类抽样方法抽取其中若...

随机函数在Excel中的应用_随机函数在excel中的应用实例

【分享成果,随喜正能量】职场,如果你没有价值,那么你随时可能被取代;如果你的价值不如别人,那么社会也不会惯你,你将被无情地淘汰掉。不管什么时候,你一定要学会构建自己的价值。每个人都应该思考这个问题:我...