From 033a7bffb30a76875305b377aa92fc3893d74be9 Mon Sep 17 00:00:00 2001 From: linyuchen Date: Sat, 27 Apr 2024 11:45:24 +0800 Subject: [PATCH] refactor: log --- src/common/data.ts | 2 +- src/common/utils/ConfigBase.ts | 53 ++++++++++++++++++++++++++++++++++ src/common/utils/db.ts | 40 ++++++++++++------------- src/common/utils/log.ts | 6 ++-- src/core | 2 +- src/index.ts | 3 +- src/onebot11/config.ts | 36 ++--------------------- src/onebot11/log.ts | 13 +++++++++ src/onebot11/main.ts | 25 ++++++++++++---- 9 files changed, 113 insertions(+), 67 deletions(-) create mode 100644 src/common/utils/ConfigBase.ts create mode 100644 src/onebot11/log.ts diff --git a/src/common/data.ts b/src/common/data.ts index fdee5687..234cad8a 100644 --- a/src/common/data.ts +++ b/src/common/data.ts @@ -49,7 +49,7 @@ export async function getFriend(uinOrUid: string): Promise { } } -export async function getGroup(qq: string): Promise { +export async function getGroup(qq: string | number): Promise { const group = groups.get(qq.toString()); return group; } diff --git a/src/common/utils/ConfigBase.ts b/src/common/utils/ConfigBase.ts new file mode 100644 index 00000000..dcf0cd3d --- /dev/null +++ b/src/common/utils/ConfigBase.ts @@ -0,0 +1,53 @@ +import path from 'node:path'; +import fs from 'node:fs'; +import { logDebug, logError } from '@/common/utils/log'; + +const configDir = path.resolve(__dirname, 'config'); +fs.mkdirSync(configDir, { recursive: true }); + + +export class ConfigBase{ + + constructor() { + } + + getConfigPath(): string { + throw new Error('Method not implemented.'); + } + + read() { + const configPath = this.getConfigPath(); + if (!fs.existsSync(configPath)) { + try{ + fs.writeFileSync(configPath, JSON.stringify(this, null, 2)); + logDebug(`配置文件${configPath}已创建, 修改此文件后重启NapCat生效`); + } + catch (e: any) { + logError(`创建配置文件 ${configPath} 时发生错误:`, e.message); + } + return this; + } + try { + const data = JSON.parse(fs.readFileSync(configPath, 'utf-8')); + logDebug(`配置文件${configPath}已加载`, data); + Object.assign(this, data); + return this; + } catch (e: any) { + if (e instanceof SyntaxError) { + logError(`配置文件 ${configPath} 格式错误,请检查配置文件:`, e.message); + } else { + logError(`读取配置文件 ${configPath} 时发生错误:`, e.message); + } + return this; + } + } + + save(config: T) { + const configPath = this.getConfigPath(); + try { + fs.writeFileSync(configPath, JSON.stringify(config, null, 2)); + } catch (e: any) { + logError(`保存配置文件 ${configPath} 时发生错误:`, e.message); + } + } +} diff --git a/src/common/utils/db.ts b/src/common/utils/db.ts index 7ca91e50..44deddb5 100644 --- a/src/common/utils/db.ts +++ b/src/common/utils/db.ts @@ -1,7 +1,7 @@ import { ElementType, FileElement, PicElement, PttElement, RawMessage, VideoElement } from '../../core/src/entities'; import sqlite3 from 'sqlite3'; -import { log } from '@/common/utils/log'; +import { log, logDebug, logError } from '@/common/utils/log'; type DBMsg = { id: number, @@ -33,7 +33,7 @@ class DBUtilBase { } this.db = new sqlite3.Database(dbPath, sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, (err) => { if (err) { - log('Could not connect to database', err); + logError('Could not connect to database', err); return; } this.createTable(); @@ -56,7 +56,7 @@ class DBUtil extends DBUtilBase { super(); const interval = 1000 * 60 * 10; // 10分钟清理一次缓存 setInterval(() => { - log('清理消息缓存'); + logDebug('清理消息缓存'); this.msgCache.forEach((msg, key) => { if ((Date.now() - parseInt(msg.msgTime) * 1000) > interval) { this.msgCache.delete(key); @@ -78,7 +78,7 @@ class DBUtil extends DBUtilBase { )`; this.db!.run(createTableSQL, function (err) { if (err) { - log('Could not create table', err); + logError('Could not create table', err); } }); @@ -98,7 +98,7 @@ class DBUtil extends DBUtilBase { )`; this.db!.run(createFileTableSQL, function (err) { if (err) { - log('Could not create table files', err); + logError('Could not create table files', err); } }); @@ -111,7 +111,7 @@ class DBUtil extends DBUtilBase { )`; this.db!.run(createTempUinTableSQL, function (err) { if (err) { - log('Could not create table temp_uins', err); + logError('Could not create table temp_uins', err); } }); } @@ -122,7 +122,7 @@ class DBUtil extends DBUtilBase { stmt.get(...params, (err: any, row: DBMsg) => { // log("getMsg", row, err); if (err) { - log('Could not get msg by short id', err); + logError('Could not get msg by short id', err); resolve(null); } try { @@ -154,10 +154,10 @@ class DBUtil extends DBUtilBase { } async addMsg(msg: RawMessage, update = true): Promise { - log('正在记录消息到数据库', msg.msgId); + logDebug('正在记录消息到数据库', msg.msgId); const existMsg = await this.getMsgByLongId(msg.msgId); if (existMsg) { - // log('消息已存在,更新数据库', msg.msgId); + // logDebug('消息已存在,更新数据库', msg.msgId); if (update) this.updateMsg(msg).then(); return existMsg.id!; } @@ -170,19 +170,19 @@ class DBUtil extends DBUtilBase { stmt.run(msg.msgId, msg.msgSeq, msg.peerUid, JSON.stringify(msg), function (err: any) { if (err) { if (err.errno === 19) { - // log('消息已存在,更新数据库', msg.msgId); + // logDebug('消息已存在,更新数据库', msg.msgId); dbInstance.getMsgByLongId(msg.msgId).then((msg: RawMessage | null) => { if (msg) { dbInstance.msgCache.set(msg.msgId, msg); - // log('获取消息短id成功', msg.id); + // logDebug('获取消息短id成功', msg.id); resolve(msg.id!); } else { - log('db could not get msg by long id', err); + logError('db could not get msg by long id', err); resolve(-1); } }); } else { - log('db could not add msg', err); + logError('db could not add msg', err); resolve(-1); } } else { @@ -210,7 +210,7 @@ class DBUtil extends DBUtilBase { try { stmt.run(JSON.stringify(msg), msg.msgSeq, msg.msgId); } catch (e) { - log('updateMsg db error', e); + logError('updateMsg db error', e); } } @@ -224,7 +224,7 @@ class DBUtil extends DBUtilBase { file.msgId, function (err: any) { if (err) { - log('db could not add file', err); + logError('db could not add file', err); reject(err); } resolve(null); @@ -237,7 +237,7 @@ class DBUtil extends DBUtilBase { return new Promise((resolve, reject) => { stmt.get(...params, (err: any, row: DBFile & { element: string }) => { if (err) { - log('db could not get file cache', err); + logError('db could not get file cache', err); reject(err); } if (row) { @@ -262,7 +262,7 @@ class DBUtil extends DBUtilBase { return new Promise((resolve, reject) => { stmt.run(file.path, file.url,file.uuid, function (err: any) { if (err) { - log('db could not update file cache', err); + logError('db could not update file cache', err); reject(err); } resolve(null); @@ -276,7 +276,7 @@ class DBUtil extends DBUtilBase { return new Promise>((resolve, reject) => { this.db!.all(stmt, (err, rows: { uin: string, uid: string }[]) => { if (err) { - log('db could not get temp uin map', err); + logError('db could not get temp uin map', err); reject(err); } const map: Record = {}; @@ -294,7 +294,7 @@ class DBUtil extends DBUtilBase { return new Promise((resolve, reject) => { this.db!.get(stmt, [uid], (err, row: { uin: string, uid: string }) => { if (err) { - log('db could not get temp uin map', err); + logError('db could not get temp uin map', err); reject(err); } resolve(row?.uid); @@ -309,7 +309,7 @@ class DBUtil extends DBUtilBase { return new Promise((resolve, reject) => { stmt.run(uin, uid, function (err: any) { if (err) { - log('db could not add temp uin', err); + logError('db could not add temp uin', err); reject(err); } resolve(null); diff --git a/src/common/utils/log.ts b/src/common/utils/log.ts index 52e8a802..ae7e8912 100644 --- a/src/common/utils/log.ts +++ b/src/common/utils/log.ts @@ -25,9 +25,9 @@ function genLogConfig(fileLogLevel: LogLevel, consoleLogLevel: LogLevel) { } }, categories: { - default: { appenders: ['fileAppender', 'consoleAppender'], level: 'info' }, // 默认情况下同时输出到文件和控制台 + default: { appenders: ['fileAppender', 'consoleAppender'], level: 'debug' }, // 默认情况下同时输出到文件和控制台 file: { appenders: ['fileAppender'], level: fileLogLevel }, - console: { appenders: ['consoleAppender'], level: fileLogLevel } + console: { appenders: ['consoleAppender'], level: consoleLogLevel } } }; } @@ -59,7 +59,7 @@ function formatMsg(msg: any[]){ } logMsg += msgItem + ' '; } - return logMsg; + return '\n' + logMsg + '\n'; } function _log(level: LogLevel, ...args: any[]){ diff --git a/src/core b/src/core index 4590fe89..703cf03e 160000 --- a/src/core +++ b/src/core @@ -1 +1 @@ -Subproject commit 4590fe89ddf124c73f513d738ccc202e1df430e7 +Subproject commit 703cf03e708c7ab011c6a02f08a2a73329c2969f diff --git a/src/index.ts b/src/index.ts index 15ffd8cb..7deb360e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -14,7 +14,6 @@ program const cmdOptions = program.opts(); // console.log(process.argv); -setLogLevel(LogLevel.DEBUG, LogLevel.DEBUG); checkVersion().then((remoteVersion: string) => { const localVersion = require('./package.json').version; @@ -56,7 +55,7 @@ const quickLoginQQ = cmdOptions.qq; // napCatCore.qrLogin().then().catch(console.error); // }); if (quickLoginQQ) { - console.log('quick login', quickLoginQQ); + log('正在快速登录 ', quickLoginQQ); napCatCore.quickLogin(quickLoginQQ).then(res=>{ // log('快速登录结果:', res); }).catch((e) => { diff --git a/src/onebot11/config.ts b/src/onebot11/config.ts index 701e9f66..110725d3 100644 --- a/src/onebot11/config.ts +++ b/src/onebot11/config.ts @@ -2,6 +2,7 @@ import fs from 'node:fs'; import path from 'node:path'; import { selfInfo } from '@/common/data'; import { logDebug, logError } from '@/common/utils/log'; +import { ConfigBase } from '@/common/utils/ConfigBase'; export interface OB11Config { httpPort: number; @@ -29,7 +30,7 @@ export interface OB11Config { const ob11ConfigDir = path.resolve(__dirname, 'config'); fs.mkdirSync(ob11ConfigDir, { recursive: true }); -class Config implements OB11Config { +class Config extends ConfigBase implements OB11Config { httpPort: number = 3000; httpPostUrls: string[] = []; httpSecret = ''; @@ -47,42 +48,9 @@ class Config implements OB11Config { heartInterval = 30000; token = ''; - constructor() { - } - getConfigPath() { return path.join(ob11ConfigDir, `onebot11_${selfInfo.uin}.json`); } - - read() { - const ob11ConfigPath = this.getConfigPath(); - if (!fs.existsSync(ob11ConfigPath)) { - logError(`onebot11配置文件 ${ob11ConfigPath} 不存在, 现已创建,请修改配置文件后重启NapCat`); - this.save(); - return this; - } - const data = fs.readFileSync(ob11ConfigPath, 'utf-8'); - try { - const jsonData = JSON.parse(data); - logDebug('Onebot 11配置文件已加载', jsonData); - Object.assign(this, jsonData); - // eslint-disable-next-line - } catch (e: any) { - if (e instanceof SyntaxError) { - logError(`配置文件 ${ob11ConfigPath} 格式错误,请检查配置文件:`, e.message); - }else{ - logError(`读取配置文件 ${ob11ConfigPath} 时发生错误:`, e.message); - } - } - return this; - } - - save(newConfig: OB11Config | null = null) { - if (newConfig) { - Object.assign(this, newConfig); - } - fs.writeFileSync(this.getConfigPath(), JSON.stringify(this, null, 4)); - } } export const ob11Config = new Config(); diff --git a/src/onebot11/log.ts b/src/onebot11/log.ts new file mode 100644 index 00000000..94f8e561 --- /dev/null +++ b/src/onebot11/log.ts @@ -0,0 +1,13 @@ +import { OB11Message } from '@/onebot11/types'; +import { log } from '@/common/utils/log'; +import { getGroup } from '@/common/data'; + +export async function logMessage(ob11Message: OB11Message){ + let prefix = ''; + if (ob11Message.message_type === 'group') { + const group = await getGroup(ob11Message.group_id!); + prefix = `群[${group?.groupName}(${ob11Message.group_id})] `; + } + const msgString = `${prefix}${ob11Message.sender.nickname}(${ob11Message.sender.user_id}): ${ob11Message.raw_message}`; + log(msgString); +} diff --git a/src/onebot11/main.ts b/src/onebot11/main.ts index 1d4a5593..a8e298ca 100644 --- a/src/onebot11/main.ts +++ b/src/onebot11/main.ts @@ -26,6 +26,7 @@ import { OB11GroupAdminNoticeEvent } from '@/onebot11/event/notice/OB11GroupAdmi import { GroupDecreaseSubType, OB11GroupDecreaseEvent } from '@/onebot11/event/notice/OB11GroupDecreaseEvent'; import { OB11FriendRecallNoticeEvent } from '@/onebot11/event/notice/OB11FriendRecallNoticeEvent'; import { OB11GroupRecallNoticeEvent } from '@/onebot11/event/notice/OB11GroupRecallNoticeEvent'; +import { logMessage } from '@/onebot11/log'; export class NapCatOnebot11 { @@ -40,6 +41,16 @@ export class NapCatOnebot11 { public onReady() { logDebug('ob11 ready'); ob11Config.read(); + const serviceInfo = ` + HTTP服务 ${ob11Config.enableHttp ? '已启动' : '未启动'}, 端口: ${ob11Config.httpPort} + HTTP上报服务 ${ob11Config.enableHttpPost ? '已启动' : '未启动'}, 上报地址: ${ob11Config.httpPostUrls} + WebSocket服务 ${ob11Config.enableWs ? '已启动' : '未启动'}, 端口: ${ob11Config.wsPort} + WebSocket反向服务 ${ob11Config.enableWsReverse ? '已启动' : '未启动'}, 反向地址: ${ob11Config.wsReverseUrls} + `; + log(serviceInfo); + NTQQUserApi.getUserDetailInfo(selfInfo.uin).then(user => { + selfInfo.nick = user.nick; + }).catch(logError); if (ob11Config.enableHttp) { ob11HTTPServer.start(ob11Config.httpPort); } @@ -78,19 +89,19 @@ export class NapCatOnebot11 { new Promise((resolve) => { dbUtil.addMsg(m).then(msgShortId => { m.id = msgShortId; - this.postReceiveMsg([m]).then().catch(log); - }).catch(log); + this.postReceiveMsg([m]).then().catch(logError); + }).catch(logError); }).then(); } }; msgListener.onMsgInfoListUpdate = (msgList) => { - this.postRecallMsg(msgList).then().catch(log); + this.postRecallMsg(msgList).then().catch(logError); }; msgListener.onAddSendMsg = (msg) => { if (ob11Config.reportSelfMessage) { dbUtil.addMsg(msg).then(id => { msg.id = id; - this.postReceiveMsg([msg]).then().catch(log); + this.postReceiveMsg([msg]).then().catch(logError); }); } }; @@ -100,7 +111,7 @@ export class NapCatOnebot11 { // BuddyListener const buddyListener = new BuddyListener(); buddyListener.onBuddyReqChange = ((req) => { - this.postFriendRequest(req.buddyReqs).then().catch(log); + this.postFriendRequest(req.buddyReqs).then().catch(logError); }); napCatCore.addListener(buddyListener); logDebug('ob11 buddy listener added'); @@ -126,11 +137,12 @@ export class NapCatOnebot11 { async postReceiveMsg(msgList: RawMessage[]) { const { debug, reportSelfMessage } = ob11Config; for (const message of msgList) { - log('收到新消息', message); + logDebug('收到新消息', message); // if (message.senderUin !== selfInfo.uin){ // message.msgShortId = await dbUtil.addMsg(message); // } OB11Constructor.message(message).then((msg) => { + logMessage(msg).then().catch(logError); if (debug) { msg.raw = message; } else { @@ -138,6 +150,7 @@ export class NapCatOnebot11 { return; } } + logDebug('收到消息: ', msg); const isSelfMsg = msg.user_id.toString() == selfInfo.uin; if (isSelfMsg && !reportSelfMessage) { return;