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.
 
 
 

676 lines
23 KiB

@{
ViewData["Title"] = "实时日志";
}
<style>
/* 页面布局 */
.log-container {
display: flex;
height: calc(100vh - 120px);
font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
}
/* 左侧日志列表 */
.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: space-between;
white-space: nowrap;
}
.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: 15px;
}
/* 列宽定义:固定与弹性结合 */
.log-timestamp { flex: 0 0 170px; } /* 固定宽度 */
.log-layer { flex: 0 0 100px; } /* 固定宽度 */
.log-direction { flex: 0 0 120px; } /* 固定宽度 */
.log-info { flex: 0 0 80px; } /* 固定宽度 */
.log-message {
flex: 1 1 0; /* 弹性增长和收缩,占据剩余空间 */
min-width: 150px; /* 保证最小宽度 */
}
/* 日志列表标题栏 */
.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;
}
/* 右侧日志详情 */
.log-detail-panel {
flex-grow: 1;
padding: 0 20px;
overflow-y: auto;
min-width: 250px; /* 保证最小宽度 */
}
.log-detail-panel h4 {
margin-top: 10px;
border-bottom: 2px solid #007bff;
padding-bottom: 5px;
color: #0056b3;
}
.detail-item {
margin-bottom: 12px;
}
.detail-item-label {
font-weight: bold;
color: #333;
}
.detail-item-value {
background-color: #f7f7f7;
padding: 12px;
border-radius: 4px;
word-break: break-all;
white-space: pre-wrap;
margin-top: 4px;
font-size: 0.95em;
line-height: 1.6;
}
/* 可拖动调整大小的分割线 */
.resizer {
flex: 0 0 5px;
background: #e9ecef;
cursor: col-resize;
transition: background-color 0.2s ease;
}
.resizer:hover,
.resizer.is-dragging {
background: #007bff;
}
#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: 8px;
}
.btn-small {
padding: 4px 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: #007bff;
}
.btn-small:active {
background-color: #e9ecef;
}
/* 错误提示 */
.error-message {
background-color: #f8d7da;
color: #721c24;
padding: 8px 12px;
border: 1px solid #f5c6cb;
border-radius: 4px;
margin-bottom: 10px;
display: none;
}
/* 信息提示 */
.info-message {
background-color: #d1ecf1;
color: #0c5460;
padding: 8px 12px;
border: 1px solid #bee5eb;
border-radius: 4px;
margin-bottom: 10px;
display: none;
}
</style>
<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">Timestamp</span>
<span class="log-layer">Layer</span>
<span class="log-direction">Direction</span>
<span class="log-message">Message</span>
<span class="log-info">Info</span>
</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>
</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">
<h4>日志详情</h4>
<!-- 详情将在这里动态生成 -->
</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 logListPanel = document.querySelector('.log-list-panel');
const resizer = document.getElementById('drag-resizer');
let allLogsData = [];
let eventSource = null;
let reconnectAttempts = 0;
const maxReconnectAttempts = 5;
const reconnectDelay = 3000; // 3秒
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 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 = [];
clusterize.clear();
totalLogsEl.textContent = '0';
newLogsCountEl.textContent = '';
detailPlaceholder.classList.remove('d-none');
detailContent.classList.add('d-none');
}
// 美化方向
function formatDirection(dir) {
return dir === 0 ? "Uplink" : "Downlink";
}
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') {
timestamp = formatDuration(log.Timestamp);
title = `Duration from start: ${timestamp} (Raw: ${log.Timestamp}ms)`;
} else {
timestamp = 'Invalid Time';
title = 'Timestamp from server was invalid or missing.';
note = `<br><small class="text-muted">${title}</small>`;
console.warn('Timestamp missing or invalid, using fallback for log:', 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-message" title="${log.Message || ''}">${log.Message || ''}</span>
<span class="log-info" title="${log.Info || ''}">${log.Info || ''}</span>
</div>`;
}
// 更新日志列表
function updateLogList(logs, prepend = false) {
if (!logs || logs.length === 0) return;
const newRows = logs.map((log, i) => formatLogItem(log, allLogsData.length + i));
if (prepend) {
clusterize.prepend(newRows);
} else {
clusterize.append(newRows);
}
allLogsData.push(...logs);
totalLogsEl.textContent = allLogsData.length;
// 显示新日志数量
if (!prepend) {
newLogsCountEl.textContent = `+${logs.length}`;
setTimeout(() => {
newLogsCountEl.textContent = '';
}, 2000);
}
}
// 显示日志详情
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">Data</div>
<div class="detail-item-value">${dataContent}</div>
</div>
`;
detailContent.innerHTML = '<h4>日志详情</h4>' + detailHtml;
detailContent.classList.remove('d-none');
}
// 建立SSE连接
function connectSSE() {
if (eventSource) {
eventSource.close();
}
updateConnectionStatus('connecting', '连接中...');
eventSource = new EventSource('/api/websocket/logs/stream');
eventSource.addEventListener('connected', function(event) {
console.log("SSE连接已建立");
updateConnectionStatus('connected', '已连接');
showInfo('日志流连接已建立');
reconnectAttempts = 0; // 重置重连计数
});
eventSource.addEventListener('history', function(event) {
console.log("接收到历史日志...", event.data);
try {
const data = JSON.parse(event.data);
console.log("历史日志数据:", data);
if (data.logs && Array.isArray(data.logs)) {
updateLogList(data.logs);
showInfo(`加载了 ${data.logs.length} 条历史日志`);
} else {
console.warn("历史日志数据格式不正确:", data);
showError("历史日志数据格式不正确");
}
} catch (error) {
console.error("解析历史日志数据失败:", error);
showError("解析历史日志数据失败: " + error.message);
}
});
eventSource.addEventListener('new_logs', function(event) {
console.log("接收到新日志...", event.data);
try {
const data = JSON.parse(event.data);
console.log("新日志数据:", data);
if (data.logs && Array.isArray(data.logs)) {
updateLogList(data.logs);
} else {
console.warn("新日志数据格式不正确:", data);
}
} catch (error) {
console.error("解析新日志数据失败:", error);
showError("解析新日志数据失败: " + error.message);
}
});
eventSource.addEventListener('reset', function(event) {
console.log("日志缓存已重置");
try {
const data = JSON.parse(event.data);
clearLogsDisplay();
showInfo('日志缓存已重置,等待新日志以建立时间线');
} catch (error) {
console.error("解析重置事件数据失败:", error);
}
});
eventSource.addEventListener('error', function(event) {
console.log("接收到错误事件");
try {
const data = JSON.parse(event.data);
updateConnectionStatus('error', '连接错误');
showError(`连接错误: ${data.message}`);
} catch (error) {
console.error("解析错误事件数据失败:", error);
}
});
eventSource.addEventListener('disconnected', function(event) {
console.log("连接已断开");
updateConnectionStatus('disconnected', '已断开');
showInfo('日志流连接已断开');
});
eventSource.addEventListener('fatal_error', function(event) {
console.error("致命错误");
try {
const data = JSON.parse(event.data);
updateConnectionStatus('error', '服务器错误');
showError(`服务器错误: ${data.message}`);
} catch (error) {
console.error("解析致命错误数据失败:", error);
}
});
eventSource.onerror = function (err) {
console.error("SSE 错误:", err);
updateConnectionStatus('error', '连接失败');
// 自动重连
if (reconnectAttempts < maxReconnectAttempts) {
reconnectAttempts++;
showError(`连接失败,${reconnectDelay/1000}秒后重试 (${reconnectAttempts}/${maxReconnectAttempts})`);
setTimeout(connectSSE, reconnectDelay);
} else {
showError('连接失败,已达到最大重试次数');
updateConnectionStatus('disconnected', '连接失败');
}
};
}
// 事件委托处理点击事件
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();
});
// --- 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();
});
</script>
}