Oracle监听日志分析
moboyou 2025-04-09 13:40 47 浏览
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()
- 上一篇:数据库中常用的数值函数
- 下一篇:DTrace 和 strace 概述
相关推荐
- 【开源推荐】给大家推荐个基于ChatGPT的PHP开发库 openai-php-api
-
有了这个库大家就可以愉快的使用PHP对接chatGPT的官方接口了,至于对接了官方接口想要做什么就看你自己的啦环境要求PHP7.4或以上composer1.6.5以上支持框架Laravel、Sym...
- PHP使用Phar打包控制台程序
-
1.介绍1.1介绍php脚本有着非常强大的库支持,可以轻松做出特别强大的程序。php不仅仅可以搭建各种各样的网站系统、平台系统,还可以开发基于控制台运行的程序。不过使用php开发的控制台程序在使用...
- PHP实现URL编码、Base64编码、MD5编码的方法
-
1.介绍1.1介绍今天开始福哥要给大家讲解关于字符编码的知识,所谓字符编码就是将一个字符串或者是一个二进制字节数组里面的每一个字符根据一定的规则替换成一个或者多个其他字符的过程。字符编码的意义有很...
- 雷卯针对易百纳海思Hi3521D开发板防雷防静电方案
-
一、应用场景1、医疗电子2、安防监控3、数字标牌4、视频广告5、环境监测二、功能概述1CPU:ARMCortexA7双核@Max.1.3GHz2H.265/H.264&JPEG多码流编...
- 不折腾无人生-安卓盒子安装Linux系统armbian纪实
-
不折腾无人生-安卓盒子安装Linux系统armbian纪实小编的x96max+(晶晨Amlogics905x3)安卓盒子已安装二个系统,原装安卓9.0和tf卡上的CoreELEC9.2.3,可玩性...
- 全网最简单的玩客云刷casaos方法及后续使用心得
-
本内容来源于@什么值得买APP,观点仅代表作者本人|作者:不鸣de前几天在站内看见很多值友分享了玩客云刷casaos,被简洁的操作界面种草,于是我将之前刷了powersee大神网页导航版armbia...
- 最新评测:英特尔旗舰 Alder Lake 处理器击败苹果M1 Max
-
据国外媒体tomshardware报道,英特尔最新的酷睿i9-12900HK处理器刚刚赢得了移动x86与Arm的性能大战,但这是有代价的。这款移动14核AlderLake芯片在多个工作负...
- 创维酷开Max系列电视开启ADB并安装第三方应用教程
-
前言创维酷开系列智能电视采用的是相对封闭的系统,虽然设置中提供了安装未知应用的选项,但由于电视安装位置的限制,往往难以直接使用USB接口安装应用。本文将详细介绍如何通过ADB方式在创维酷开Max系列电...
- 苹果 Mac Studio,再次刷新我们对个人电脑的认知
-
由两块M1Max组成的M1Ultra,成为了M1系列的最后一块拼图,并完成了整个M1SoC宇宙。这就好像《复仇者联盟4:终局之战》对于漫威第一阶段,十几年勤恳的布局,最终达到顶峰...
- 「必买」盘点2021年男人们的败家清单,越“败”越香
-
心里总想买点啥?看看《必买》,全网最有料的场景种草指南。草原割不尽,春风吹又生。在过去的2021年,不断被各种数码产品种草,一直在买买买,剁手不停。大部分产品都经过详细的对比做足了功课,也有部分是一时...
- Opus音频编解码在arm上的移植
-
一、简介现在有个需求,在局域网内实现实时语音,传输层协议使用UDP协议,如果直接使用ALSA进行录制音频流并发送到另一端进行播放,音质会非常差,而且断断续续,原因如下:采样频率:fm=44.1K...
- N ARM MINI空气减震系统臂体安装指南及应用说明
-
距离MOVMAX移动大师NARMMINI发布已经过去一段时间了,不少收到NARMMINI的小伙伴也已经迅速将产品投入到自己的车拍工作中去了。而在实际工作过程中我们也收到了用户的部分疑问和反馈:...
- 搜索引擎中的性能怪兽,Elasticsearch挑战者之Manticore Search
-
ManticoreSearch简介ManticoreSearch是一个使用C++开发的高性能搜索引擎,创建于2017年,其前身是SphinxSearch。ManticoreSe...
- 10个运维拿来就用的 Shell 脚本,用了才知道有多爽
-
1、监控MySQL主从同步状态是否异常脚本#!/bin/bashHOST=localhostUSER=rootPASSWD=123.comIO_SQL_STATUS=$(mysql-h$...
- PHP7.0.0正式版开放下载:速度大提升
-
IT之家讯PHP发布经理AnatolBelski在GitHub发布了PHP7.0.0正式版,该版本在速度提升上面有非常大的进步,比5.6版本提速两倍,已经接近Facebook开发的PHP执行引擎...
- 一周热门
- 最近发表
- 标签列表
-
- curseforge官网网址 (16)
- 外键约束 oracle (36)
- oracle的row number (32)
- 唯一索引 oracle (34)
- oracle in 表变量 (28)
- oracle导出dmp导出 (28)
- oracle两个表 (20)
- oracle 数据库 字符集 (20)
- oracle安装补丁 (19)
- matlab化简多项式 (20)
- 多线程的创建方式 (29)
- 多线程 python (30)
- java多线程并发处理 (32)
- 宏程序代码一览表 (35)
- c++需要学多久 (25)
- c语言编程小知识大全 (17)
- css class选择器用法 (25)
- css样式引入 (30)
- html5和css3新特性 (19)
- css教程文字移动 (33)
- php简单源码 (36)
- php个人中心源码 (25)
- 网站管理平台php源码 (19)
- php小说爬取源码 (23)
- github好玩的php项目 (18)