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

Oracle监听日志分析

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

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()

相关推荐

高效有趣学Excel:从入门到精通的全面教程分享

在当今这个数据驱动的时代,掌握Excel不仅是提升工作效率的利器,更是职场竞争中的一项重要技能。今天,我非常高兴地与大家分享一套全面的Excel学习教程——《高效有趣学Excel:轻松入门到精通》,这...

Excel新函数重磅来袭!告别复杂公式,效率提升200%!

“透视表终于不用点来点去了?”昨晚刷到这条留言,顺手把新表扔进365,一行=GROUPBY(部门,产品,销售额,SUM)回车,三秒出汇总,刷新按钮直接失业。那一刻,办公室空调声都显得多余。有人还在录宏...

Excel 效率神器:LET 函数入门教程,让复杂公式变简单

您是否曾经编写过又长又复杂的Excel公式,然后没过几天自己都看不懂了?或者,同一个计算在公式里重复写了无数次,不仅容易出错,修改起来更是噩梦?Excel推出的LET函数就是来解决这些痛点...

Excel多对多查询函数新手教程:从案例到实操

一、为啥要学多对多查询?举个例子你就懂!假设你是公司HR,手里有张员工技能表(如下),现在需要快速找出:"张三"会哪些技能?"Excel"技能有哪些人掌握?员工姓名...

14、VBA代码+excel内置函数,实现高效数据处理(零基础入门)

1、学习VBA的主要目的是数据处理,VBA在数据处理上展现出强大的计算实力。它不仅完美继承EXCEl内置函数的功能,还能通过编程语法实现更灵活的应用。无论是基础的加减乘除,还是复杂的统计分析、逻辑判断...

word和excel零基础学习免费视频教程,赶紧收藏,作者将转付费课

亲爱的朋友们:大家好!本人是全国计算机等级考试二级MSoffice高级应用课程的在校授课老师。本人近段时间打算将wore/excel免费分享给所有有需要的朋友。知识本身无深浅,本人知识也有限,如果讲...

excel函数从入门到精通,5组13个函数,易学易懂易用

对于职场中经常使用Excel的小伙伴们,最希望掌握一些函数公式,毕竟给数据处理带来很多方便,可以提高我们的工作效率。今天分享几组函数公式,适合于初学者,也是职场中经常用到的,下次碰到可以直接套用了。0...

Excel效率神器:LET函数入门教程,让复杂公式变简单

写公式写到想砸电脑?教你用LET把Excel公式从“迷宫”变成“小剧本”,几步看懂又好改很多人都经历过这样的窘境:花了半小时写出一条看似厉害的Excel公式,几天后再看自己都懵了,或者同样...

完全免费的Excel教程大全,适合日常excel办公和技能提升

说明微软官方的excel文档,由于网站在国外,有时打开慢,而且应用层面介绍不够详细;这里介绍一个集齐了excel各种使用方法和说明的网站;网站名称:懒人Excel网站介绍可以看到有基础教程、快捷键、函...

Excel 新函数 LAMBDA 入门级教程_excel365新增函数

LAMBDA函数的出现是Excel历史上的一次革命性飞跃。它允许用户自定义函数,而无需学习VBA等编程语言。这意味着你可以将复杂的、重复的计算逻辑封装成一个简单的、可复用的自定义函数,极大地...

Excel新函数LAMBDA入门级教程_excel新建函数

把复杂公式“变成函数”后,我在Excel上的重复工作少了一半——你也能做到我一直有一个习惯:遇到每天要重复写的复杂公式,就想把它封装起来,像调用内置函数那样去用。说实话,过去没有LAMBDA,这个想法...

Excel DROP 函数全方位教程:从基础入门到高级动态应用

上一篇我们学习了ExcelTAKE函数,今天我们来学习一下和TAKE函数相对应的DROP函数,它是Microsoft365和Excel2021中引入的一个动态数组函数。它的核心功能是从一...

学习Excel公式函数还有官方提供的教程,还是免费的!赶紧试试

首先声明,这不是广告,纯干货分享!除了学习Excel的基本操作之外,很多人都是冲着公式和函数才去找教程买教材的,这个结论应该不会有什么毛病。因为,Excel的公式函数真的很强大!现在的Excel教程可...

什么是保险员常说的“IRR”?让我们一次说明白!

买保险的时候,你是不是常听到销售抛出一些术语,比如“IRR很高哦,收益不错!”?听着挺专业,但“IRR”到底啥意思?想问又不好意思问,别急,它其实是个很简单的概念,咱们今天一次把它说明白。1,IRR...

理财型保险如何选择缴费期?_理财型保险计算方式

选择理财型保险(通常指年金险、增额终身寿险等)的缴费期,并非简单地看哪个年限短或长,而是需要结合自己的财务状况、理财目标和产品特性来综合决定。下面我将为大家详细解析不同缴费期的特点、适用人群和选择策略...