71 lines
1.8 KiB
JavaScript
71 lines
1.8 KiB
JavaScript
const { getDBConnection } = require('./file-utils');
|
|
|
|
// 获取所有系统日志
|
|
function getSystemLogs() {
|
|
try {
|
|
const db = getDBConnection(true);
|
|
|
|
const logs = db.prepare(`
|
|
SELECT id, time, level, user, source, log
|
|
FROM SystemLog
|
|
ORDER BY time DESC
|
|
`).all();
|
|
|
|
return logs;
|
|
} catch (error) {
|
|
console.error('获取系统日志失败:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
// 添加系统日志
|
|
function addSystemLog(logData) {
|
|
try {
|
|
// 验证必填字段
|
|
if (!logData.level || !logData.source) {
|
|
throw new Error('日志级别和来源是必填字段');
|
|
}
|
|
|
|
const db = getDBConnection();
|
|
|
|
// 获取当前本地时间
|
|
const now = new Date();
|
|
const year = now.getFullYear();
|
|
const month = String(now.getMonth() + 1).padStart(2, '0');
|
|
const day = String(now.getDate()).padStart(2, '0');
|
|
const hours = String(now.getHours()).padStart(2, '0');
|
|
const minutes = String(now.getMinutes()).padStart(2, '0');
|
|
const seconds = String(now.getSeconds()).padStart(2, '0');
|
|
const localDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
|
|
|
|
// 在插入日志时添加时间
|
|
const result = db.prepare(`
|
|
INSERT INTO SystemLog (level, user, source, log, time)
|
|
VALUES (?, ?, ?, ?, ?)
|
|
`).run(
|
|
logData.level,
|
|
logData.user || null,
|
|
logData.source,
|
|
logData.log || null,
|
|
localDateTime
|
|
);
|
|
|
|
if (result.changes > 0) {
|
|
return {
|
|
success: true,
|
|
id: result.lastInsertRowid,
|
|
message: '系统日志添加成功'
|
|
};
|
|
} else {
|
|
throw new Error('系统日志添加失败');
|
|
}
|
|
} catch (error) {
|
|
console.error('添加系统日志失败:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
getSystemLogs,
|
|
addSystemLog
|
|
};
|