<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>日志可视化工具</title>
<!-- 引入D3.js库 -->
<script src="https://d3js.org/d3.v7.min.js"></script>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
height: 100vh;
}
header {
padding: 10px;
background-color: #3f51b5;
color: white;
text-align: center;
font-size: 24px;
}
#container {
display: flex;
flex: 1;
overflow: hidden;
}
#left-panel, #right-panel {
padding: 10px;
box-sizing: border-box;
overflow: auto;
}
#left-panel {
width: 30%;
border-right: 1px solid #ccc;
}
#right-panel {
width: 70%;
}
textarea {
width: 100%;
height: 150px;
resize: none;
padding: 10px;
box-sizing: border-box;
font-family: monospace;
font-size: 14px;
}
button {
margin-top: 10px;
padding: 10px 20px;
background-color: #3f51b5;
color: white;
border: none;
cursor: pointer;
font-size: 16px;
}
button:hover {
background-color: #303f9f;
}
.node {
cursor: pointer;
}
.node circle {
fill: #69b3a2;
stroke: #333;
stroke-width: 1.5px;
}
.node text {
font: 12px sans-serif;
pointer-events: none;
}
.link {
fill: none;
stroke: #555;
stroke-opacity: 0.4;
stroke-width: 1.5px;
}
.log-entry {
border-left: 3px solid #3f51b5;
padding-left: 10px;
margin: 5px 0;
}
.log-header {
font-weight: bold;
cursor: pointer;
}
.log-content {
margin-left: 20px;
display: none;
}
.important {
opacity: 1 !important;
}
.unimportant {
opacity: 0.3;
}
.level-I {
color: #2e7d32;
}
.level-E {
color: #c62828;
}
</style>
</head>
<body>
<header>日志可视化工具</header>
<div id="container">
<div id="left-panel">
<h3>日志输入</h3>
<textarea id="log-input" placeholder="在此粘贴日志内容..."></textarea>
<button id="process-btn">生成可视化</button>
<h3>线程关系</h3>
<svg id="thread-svg" width="100%" height="600"></svg>
</div>
<div id="right-panel">
<h3>日志跟踪</h3>
<div id="log-trace"></div>
</div>
</div>
<script>
// 定义全局变量
let threadData = null;
let logMap = {};
let selectedThreadId = null;
document.getElementById('process-btn').addEventListener('click', () => {
const logText = document.getElementById('log-input').value;
if (!logText.trim()) {
alert('请在日志输入区域粘贴日志内容。');
return;
}
// 解析日志
const logs = parseLogs(logText);
// 构建线程关系
threadData = buildThreadHierarchy(logs);
// 构建日志映射
logMap = buildLogMap(logs);
// 绘制线程关系图
drawThreadGraph(threadData);
// 清空日志跟踪
document.getElementById('log-trace').innerHTML = '';
});
/**
* 解析日志文本为日志对象数组
* @param {string} logText
* @returns {Array}
*/
function parseLogs(logText) {
const logLines = logText.split('\n').filter(line => line.trim() !== '');
const logs = logLines.map(line => {
const regex = /^([IE]\d{3}):(\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3})\((\d+)\|(\d+)\)([^:]+):\s*(.+)$/;
const match = line.match(regex);
if (match) {
return {
level: match[1].charAt(0),
timestamp: new Date(`2023-${match[2].replace('-', '/').replace(' ', 'T')}`), // 假设年份为2023
processId: match[3],
threadId: match[4],
tag: match[5],
content: match[6],
original: line
};
}
return null;
}).filter(log => log !== null);
// 按时间排序
logs.sort((a, b) => a.timestamp - b.timestamp);
return logs;
}
/**
* 构建线程的层级关系
* 假设线程的创建关系可以通过时间顺序推断,父线程在子线程之前
* @param {Array} logs
* @returns {Object} Hierarchical thread data
*/
function buildThreadHierarchy(logs) {
const threads = {};
logs.forEach(log => {
if (!threads[log.threadId]) {
threads[log.threadId] = {
id: log.threadId,
logs: [],
children: [],
parent: null,
startTime: log.timestamp,
endTime: log.timestamp
};
}
threads[log.threadId].logs.push(log);
if (log.timestamp < threads[log.threadId].startTime) {
threads[log.threadId].startTime = log.timestamp;
}
if (log.timestamp > threads[log.threadId].endTime) {
threads[log.threadId].endTime = log.timestamp;
}
});
// 转换为数组
const threadList = Object.values(threads);
// 构建父子关系
threadList.forEach(thread => {
threadList.forEach(other => {
if (thread.id !== other.id &&
thread.startTime <= other.startTime &&
thread.endTime >= other.endTime) {
if (!other.parent || thread.startTime > threads[other.parent].startTime) {
other.parent = thread.id;
}
}
});
});
// 构建树状结构
const rootThreads = threadList.filter(t => !t.parent);
rootThreads.forEach(root => {
buildChildren(root, threadList);
});
return { name: "Threads", children: rootThreads };
}
/**
* 递归构建子线程
* @param {Object} parent
* @param {Array} threadList
*/
function buildChildren(parent, threadList) {
parent.children = threadList.filter(t => t.parent === parent.id);
parent.children.forEach(child => buildChildren(child, threadList));
}
/**
* 构建日志映射,以线程ID为键
* @param {Array} logs
* @returns {Object}
*/
function buildLogMap(logs) {
const map = {};
logs.forEach(log => {
if (!map[log.threadId]) {
map[log.threadId] = [];
}
map[log.threadId].push(log);
});
return map;
}
/**
* 绘制线程关系图
* @param {Object} data
*/
function drawThreadGraph(data) {
const svg = d3.select("#thread-svg");
svg.selectAll("*").remove(); // 清空之前的图
const width = +svg.attr("width");
const height = 600;
const treeLayout = d3.tree().size([height, width * 0.7]);
const root = d3.hierarchy(data);
treeLayout(root);
// 添加连线
svg.append("g")
.selectAll(".link")
.data(root.links())
.enter()
.append("path")
.attr("class", "link")
.attr("d", d3.linkHorizontal()
.x(d => d.y)
.y(d => d.x));
// 添加节点
const node = svg.append("g")
.selectAll(".node")
.data(root.descendants())
.enter()
.append("g")
.attr("class", "node")
.attr("transform", d => `translate(${d.y},${d.x})`)
.on("click", (event, d) => {
selectedThreadId = d.data.id;
displayLogTrace(d.data.id);
})
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
node.append("circle")
.attr("r", 20)
.attr("fill", d => d.children ? "#1f77b4" : "#ff7f0e");
node.append("text")
.attr("dy", 4)
.attr("x", d => d.children ? -25 : 25)
.style("text-anchor", d => d.children ? "end" : "start")
.text(d => `Thread ${d.data.id}`)
.style("font-size", "12px")
.style("fill", "#fff");
// 缩放和拖拽
const zoom = d3.zoom()
.scaleExtent([0.1, 10])
.on("zoom", (event) => {
svg.selectAll("g").attr("transform", event.transform);
});
svg.call(zoom);
function dragstarted(event, d) {
d3.select(this).raise().attr("stroke", "black");
}
function dragged(event, d) {
d3.select(this).attr("transform", `translate(${event.x},${event.y})`);
}
function dragended(event, d) {
d3.select(this).attr("stroke", null);
}
}
/**
* 显示选中线程的日志跟踪
* @param {string} threadId
*/
function displayLogTrace(threadId) {
const logs = logMap[threadId] || [];
const hierarchicalLogs = buildLogHierarchy(logs);
const container = document.getElementById('log-trace');
container.innerHTML = '';
if (hierarchicalLogs.length === 0) {
container.innerText = '无日志信息。';
return;
}
hierarchicalLogs.forEach(logTree => {
const logElement = createLogElement(logTree);
container.appendChild(logElement);
});
}
/**
* 构建日志的层级结构
* @param {Array} logs
* @returns {Array}
*/
function buildLogHierarchy(logs) {
const stack = [];
const roots = [];
logs.forEach(log => {
if (log.content.endsWith('Entered...')) {
const node = { log: log, children: [], important: true };
if (stack.length > 0) {
stack[stack.length - 1].children.push(node);
} else {
roots.push(node);
}
stack.push(node);
} else if (log.content.endsWith('Exited...')) {
stack.pop();
} else {
const node = { log: log, children: [], important: true };
if (stack.length > 0) {
stack[stack.length - 1].children.push(node);
} else {
roots.push(node);
}
}
});
return roots;
}
/**
* 创建日志元素的HTML结构
* @param {Object} node
* @returns {HTMLElement}
*/
function createLogElement(node) {
const div = document.createElement('div');
div.classList.add('log-entry');
const header = document.createElement('div');
header.classList.add('log-header', `level-${node.log.level}`);
header.innerText = `[${formatTimestamp(node.log.timestamp)}] [${node.log.level}] ${node.log.content}`;
header.addEventListener('click', () => {
const contentDiv = header.nextElementSibling;
contentDiv.style.display = contentDiv.style.display === 'none' ? 'block' : 'none';
});
// 标记重要性
header.addEventListener('dblclick', () => {
node.important = !node.important;
if (node.important) {
header.classList.remove('unimportant');
header.classList.add('important');
} else {
header.classList.remove('important');
header.classList.add('unimportant');
}
// 递归更新子节点
updateImportance(node.children, node.important);
});
const content = document.createElement('div');
content.classList.add('log-content');
node.children.forEach(child => {
const childElement = createLogElement(child);
content.appendChild(childElement);
});
div.appendChild(header);
div.appendChild(content);
return div;
}
/**
* 递归更新节点及其子节点的显著性
* @param {Array} children
* @param {boolean} parentImportant
*/
function updateImportance(children, parentImportant) {
children.forEach(child => {
child.important = parentImportant;
const headers = document.querySelectorAll('.log-header');
headers.forEach(header => {
if (header.innerText.includes(child.log.content)) {
if (child.important) {
header.classList.remove('unimportant');
header.classList.add('important');
} else {
header.classList.remove('important');
header.classList.add('unimportant');
}
}
});
if (child.children.length > 0) {
updateImportance(child.children, child.important);
}
});
}
/**
* 格式化时间戳
* @param {Date} date
* @returns {string}
*/
function formatTimestamp(date) {
const pad = (num) => num.toString().padStart(2, '0');
return `${pad(date.getMonth()+1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}.${date.getMilliseconds()}`;
}
</script>
</body>
</html>