You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

1505 lines
54 KiB

@{
ViewData["Title"] = "实时日志";
}
<style>
/* 页面布局 */
.log-container {
display: flex;
height: calc(100vh - 280px); /* 调整高度以适应容器 */
font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
border: 1px solid #dee2e6;
border-radius: 0.5rem;
overflow: hidden;
background-color: #fff;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
/* 左侧日志列表 */
.log-list-panel {
flex: 0 0 65%;
border-right: 2px solid #ddd;
display: flex;
flex-direction: column;
overflow: hidden; /* 防止内部元素溢出 */
}
#log-scroll-area {
flex-grow: 1;
overflow-y: auto;
}
#log-content-area {
width: 100%;
}
.log-item {
padding: 6px 10px;
border-bottom: 1px solid #f0f0f0;
cursor: pointer;
display: flex;
justify-content: flex-start; /* 改为左对齐 */
align-items: flex-start; /* 顶部对齐,支持多行内容 */
min-height: 24px; /* 最小高度 */
transition: background-color 0.2s;
}
.log-item:hover {
background-color: #e8f4ff;
}
.log-item.selected {
background-color: #cce7ff;
font-weight: bold;
}
.log-item > span, .log-list-header > span {
text-overflow: ellipsis;
overflow: hidden;
padding-right: 8px;
white-space: nowrap; /* 保持单行显示 */
word-break: keep-all; /* 防止单词被截断 */
}
/* 列宽定义:自适应宽度 */
.log-timestamp {
flex: 0 0 auto;
min-width: 150px;
max-width: 200px;
}
.log-layer {
flex: 0 0 auto;
min-width: 80px;
max-width: 120px;
}
.log-direction {
flex: 0 0 auto;
min-width: 60px;
max-width: 100px;
}
.log-ueid {
flex: 0 0 auto;
min-width: 60px;
max-width: 100px;
}
.log-rnti {
flex: 0 0 auto;
min-width: 60px;
max-width: 100px;
}
.log-cell {
flex: 0 0 auto;
min-width: 60px;
max-width: 100px;
}
.log-channel {
flex: 0 0 auto;
min-width: 80px;
max-width: 120px;
}
.log-info {
flex: 0 0 auto;
min-width: 60px;
max-width: 100px;
}
.log-message {
flex: 1 1 auto; /* 弹性增长和收缩,占据剩余空间 */
min-width: 200px; /* 保证最小宽度 */
max-width: none; /* 不限制最大宽度 */
white-space: normal; /* 允许换行 */
word-break: break-word; /* 长单词可以换行 */
line-height: 1.4; /* 增加行高 */
max-height: 3.2em; /* 最多显示2行 */
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 2; /* 限制显示行数 */
-webkit-box-orient: vertical;
}
/* 日志列表标题栏 */
.log-list-header {
display: flex;
justify-content: space-between;
padding: 8px 10px;
padding-right: 27px; /* 10px base padding + 17px for a standard scrollbar */
background-color: #f8f9fa;
font-weight: bold;
border-bottom: 2px solid #dee2e6;
color: #495057;
font-size: 0.9em;
white-space: nowrap;
}
/* 排序相关样式 */
.sortable-header {
cursor: pointer;
user-select: none;
display: flex;
align-items: center;
gap: 4px;
transition: background-color 0.2s;
}
.sortable-header:hover {
background-color: #e9ecef;
border-radius: 3px;
padding: 2px 4px;
margin: -2px -4px;
}
.sort-icon {
font-size: 0.8em;
opacity: 0.5;
transition: opacity 0.2s;
}
.sortable-header:hover .sort-icon {
opacity: 1;
}
.sort-icon.active {
opacity: 1;
color: #007bff;
}
.sort-icon.asc::after {
content: " ▲";
}
.sort-icon.desc::after {
content: " ▼";
}
/* 右侧日志详情 */
.log-detail-panel {
flex-grow: 1;
padding: 0 20px;
overflow-y: auto;
min-width: 250px; /* 保证最小宽度 */
background-color: #fff;
border-left: 1px solid #ddd;
}
.log-detail-panel h4 {
background-color: #f8f9fa;
border-bottom: 1px solid #dee2e6;
padding: 12px 20px;
margin: 0 -20px 0 -20px; /* Extend to panel edges */
font-size: 1.1em;
color: #343a40;
}
.detail-item {
margin-top: 15px;
}
.detail-item-label {
font-size: 0.9em;
font-weight: bold;
color: #6c757d;
text-transform: uppercase;
margin-bottom: 5px;
display: block;
}
.detail-item-value {
background-color: #f6f8fa; /* Light theme background */
color: #24292e; /* Dark theme text */
padding: 15px;
border-radius: 5px;
white-space: pre; /* Prevent wrapping, preserve whitespace */
overflow-x: auto; /* Add horizontal scrollbar */
margin-top: 4px;
font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;
font-size: 0.9em;
line-height: 1.7;
border: 1px solid #ced4da; /* Light border */
}
/* 可拖动调整大小的分割线 */
.resizer {
flex: 0 0 10px; /* Wider grab area */
cursor: col-resize;
background: #f1f3f5; /* A bit darker than page bg */
border-left: 1px solid #dee2e6;
border-right: 1px solid #dee2e6;
position: relative;
transition: all 0.2s ease;
}
.resizer::before {
content: '⋮';
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%) rotate(90deg);
color: #adb5bd;
font-size: 1.2em;
line-height: 0;
transition: color 0.2s ease;
}
.resizer:hover,
.resizer.is-dragging {
background: #007bff;
border-color: #0056b3;
}
.resizer:hover::before,
.resizer.is-dragging::before {
color: #fff;
}
#detail-placeholder {
color: #999;
text-align: center;
padding-top: 50px;
font-size: 1.2em;
}
/* 状态栏 */
.status-bar {
padding: 8px 10px;
background-color: #f8f9fa;
border-top: 1px solid #ddd;
font-size: 0.9em;
color: #666;
display: flex;
justify-content: space-between;
align-items: center;
}
/* 连接状态指示器 */
.connection-status {
display: flex;
align-items: center;
gap: 8px;
}
.status-indicator {
width: 10px;
height: 10px;
border-radius: 50%;
display: inline-block;
}
.status-connected {
background-color: #28a745;
animation: pulse 2s infinite;
}
.status-connecting {
background-color: #ffc107;
animation: pulse 1s infinite;
}
.status-disconnected {
background-color: #dc3545;
}
.status-error {
background-color: #dc3545;
animation: blink 1s infinite;
}
@@keyframes pulse {
0% { opacity: 1; }
50% { opacity: 0.5; }
100% { opacity: 1; }
}
@@keyframes blink {
0%, 50% { opacity: 1; }
51%, 100% { opacity: 0.3; }
}
/* 控制按钮 */
.control-buttons {
display: flex;
gap: 5px;
}
.btn-small {
padding: 2px 8px;
font-size: 0.8em;
border: 1px solid #ddd;
background-color: #fff;
border-radius: 3px;
cursor: pointer;
transition: all 0.2s;
}
.btn-small:hover {
background-color: #f8f9fa;
border-color: #adb5bd;
}
.btn-small:active {
background-color: #e9ecef;
}
/* 错误提示 */
.error-message {
background-color: #f8d7da;
color: #721c24;
padding: 10px;
margin: 10px;
border-radius: 4px;
border: 1px solid #f5c6cb;
display: none;
}
/* 信息提示 */
.info-message {
background-color: #d1ecf1;
color: #0c5460;
padding: 10px;
margin: 10px;
border-radius: 4px;
border: 1px solid #bee5eb;
display: none;
}
/* Layer过滤器样式 */
.layer-filter-section {
background-color: #f8f9fa;
border-bottom: 1px solid #dee2e6;
padding: 10px;
}
.filter-header-row {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 8px;
}
.filter-label {
font-weight: bold;
color: #495057;
}
.select-all-label {
font-size: 0.9em;
color: #6c757d;
cursor: pointer;
}
.filter-options-row {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.filter-option {
display: flex;
align-items: center;
}
.filter-option label {
display: flex;
align-items: center;
gap: 4px;
font-size: 0.85em;
color: #495057;
cursor: pointer;
padding: 2px 6px;
border-radius: 3px;
transition: background-color 0.2s;
}
.filter-option label:hover {
background-color: #e9ecef;
}
.filter-option input[type="checkbox"] {
margin: 0;
}
.filter-option input:checked + span {
font-weight: bold;
color: #007bff;
}
.log-layer {
display: flex;
align-items: center;
flex: 0 0 100px;
}
/* 响应式调整 */
@@media (max-width: 768px) {
.log-container {
flex-direction: column;
height: calc(100vh - 150px);
}
.log-list-panel {
flex: 0 0 60%;
border-right: none;
border-bottom: 2px solid #ddd;
}
.resizer {
flex: 0 0 5px;
cursor: row-resize;
}
.resizer::before {
transform: translate(-50%, -50%);
}
.log-detail-panel {
min-width: auto;
border-left: none;
}
}
/* 列设置相关样式 */
.column-settings {
position: relative;
display: inline-block;
}
.column-settings-dropdown {
position: absolute;
bottom: 100%; /* Changed from top to bottom */
right: 0;
margin-bottom: 4px; /* Add some space between button and menu */
background: white;
border: 1px solid #ddd;
border-radius: 4px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
z-index: 1000;
min-width: 200px;
display: none;
padding: 8px;
}
.column-settings-dropdown.show {
display: block;
}
.column-settings-header {
font-weight: bold;
padding: 4px 8px;
border-bottom: 1px solid #eee;
margin-bottom: 8px;
color: #495057;
font-size: 0.9em;
}
.column-option {
display: flex;
align-items: center;
padding: 4px 8px;
cursor: pointer;
border-radius: 3px;
transition: background-color 0.2s;
}
.column-option:hover {
background-color: #f8f9fa;
}
.column-option input[type="checkbox"] {
margin-right: 8px;
}
.column-option label {
cursor: pointer;
font-size: 0.85em;
color: #495057;
margin: 0;
flex: 1;
}
.column-option.disabled {
opacity: 0.5;
cursor: not-allowed;
}
.column-option.disabled:hover {
background-color: transparent;
}
</style>
<div class="container">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-list-alt"></i> 实时日志监控
</h3>
</div>
<div class="card-body p-0">
<div class="log-container">
<div class="log-list-panel">
<!-- 状态提示区域 -->
<div id="error-message" class="error-message"></div>
<div id="info-message" class="info-message"></div>
<div class="log-list-header">
<span class="log-timestamp sortable-header" id="timestamp-sort">
Timestamp
<span class="sort-icon" id="timestamp-sort-icon"></span>
</span>
<span class="log-layer">Layer</span>
<span class="log-direction">Direction</span>
<span class="log-ueid">UE ID</span>
<span class="log-rnti">RNTI</span>
<span class="log-cell">Cell</span>
<span class="log-channel">Channel</span>
<span class="log-message">Message</span>
<span class="log-info">Info</span>
</div>
<!-- Layer过滤器区域 -->
<div class="layer-filter-section">
<div class="filter-header-row">
<span class="filter-label">Layer过滤:</span>
<label class="select-all-label">
<input type="checkbox" id="select-all-layers"> 全选
</label>
</div>
<div class="filter-options-row" id="layer-filter-options">
<!-- 选项将动态生成 -->
</div>
</div>
<div id="log-scroll-area">
<div id="log-content-area"></div>
</div>
<div class="status-bar">
<div>
总日志条数: <span id="total-logs">0</span>
<span id="new-logs-count" style="color: #28a745; margin-left: 10px;"></span>
</div>
<div class="connection-status">
<span class="status-indicator" id="status-indicator"></span>
<span id="status-text">连接中...</span>
<div class="control-buttons">
<button class="btn-small" id="clear-logs-btn" title="清空日志">清空</button>
<button class="btn-small" id="reset-logs-btn" title="重置日志">重置</button>
<button class="btn-small" id="add-test-data-btn" title="添加测试数据">测试</button>
<button class="btn-small" id="reconnect-btn" title="重新连接">重连</button>
<button class="btn-small" id="debug-btn" title="调试信息">调试</button>
<button class="btn-small" id="test-connection-btn" title="测试连接">测试连接</button>
<button class="btn-small" id="force-push-btn" title="强制推送">强制推送</button>
<div class="column-settings">
<button class="btn-small" id="column-settings-btn" title="列设置">列设置</button>
<div class="column-settings-dropdown" id="column-settings-dropdown">
<div class="column-settings-header">显示/隐藏列</div>
<div class="column-option">
<input type="checkbox" id="col-timestamp" checked>
<label for="col-timestamp">时间戳</label>
</div>
<div class="column-option">
<input type="checkbox" id="col-layer" checked>
<label for="col-layer">协议层</label>
</div>
<div class="column-option">
<input type="checkbox" id="col-direction" checked>
<label for="col-direction">方向</label>
</div>
<div class="column-option">
<input type="checkbox" id="col-ueid" checked>
<label for="col-ueid">UE ID</label>
</div>
<div class="column-option">
<input type="checkbox" id="col-rnti" checked>
<label for="col-rnti">RNTI</label>
</div>
<div class="column-option">
<input type="checkbox" id="col-cell" checked>
<label for="col-cell">Cell</label>
</div>
<div class="column-option">
<input type="checkbox" id="col-channel" checked>
<label for="col-channel">Channel</label>
</div>
<div class="column-option">
<input type="checkbox" id="col-message" checked>
<label for="col-message">消息</label>
</div>
<div class="column-option">
<input type="checkbox" id="col-info" checked>
<label for="col-info">信息</label>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="resizer" id="drag-resizer"></div>
<div class="log-detail-panel">
<div id="detail-placeholder">
<p>请从左侧选择一条日志以查看详情</p>
</div>
<div id="detail-content" class="d-none">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
@section Scripts {
<script src="https://cdnjs.cloudflare.com/ajax/libs/clusterize.js/0.19.0/clusterize.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/clusterize.js/0.19.0/clusterize.min.css" />
<script>
document.addEventListener("DOMContentLoaded", function () {
const scrollArea = document.getElementById('log-scroll-area');
const contentArea = document.getElementById('log-content-area');
const totalLogsEl = document.getElementById('total-logs');
const newLogsCountEl = document.getElementById('new-logs-count');
const detailPlaceholder = document.getElementById('detail-placeholder');
const detailContent = document.getElementById('detail-content');
const statusIndicator = document.getElementById('status-indicator');
const statusText = document.getElementById('status-text');
const errorMessage = document.getElementById('error-message');
const infoMessage = document.getElementById('info-message');
const clearLogsBtn = document.getElementById('clear-logs-btn');
const resetLogsBtn = document.getElementById('reset-logs-btn');
const addTestDataBtn = document.getElementById('add-test-data-btn');
const reconnectBtn = document.getElementById('reconnect-btn');
const debugBtn = document.getElementById('debug-btn');
const testConnectionBtn = document.getElementById('test-connection-btn');
const forcePushBtn = document.getElementById('force-push-btn');
const logListPanel = document.querySelector('.log-list-panel');
const resizer = document.getElementById('drag-resizer');
const layerFilterOptions = document.getElementById('layer-filter-options');
const selectAllLayers = document.getElementById('select-all-layers');
let allLogsData = [];
let availableLayers = new Set(['PHY', 'MAC', 'RLC', 'PDCP', 'RRC', 'NAS']); // 初始化标准LTE层
let selectedLayers = new Set(); // 用于跟踪选中的日志层
let eventSource = null;
let reconnectAttempts = 0;
const maxReconnectAttempts = 5;
const reconnectDelay = 3000; // 3秒
// 排序相关变量
let sortField = 'timestamp'; // 当前排序字段
let sortDirection = 'desc'; // 当前排序方向:'asc' 或 'desc'
// 列显示状态管理
let columnVisibility = {
timestamp: true,
layer: true,
direction: true,
ueid: true,
rnti: true,
cell: true,
channel: true,
message: true,
info: true
};
let clusterize = new Clusterize({
rows: [],
scrollId: 'log-scroll-area',
contentId: 'log-content-area',
tag: 'div',
rows_in_block: 50,
blocks_in_cluster: 4,
no_data_text: "正在等待日志..."
});
// 更新全选复选框状态
function updateSelectAllState() {
if (availableLayers.size === 0) {
selectAllLayers.checked = false;
selectAllLayers.indeterminate = false;
} else if (selectedLayers.size === 0) {
selectAllLayers.checked = false;
selectAllLayers.indeterminate = false;
} else if (selectedLayers.size === availableLayers.size) {
selectAllLayers.checked = true;
selectAllLayers.indeterminate = false;
} else {
selectAllLayers.checked = false;
selectAllLayers.indeterminate = true;
}
}
// 更新排序图标
function updateSortIcon() {
const sortIcon = document.getElementById('timestamp-sort-icon');
sortIcon.className = 'sort-icon';
if (sortField === 'timestamp') {
sortIcon.classList.add('active', sortDirection);
}
}
// 排序数据
function sortLogsData() {
allLogsData.sort((a, b) => {
if (sortField === 'timestamp') {
const timeA = a.Timestamp || 0;
const timeB = b.Timestamp || 0;
return sortDirection === 'asc' ? timeA - timeB : timeB - timeA;
}
return 0;
});
}
// 更新Layer过滤器选项
function updateLayerFilter() {
const options = [];
// 按字母顺序排序
const sortedLayers = Array.from(availableLayers).sort();
sortedLayers.forEach(layer => {
const isChecked = selectedLayers.has(layer) ? ' checked' : '';
options.push(`<div class="filter-option">
<label>
<input type="checkbox" value="${layer}"${isChecked}>
<span>${layer}</span>
</label>
</div>`);
});
layerFilterOptions.innerHTML = options.join('');
// 重新绑定事件
bindFilterEvents();
// 更新全选状态
updateSelectAllState();
}
// 绑定过滤器事件
function bindFilterEvents() {
// 绑定单个复选框事件
layerFilterOptions.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
checkbox.addEventListener('change', function() {
if (this.checked) {
selectedLayers.add(this.value);
} else {
selectedLayers.delete(this.value);
}
updateSelectAllState();
refreshLogList();
});
});
}
// 根据当前过滤器重新渲染日志列表
function refreshLogList() {
let filteredLogs = allLogsData;
if (selectedLayers.size > 0 && selectedLayers.size < availableLayers.size) {
filteredLogs = allLogsData.filter(log => selectedLayers.has(log.Layer));
}
// 对过滤后的数据进行排序
if (sortField === 'timestamp') {
filteredLogs.sort((a, b) => {
const timeA = a.Timestamp || 0;
const timeB = b.Timestamp || 0;
return sortDirection === 'asc' ? timeA - timeB : timeB - timeA;
});
}
const rows = filteredLogs.map((log, i) => formatLogItem(log, i));
clusterize.clear();
clusterize.append(rows);
// 更新总数显示
totalLogsEl.textContent = filteredLogs.length;
}
// 更新连接状态
function updateConnectionStatus(status, text) {
statusIndicator.className = 'status-indicator status-' + status;
statusText.textContent = text;
}
// 显示错误消息
function showError(message) {
errorMessage.textContent = message;
errorMessage.style.display = 'block';
setTimeout(() => {
errorMessage.style.display = 'none';
}, 5000);
}
// 显示信息消息
function showInfo(message) {
infoMessage.textContent = message;
infoMessage.style.display = 'block';
setTimeout(() => {
infoMessage.style.display = 'none';
}, 3000);
}
// 清空日志显示
function clearLogsDisplay() {
allLogsData = [];
availableLayers.clear();
// 重新添加标准LTE层
['PHY', 'MAC', 'RLC', 'PDCP', 'RRC', 'NAS'].forEach(layer => availableLayers.add(layer));
selectedLayers.clear();
clusterize.clear();
totalLogsEl.textContent = '0';
newLogsCountEl.textContent = '';
detailPlaceholder.classList.remove('d-none');
detailContent.classList.add('d-none');
updateLayerFilter();
// 重置排序状态
sortField = 'timestamp';
sortDirection = 'desc';
updateSortIcon();
}
// 处理时间戳排序
function handleTimestampSort() {
if (sortField === 'timestamp') {
// 切换排序方向
sortDirection = sortDirection === 'asc' ? 'desc' : 'asc';
} else {
// 首次点击时间戳排序
sortField = 'timestamp';
sortDirection = 'desc';
}
updateSortIcon();
refreshLogList();
}
// 切换列显示状态
function toggleColumnVisibility(columnName, visible) {
columnVisibility[columnName] = visible;
updateColumnDisplay();
saveColumnSettings();
}
// 更新列显示
function updateColumnDisplay() {
// 更新标题栏
const headerSpans = document.querySelectorAll('.log-list-header > span');
headerSpans.forEach(span => {
const columnClass = Array.from(span.classList).find(cls => cls.startsWith('log-'));
if (columnClass) {
const columnName = columnClass.replace('log-', '');
if (columnName === 'timestamp') {
span.style.display = columnVisibility.timestamp ? 'flex' : 'none';
} else {
span.style.display = columnVisibility[columnName] ? 'block' : 'none';
}
}
});
// 更新日志条目
const logItems = document.querySelectorAll('.log-item > span');
logItems.forEach(span => {
const columnClass = Array.from(span.classList).find(cls => cls.startsWith('log-'));
if (columnClass) {
const columnName = columnClass.replace('log-', '');
if (columnName === 'timestamp') {
span.style.display = columnVisibility.timestamp ? 'flex' : 'none';
} else {
span.style.display = columnVisibility[columnName] ? 'block' : 'none';
}
}
});
}
// 保存列设置到本地存储
function saveColumnSettings() {
localStorage.setItem('logColumnSettings', JSON.stringify(columnVisibility));
}
// 从本地存储加载列设置
function loadColumnSettings() {
const saved = localStorage.getItem('logColumnSettings');
if (saved) {
try {
const savedSettings = JSON.parse(saved);
columnVisibility = { ...columnVisibility, ...savedSettings };
} catch (error) {
console.warn('加载列设置失败:', error);
}
}
}
// 更新列设置复选框状态
function updateColumnCheckboxes() {
document.getElementById('col-timestamp').checked = columnVisibility.timestamp;
document.getElementById('col-layer').checked = columnVisibility.layer;
document.getElementById('col-direction').checked = columnVisibility.direction;
document.getElementById('col-ueid').checked = columnVisibility.ueid;
document.getElementById('col-rnti').checked = columnVisibility.rnti;
document.getElementById('col-cell').checked = columnVisibility.cell;
document.getElementById('col-channel').checked = columnVisibility.channel;
document.getElementById('col-message').checked = columnVisibility.message;
document.getElementById('col-info').checked = columnVisibility.info;
}
// 美化方向
function formatDirection(dir) {
if (dir === 1) {
return "UL";
} else if (dir === 2) {
return "DL";
} else {
return "Unknown";
}
}
function formatDuration(ms) {
if (typeof ms !== 'number' || ms < 0) {
return 'Invalid Time';
}
let remaining = ms;
const hours = Math.floor(remaining / 3600000);
remaining %= 3600000;
const minutes = Math.floor(remaining / 60000);
remaining %= 60000;
const seconds = Math.floor(remaining / 1000);
remaining %= 1000;
const strHours = String(hours).padStart(2, '0');
const strMinutes = String(minutes).padStart(2, '0');
const strSeconds = String(seconds).padStart(2, '0');
const strMs = String(remaining).padStart(3, '0');
return `${strHours}:${strMinutes}:${strSeconds}.${strMs}`;
}
function getDisplayTimestamp(log) {
let timestamp = 'Invalid Date';
let title = 'Timestamp from server.';
let note = '';
if (log && typeof log.Timestamp === 'number') {
// 检查是否为 Unix 时间戳(13位数字,通常大于 1000000000000)
if (log.Timestamp > 1000000000000) {
// Unix 时间戳,转换为本地时间
const date = new Date(log.Timestamp);
timestamp = date.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
fractionalSecondDigits: 3
});
title = `Unix 时间戳: ${log.Timestamp} -> ${date.toISOString()}`;
} else {
// 持续时间(毫秒数)
timestamp = formatDuration(log.Timestamp);
title = `持续时间: ${timestamp} (${log.Timestamp}ms)`;
}
} else {
timestamp = 'Invalid Time';
title = '时间戳无效或缺失';
note = `<br><small class="text-muted">${title}</small>`;
console.warn('时间戳缺失或无效,使用默认值:', log);
}
return { timestamp, title, note };
}
// 格式化日志条目为 HTML 字符串
function formatLogItem(log, index) {
const { timestamp, title: timestampTitle } = getDisplayTimestamp(log);
return `<div class="log-item" data-index="${index}">
<span class="log-timestamp" title="${timestampTitle}">${timestamp}</span>
<span class="log-layer" title="${log.Layer || ''}">${log.Layer || ''}</span>
<span class="log-direction" title="${formatDirection(log.Direction)}">${formatDirection(log.Direction)}</span>
<span class="log-ueid" title="${log.UeId || ''}">${log.UeId || ''}</span>
<span class="log-rnti" title="${log.Rnti || ''}">${log.Rnti || ''}</span>
<span class="log-cell" title="${log.Cell || ''}">${log.Cell || ''}</span>
<span class="log-channel" title="${log.Channel || ''}">${log.Channel || ''}</span>
<span class="log-message" title="${log.Message || ''}">${log.Message || ''}</span>
<span class="log-info" title="${log.Info || ''}">${log.Info || ''}</span>
</div>`;
}
// 更新日志列表
function updateLogList(logs, prepend = false, isHistory = false) {
if (!logs || logs.length === 0) return;
// 收集新的日志层
logs.forEach(log => {
if (log.Layer) {
availableLayers.add(log.Layer);
}
});
// 更新过滤器选项
updateLayerFilter();
if (isHistory) {
// 历史日志:直接替换所有数据
allLogsData = [...logs];
const rows = logs.map((log, i) => formatLogItem(log, i));
clusterize.clear();
clusterize.append(rows);
showInfo(`加载了 ${logs.length} 条历史日志`);
} else {
// 新日志:添加到现有数据
const newRows = logs.map((log, i) => formatLogItem(log, allLogsData.length + i));
if (prepend) {
clusterize.prepend(newRows);
} else {
clusterize.append(newRows);
}
allLogsData.push(...logs);
// 显示新日志数量
if (!prepend) {
newLogsCountEl.textContent = `+${logs.length}`;
setTimeout(() => {
newLogsCountEl.textContent = '';
}, 2000);
}
}
// 根据当前过滤器更新显示
refreshLogList();
}
// 显示日志详情
function showLogDetail(index) {
const log = allLogsData[index];
if (!log) return;
detailPlaceholder.classList.add('d-none');
const dataContent = (log.Data && Array.isArray(log.Data) && log.Data.length > 0)
? log.Data.join('\n')
: 'N/A';
const detailHtml = `
<div class="detail-item">
<div class="detail-item-label">UE ID</div>
<div class="detail-item-value">${log.UeId || 'N/A'}</div>
</div>
<div class="detail-item">
<div class="detail-item-label">RNTI</div>
<div class="detail-item-value">${log.Rnti || 'N/A'}</div>
</div>
<div class="detail-item">
<div class="detail-item-label">Cell</div>
<div class="detail-item-value">${log.Cell || 'N/A'}</div>
</div>
<div class="detail-item">
<div class="detail-item-label">Channel</div>
<div class="detail-item-value">${log.Channel || 'N/A'}</div>
</div>
<div class="detail-item">
<div class="detail-item-label">Data</div>
<div class="detail-item-value">${dataContent}</div>
</div>
`;
detailContent.innerHTML = detailHtml;
detailContent.classList.remove('d-none');
}
// 建立SSE连接
function connectSSE() {
if (eventSource) {
eventSource.close();
}
updateConnectionStatus('connecting', '连接中...');
console.log('开始建立SSE连接...');
eventSource = new EventSource('/api/websocket/logs/stream');
// 添加连接打开事件监听
eventSource.onopen = function(event) {
console.log('EventSource onopen 事件:', event);
updateConnectionStatus('connected', '已连接');
};
eventSource.addEventListener('connected', function(event) {
console.log("SSE连接已建立", event);
updateConnectionStatus('connected', '已连接');
showInfo('日志流连接已建立');
reconnectAttempts = 0; // 重置重连计数
});
eventSource.addEventListener('history', function(event) {
console.log("接收到历史日志事件", event);
console.log("历史日志原始数据:", event.data);
try {
const data = JSON.parse(event.data);
console.log("历史日志数据:", data);
if (data.logs && Array.isArray(data.logs)) {
console.log(`处理 ${data.logs.length} 条历史日志`);
updateLogList(data.logs, false, true); // 标记为历史日志
} else {
console.warn("历史日志数据格式不正确:", data);
showError("历史日志数据格式不正确");
}
} catch (error) {
console.error("解析历史日志数据失败:", error);
console.error("原始数据:", event.data);
showError("解析历史日志数据失败: " + error.message);
}
});
eventSource.addEventListener('new_logs', function(event) {
console.log("接收到新日志事件", event);
console.log("新日志原始数据:", event.data);
try {
const data = JSON.parse(event.data);
console.log("新日志数据:", data);
if (data.logs && Array.isArray(data.logs)) {
console.log(`处理 ${data.logs.length} 条新日志`);
updateLogList(data.logs, false, false); // 标记为新日志
} else {
console.warn("新日志数据格式不正确:", data);
}
} catch (error) {
console.error("解析新日志数据失败:", error);
console.error("原始数据:", event.data);
showError("解析新日志数据失败: " + error.message);
}
});
eventSource.addEventListener('reset', function(event) {
console.log("接收到重置事件", event);
try {
const data = JSON.parse(event.data);
console.log("重置事件数据:", data);
clearLogsDisplay();
showInfo('日志缓存已重置,等待新日志以建立时间线');
} catch (error) {
console.error("解析重置事件数据失败:", error);
}
});
eventSource.addEventListener('error', function(event) {
console.log("接收到错误事件", event);
try {
const data = JSON.parse(event.data);
console.log("错误事件数据:", data);
updateConnectionStatus('error', '连接错误');
showError(`连接错误: ${data.message}`);
} catch (error) {
console.error("解析错误事件数据失败:", error);
}
});
eventSource.addEventListener('disconnected', function(event) {
console.log("接收到断开连接事件", event);
updateConnectionStatus('disconnected', '已断开');
showInfo('日志流连接已断开');
});
eventSource.addEventListener('fatal_error', function(event) {
console.error("接收到致命错误事件", event);
try {
const data = JSON.parse(event.data);
console.log("致命错误事件数据:", data);
updateConnectionStatus('error', '服务器错误');
showError(`服务器错误: ${data.message}`);
} catch (error) {
console.error("解析致命错误数据失败:", error);
}
});
eventSource.onerror = function (err) {
console.error("SSE 连接错误:", err);
console.error("EventSource readyState:", eventSource.readyState);
updateConnectionStatus('error', '连接失败');
// 自动重连
if (reconnectAttempts < maxReconnectAttempts) {
reconnectAttempts++;
console.log(`连接失败,${reconnectDelay/1000}秒后重试 (${reconnectAttempts}/${maxReconnectAttempts})`);
showError(`连接失败,${reconnectDelay/1000}秒后重试 (${reconnectAttempts}/${maxReconnectAttempts})`);
setTimeout(connectSSE, reconnectDelay);
} else {
console.log('连接失败,已达到最大重试次数');
showError('连接失败,已达到最大重试次数');
updateConnectionStatus('disconnected', '连接失败');
}
};
}
// 事件监听器
// 全选/取消全选
selectAllLayers.addEventListener('change', function() {
const isChecked = selectAllLayers.checked;
if (isChecked) {
// 全选
selectedLayers.clear();
availableLayers.forEach(layer => selectedLayers.add(layer));
} else {
// 取消全选
selectedLayers.clear();
}
updateLayerFilter();
refreshLogList();
});
// 时间戳排序点击事件
document.getElementById('timestamp-sort').addEventListener('click', handleTimestampSort);
// 事件委托处理点击事件
contentArea.addEventListener('click', function(e) {
const item = e.target.closest('.log-item');
if (item) {
// 移除之前选中的
const selected = contentArea.querySelector('.log-item.selected');
if (selected) {
selected.classList.remove('selected');
}
// 添加选中样式
item.classList.add('selected');
const index = parseInt(item.dataset.index, 10);
showLogDetail(index);
}
});
// 控制按钮事件
clearLogsBtn.addEventListener('click', function() {
if (confirm('确定要清空所有日志吗?')) {
fetch('/api/websocket/logs/clear', { method: 'POST' })
.then(response => response.json())
.then(data => {
if (data.message) {
showInfo(data.message);
clearLogsDisplay();
}
})
.catch(error => {
showError('清空日志失败: ' + error.message);
});
}
});
resetLogsBtn.addEventListener('click', function() {
if (confirm('确定要重置日志缓存吗?')) {
fetch('/api/websocket/logs/reset', { method: 'POST' })
.then(response => response.json())
.then(data => {
if (data.message) {
showInfo(data.message);
// 重置后服务器会发送reset事件,由事件监听器处理清空
}
})
.catch(error => {
showError('重置日志失败: ' + error.message);
});
}
});
addTestDataBtn.addEventListener('click', function() {
fetch('/api/websocket/logs/add-test-data', { method: 'POST' })
.then(response => response.json())
.then(data => {
if (data.message) {
showInfo(data.message);
}
})
.catch(error => {
showError('添加测试数据失败: ' + error.message);
});
});
reconnectBtn.addEventListener('click', function() {
reconnectAttempts = 0; // 重置重连计数
connectSSE();
});
debugBtn.addEventListener('click', function() {
// 显示调试信息
const debugInfo = {
totalLogs: allLogsData.length,
availableLayers: Array.from(availableLayers),
selectedLayers: Array.from(selectedLayers),
connectionStatus: statusText.textContent,
eventSourceReadyState: eventSource ? eventSource.readyState : 'null',
sortField: sortField,
sortDirection: sortDirection,
columnVisibility: columnVisibility,
clusterizeRows: clusterize.rows.length,
url: window.location.href,
userAgent: navigator.userAgent
};
console.log('前端调试信息:', debugInfo);
// 检查服务器端日志缓存状态
fetch('/api/websocket/logs/debug')
.then(response => response.json())
.then(data => {
console.log('服务器端日志缓存状态:', data);
showInfo(`调试信息已输出到控制台。服务器缓存: ${data.totalLogs} 条日志`);
})
.catch(error => {
console.error('获取服务器调试信息失败:', error);
showError('获取服务器调试信息失败: ' + error.message);
});
// 检查SSE连接状态
fetch('/api/websocket/logs/connection-status')
.then(response => response.json())
.then(data => {
console.log('SSE连接状态:', data);
})
.catch(error => {
console.error('获取SSE连接状态失败:', error);
});
});
testConnectionBtn.addEventListener('click', function() {
// 测试连接
fetch('/api/websocket/logs/test-connection')
.then(response => response.json())
.then(data => {
if (data.message) {
showInfo(data.message);
}
})
.catch(error => {
showError('测试连接失败: ' + error.message);
});
});
forcePushBtn.addEventListener('click', function() {
// 强制推送
fetch('/api/websocket/logs/force-push-test', { method: 'POST' })
.then(response => response.json())
.then(data => {
if (data.message) {
showInfo(data.message);
}
})
.catch(error => {
showError('强制推送失败: ' + error.message);
});
});
// --- Resizer Logic ---
let isResizing = false;
resizer.addEventListener('mousedown', (e) => {
isResizing = true;
resizer.classList.add('is-dragging');
document.body.style.cursor = 'col-resize';
document.body.style.userSelect = 'none';
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
});
function onMouseMove(e) {
if (!isResizing) return;
const container = logListPanel.parentElement;
const containerRect = container.getBoundingClientRect();
const newLeftWidth = e.clientX - containerRect.left;
// Constraints
const leftPanelMinWidth = 400; // in pixels
const rightPanelMinWidth = 250; // in pixels
const maxWidth = container.offsetWidth - rightPanelMinWidth - resizer.offsetWidth;
if (newLeftWidth >= leftPanelMinWidth && newLeftWidth <= maxWidth) {
logListPanel.style.flexBasis = `${newLeftWidth}px`;
}
}
function onMouseUp() {
if (!isResizing) return;
isResizing = false;
resizer.classList.remove('is-dragging');
document.body.style.cursor = 'default';
document.body.style.userSelect = 'auto';
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
}
// --- End Resizer Logic ---
// 初始化连接
connectSSE();
// 初始化Layer过滤器,显示标准LTE层
updateLayerFilter();
// 初始化排序状态
updateSortIcon();
// 初始化列设置
loadColumnSettings();
updateColumnCheckboxes();
updateColumnDisplay();
// 列设置相关事件
const columnSettingsBtn = document.getElementById('column-settings-btn');
const columnSettingsDropdown = document.getElementById('column-settings-dropdown');
// 列设置按钮点击事件
columnSettingsBtn.addEventListener('click', function(e) {
e.stopPropagation();
columnSettingsDropdown.classList.toggle('show');
});
// 点击其他地方关闭下拉菜单
document.addEventListener('click', function(e) {
if (!columnSettingsDropdown.contains(e.target) && !columnSettingsBtn.contains(e.target)) {
columnSettingsDropdown.classList.remove('show');
}
});
// 列设置复选框事件
document.getElementById('col-timestamp').addEventListener('change', function() {
toggleColumnVisibility('timestamp', this.checked);
});
document.getElementById('col-layer').addEventListener('change', function() {
toggleColumnVisibility('layer', this.checked);
});
document.getElementById('col-direction').addEventListener('change', function() {
toggleColumnVisibility('direction', this.checked);
});
document.getElementById('col-ueid').addEventListener('change', function() {
toggleColumnVisibility('ueid', this.checked);
});
document.getElementById('col-rnti').addEventListener('change', function() {
toggleColumnVisibility('rnti', this.checked);
});
document.getElementById('col-cell').addEventListener('change', function() {
toggleColumnVisibility('cell', this.checked);
});
document.getElementById('col-channel').addEventListener('change', function() {
toggleColumnVisibility('channel', this.checked);
});
document.getElementById('col-message').addEventListener('change', function() {
toggleColumnVisibility('message', this.checked);
});
document.getElementById('col-info').addEventListener('change', function() {
toggleColumnVisibility('info', this.checked);
});
});
</script>
}
</rewritten_file>