diff --git a/bun.lock b/bun.lock index 6546001..71ead25 100644 --- a/bun.lock +++ b/bun.lock @@ -101,11 +101,11 @@ "@egg/hooks": ["@egg/hooks@1.2.0", "https://git.yingbo.im:333/api/packages/zhaoyingbo/npm/%40egg%2Fhooks/-/1.2.0/hooks-1.2.0.tgz", { "dependencies": { "lodash": "*" } }, "sha512-pH9SViGCvdNHdXIpeqqgGODYPxq0HF+b0obKxcC11O1TT6QEpDRWgImZPRdFz0SwxG9VKjJFD+MuZpXmzar+kg=="], - "@egg/lark-msg-tool": ["@egg/lark-msg-tool@1.21.0", "https://git.yingbo.im:333/api/packages/zhaoyingbo/npm/%40egg%2Flark-msg-tool/-/1.21.0/lark-msg-tool-1.21.0.tgz", { "dependencies": { "@egg/logger": "^1.6.0", "winston": "*" } }, "sha512-+Vz56wgb9BBiAowmXCdcsLMKTQoBrXADalDAbI9PiLswIw6gAgQtoy8bixIiyGuKM0QB8McVBbvzc04ukJhUKw=="], + "@egg/lark-msg-tool": ["@egg/lark-msg-tool@1.21.1", "https://git.yingbo.im:333/api/packages/zhaoyingbo/npm/%40egg%2Flark-msg-tool/-/1.21.1/lark-msg-tool-1.21.1.tgz", { "dependencies": { "@egg/logger": "^1.7.0", "winston": "*" } }, "sha512-T4d3p4MGFmxEp2QsGXwoiOpHHOC28DWWGEM6/K36U6uOAvBjkE3RGoEdC2qD/25UZq4UCJuWvf5gIrSI2UH2Eg=="], - "@egg/logger": ["@egg/logger@1.6.0", "https://git.yingbo.im:333/api/packages/zhaoyingbo/npm/%40egg%2Flogger/-/1.6.0/logger-1.6.0.tgz", { "dependencies": { "winston": "*", "winston-daily-rotate-file": "*" } }, "sha512-BgtK74YK/7q/K3iUs3FGp3B+v4/IJlD9bgrJ/S7iHwgtgMgzl/4avZ5sXNHoZ7xPRhEuOh0ie7Br3MAWFnuuYg=="], + "@egg/logger": ["@egg/logger@1.7.0", "https://git.yingbo.im:333/api/packages/zhaoyingbo/npm/%40egg%2Flogger/-/1.7.0/logger-1.7.0.tgz", { "dependencies": { "winston": "*", "winston-daily-rotate-file": "*" } }, "sha512-7JanJKWCrffj2BzKQDaB9VDzy466wTRraeVn2f13OLYfeT40hkY5rtK0ngibFdpJQgjzwkcZJQQIa9TFJAQapw=="], - "@egg/net-tool": ["@egg/net-tool@1.32.2", "https://git.yingbo.im:333/api/packages/zhaoyingbo/npm/%40egg%2Fnet-tool/-/1.32.2/net-tool-1.32.2.tgz", { "dependencies": { "@egg/logger": "^1.6.0", "@gitbeaker/rest": "*", "winston": "*" } }, "sha512-e0iWiVob2DTIKfIDNCgBH9zp7B/MquWvHKmb7DH1lJa6YeyA0Nhp8h3EYZBUTwrUzUyaY83qqMXBJYgjg5zkKA=="], + "@egg/net-tool": ["@egg/net-tool@1.32.3", "https://git.yingbo.im:333/api/packages/zhaoyingbo/npm/%40egg%2Fnet-tool/-/1.32.3/net-tool-1.32.3.tgz", { "dependencies": { "@egg/logger": "^1.7.0", "@gitbeaker/rest": "*", "winston": "*" } }, "sha512-DpzZttIa+/PeB+PvLPCPoMEwHXuVVo1Ntob6dfuz8Lq1frBQ6G7LuDT0xm1rFjDnJcOauUum0SYmkhNsFQauJw=="], "@egg/path-tool": ["@egg/path-tool@1.4.1", "https://git.yingbo.im:333/api/packages/zhaoyingbo/npm/%40egg%2Fpath-tool/-/1.4.1/path-tool-1.4.1.tgz", {}, "sha512-PZE5kMRidZh3ahhmQJQG62wcApbCdmZihKQXYI5eAOhIbwm0hgB1sOUsais94sS9uEBQ+QpH0Om7sZ9w84rumw=="], diff --git a/constant/config.ts b/constant/config.ts index 9c6acf6..3e3ce7b 100644 --- a/constant/config.ts +++ b/constant/config.ts @@ -30,13 +30,14 @@ const initAppConfig = async () => { for (const env of envList) { APP_CONFIG[env.key] = env.value } - logger.info(`Get env list: ${JSON.stringify(APP_CONFIG)}`) + logger.info("获取环境变量列表", { envList: APP_CONFIG }) + // 获取所有应用信息 const appList = await pbClient.collection("app").getFullList() for (const app of appList) { APP_MAP[app.name] = app } - logger.info(`Get app list: ${JSON.stringify(APP_MAP)}`) + logger.info("获取应用列表", { appList: APP_MAP }) } export default initAppConfig diff --git a/controller/gitlabEvent/register.ts b/controller/gitlabEvent/register.ts index 47be9d0..86e51e0 100644 --- a/controller/gitlabEvent/register.ts +++ b/controller/gitlabEvent/register.ts @@ -45,7 +45,7 @@ const openFunc = async ( const { logger, larkBody, larkService, larkCard, db } = ctx const cardGender = larkCard.child("gitlabAgent") if (!projectId) { - logger.error(`项目ID格式错误,项目ID:${projectId}`) + logger.error("项目ID格式错误", { projectId }) await larkService.message.replyCard( larkBody.messageId, cardGender.genErrorCard("项目ID格式错误,请检查项目ID是否正确") @@ -57,7 +57,7 @@ const openFunc = async ( ctx.gitlabService ) if (!project) { - logger.error(`项目不存在,项目ID:${projectId}`) + logger.error("项目不存在", { projectId }) await larkService.message.replyCard( larkBody.messageId, cardGender.genErrorCard( @@ -70,7 +70,7 @@ const openFunc = async ( [func]: true, }) if (!newProj) { - logger.error(`更新项目失败,项目ID:${projectId}`) + logger.error("更新项目失败", { projectId }) await larkService.message.replyCard( larkBody.messageId, cardGender.genErrorCard("操作失败,请稍后再试") @@ -94,7 +94,7 @@ const closeFunc = async ( const { logger, larkBody, larkService, larkCard, db } = ctx const cardGender = larkCard.child("gitlabAgent") if (!projectId) { - logger.error(`项目ID格式错误,项目ID:${projectId}`) + logger.error("项目ID格式错误", { projectId }) await larkService.message.replyCard( larkBody.messageId, cardGender.genErrorCard("项目ID格式错误,请检查项目ID是否正确") @@ -103,7 +103,7 @@ const closeFunc = async ( } const project = await db.gitlabProject.getByProjectId(projectId) if (!project) { - logger.error(`项目不存在,项目ID:${projectId}`) + logger.error("项目不存在", { projectId }) await larkService.message.replyCard( larkBody.messageId, cardGender.genSuccessCard( @@ -116,7 +116,7 @@ const closeFunc = async ( [func]: false, }) if (!newProj) { - logger.error(`更新项目失败,项目ID:${projectId}`) + logger.error("更新项目失败", { projectId }) await larkService.message.replyCard( larkBody.messageId, cardGender.genErrorCard("操作失败,请稍后再试") diff --git a/controller/groupAgent/agent.ts b/controller/groupAgent/agent.ts index 2a063c2..9dacf8b 100644 --- a/controller/groupAgent/agent.ts +++ b/controller/groupAgent/agent.ts @@ -18,7 +18,7 @@ const agent = async (ctx: Context) => { ) // 使用大模型解析用户输入 const { startTime, endTime } = await llm.timeParser(msgText, requestId) - logger.info(`Parsed time: startTime: ${startTime}, endTime: ${endTime}`) + logger.info("解析的时间范围", { startTime, endTime }) // 更新卡片 await message.updateOrReply( cardGender.genPendingCard("正在爬楼中,请稍等...") @@ -35,7 +35,7 @@ const agent = async (ctx: Context) => { excludedMessageIds: [loadingMessageId, messageId], excludeMentions: [appInfo.appName], }) - logger.debug(`Chat history: ${JSON.stringify(chatHistory)}`) + logger.debug("获取的聊天记录", { count: chatHistory.length }) // 根据Mention,拼装原始消息 let userInput = rawMsgText.trim() @@ -62,13 +62,14 @@ const agent = async (ctx: Context) => { }, requestId )) as string - logger.info( - `LLM invoked successfully, see detail: http://langfuse.ai.srv/project/cm1j2tkj9001gukrgdvc1swuw/sessions/${requestId}` - ) + logger.info("LLM调用成功", { + requestId, + url: `http://langfuse.ai.srv/project/cm1j2tkj9001gukrgdvc1swuw/sessions/${requestId}`, + }) const cleanedLlmRes = cleanLLMRes(llmRes) await message.updateOrReply(cardGender.genSuccessCard(cleanedLlmRes)) } catch (error: any) { - logger.error(`Failed to invoke llm: ${error.message}`) + logger.error("LLM调用失败", { error: error.message }) await message.updateOrReply( cardGender.genErrorCard("LLM调用失败: " + error.message) ) diff --git a/controller/groupAgent/chatHistory.ts b/controller/groupAgent/chatHistory.ts index c133c72..0baa38e 100644 --- a/controller/groupAgent/chatHistory.ts +++ b/controller/groupAgent/chatHistory.ts @@ -165,9 +165,13 @@ const getChatHistory = async ( [...senders].filter((sender) => !mentions.has(sender)) ) - logger.debug(`Mentions: ${JSON.stringify([...mentions.entries()])}`) - logger.debug(`Senders: ${JSON.stringify([...senders])}`) - logger.debug(`No mention senders: ${JSON.stringify([...noMentionSenders])}`) + logger.debug("获取聊天消息提及用户信息", { + mentions: [...mentions.entries()], + }) + logger.debug("获取消息发送者信息", { senders: [...senders] }) + logger.debug("获取未被提及的发送者信息", { + noMentionSenders: [...noMentionSenders], + }) // 从接口获取用户名 if (noMentionSenders.size !== 0) { @@ -175,13 +179,13 @@ const getChatHistory = async ( const { data: { items }, } = await larkService.user.batchGet([...noMentionSenders]) - logger.debug(`Get user info: ${JSON.stringify(items)}`) + logger.debug("获取用户详细信息", { items }) for (const item of items) { mentions.set(item.open_id, item.name) } } catch (error) { // 报错了可以不处理,只是没有名字而已 - logger.error(`Failed to get user info: ${error}`) + logger.error("获取用户信息失败", { error }) } } diff --git a/controller/groupAgent/report.ts b/controller/groupAgent/report.ts index 9007def..3223bcb 100644 --- a/controller/groupAgent/report.ts +++ b/controller/groupAgent/report.ts @@ -26,7 +26,7 @@ const genSummary = async ( appInfo, larkService: { message }, } = ctx - logger.info(`genSummary ${timeScope} by ${trigger}`) + logger.info("生成摘要", { timeScope, trigger }) const cardGender = larkCard.child("groupAgent") try { if (trigger === "manual") { @@ -128,7 +128,7 @@ const genSummary = async ( const genAllReport = async (timeScope: "daily" | "weekly" = "daily") => { const ctx = await genContextManually() const { logger, db } = ctx - logger.info(`genAllReport ${timeScope}`) + logger.info("生成所有群聊总结", { timeScope }) try { // 获取所有需要自动总结的群组 const chatList = await db.chat.getNeedSummaryChats("all") @@ -163,7 +163,7 @@ const gen4Test = async (ctx: Context, timeScope: "daily" | "weekly") => { larkBody: { chatId }, } = ctx try { - logger.info(`timeScope: ${timeScope}`) + logger.info("手动生成日报或者周报", { timeScope }) // 总结 await genSummary(ctx, timeScope, "manual") } catch (error: any) { diff --git a/controller/intentAgent/index.ts b/controller/intentAgent/index.ts index 65ca3fc..6c480f7 100644 --- a/controller/intentAgent/index.ts +++ b/controller/intentAgent/index.ts @@ -100,13 +100,13 @@ const agent = async (ctx: Context): Promise => { if (parsedIntent) { try { IntentSchema.parse(parsedIntent) - logger.debug("Intent is valid: " + JSON.stringify(parsedIntent)) + logger.debug("意图验证有效", { intent: parsedIntent }) return parsedIntent } catch (e: any) { - logger.error("Invalid intent: " + String(e.errors)) + logger.error("意图验证失败", { error: String(e.errors) }) } } else { - logger.error("Parsed intent is null") + logger.error("意图解析为空", { rawIntent }) } attempts++ diff --git a/controller/reportAgent/index.ts b/controller/reportAgent/index.ts index ea1ee60..143349e 100644 --- a/controller/reportAgent/index.ts +++ b/controller/reportAgent/index.ts @@ -96,7 +96,12 @@ const insert2Sheet = async ( ], ]) } catch (error: any) { - logger.error(`Failed to insert2Sheet: ${error}`) + logger.error("表格数据插入失败", { + error: error.message, + link, + sheetToken, + range, + }) } } @@ -222,7 +227,11 @@ const agent = async (ctx: Context, link: string, userDescription: string) => { ) ) } catch (error: any) { - logger.error(`Failed gen report: ${error}`) + logger.error("简报生成失败", { + error: error.message, + link, + userDescription, + }) await message.updateOrReply( cardGender.genErrorCard(`简报生成失败: ${error.message}`) ) @@ -233,7 +242,7 @@ const agent = async (ctx: Context, link: string, userDescription: string) => { * 解析表格信息 * @param {Context} ctx - 上下文对象 * @param {string} sheetUrl - 表格链接 - * @returns {Promise<{sheetToken: string, range: string}>} - 返回表格信息 + * @returns {Promise<{ sheetToken: string; range: string }>} - 返回表格信息 * @throws {Error} - 当解析失败时抛出错误 */ const parseSheetInfo = async ( @@ -306,7 +315,7 @@ const setSheet = async (ctx: Context, sheetUrl: string) => { cardGender.genSuccessCard("简报汇总表创建成功") ) } catch (error: any) { - logger.error(`Failed setSheet: ${error}`) + logger.error("简报汇总表设置失败", { error: error.message, sheetUrl }) await larkService.message.updateOrReply( cardGender.genErrorCard(`简报汇总表设置失败: ${error.message}`) ) diff --git a/controller/searchAgent/index.ts b/controller/searchAgent/index.ts index ca17816..8c0020b 100644 --- a/controller/searchAgent/index.ts +++ b/controller/searchAgent/index.ts @@ -56,7 +56,7 @@ const agent = async (ctx: Context, query: string) => { const answer = await generateAnswer(ctx, searchRes) await message.updateOrReply(cardGender.genSuccessCard(answer)) } catch (error: any) { - logger.error(`searchAgent error: ${error}`) + logger.error("检索Agent调用失败", { error: error.message }) await message.updateOrReply( cardGender.genErrorCard(`检索失败: ${error.message}`) ) diff --git a/controller/sheet/createKVTemp.ts b/controller/sheet/createKVTemp.ts index 614b791..b388cd7 100644 --- a/controller/sheet/createKVTemp.ts +++ b/controller/sheet/createKVTemp.ts @@ -32,7 +32,7 @@ const create = async ({ const token = `${fileToken}|${tableId}|${viewId}` - logger.info(`create KV bitable successfully: ${{ link, token }}`) + logger.info("创建KV模板成功", { link, token }) return { code: 0, @@ -95,7 +95,7 @@ const createFromEvent = async (ctx: Context) => { cardGender.genTempCard("createKVSuccess", createRes.data) as string ) } catch (e: any) { - logger.error(`create KV bitable failed: ${e.message}`) + logger.error("创建KV模板失败", { error: e.message }) larkService.message.sendCard2Chat( chatId, cardGender.genErrorCard(`创建失败:${e.message}`) as string diff --git a/controller/soupAgent/index.ts b/controller/soupAgent/index.ts index 6dece46..8af3619 100644 --- a/controller/soupAgent/index.ts +++ b/controller/soupAgent/index.ts @@ -22,13 +22,13 @@ const startOrStopGame = async ( } = ctx const cardGender = larkCard.child("soupAgent") if (!chatId) { - logger.error("chatId is required") + logger.error("缺少聊天ID", { chatId }) return } // 获取正在进行中的游戏 const activeGame = await db.soupGame.getActiveOneByChatId(chatId) if (!activeGame) { - logger.info(`chatId: ${chatId} has no active game`) + logger.info("没有找到活跃的游戏", { chatId }) } // 停止游戏 if (!value) { @@ -40,10 +40,10 @@ const startOrStopGame = async ( return } // 有进行中的游戏,关闭游戏 - logger.info(`chatId: ${chatId} is closing the game`) + logger.info("正在关闭游戏", { chatId }) const res = await db.soupGame.close(activeGame.id) if (!res) { - logger.error(`chatId: ${chatId} failed to close the game`) + logger.error("游戏关闭失败", { chatId }) await message.updateOrReply( cardGender.genErrorCard(SoupGameMessage.startFailed) ) @@ -78,17 +78,17 @@ const startOrStopGame = async ( // 开始游戏,有进行中的游戏 if (activeGame) { - logger.info(`chatId: ${chatId} has an active game`) + logger.info("已存在进行中的游戏", { chatId }) await message.updateOrReply( cardGender.genSuccessCard(SoupGameMessage.hasStarted) ) return } - logger.info(`chatId: ${chatId} is starting a new game`) + logger.info("开始新游戏", { chatId }) // 没有进行中的游戏,开始新游戏 const game = await attachService.startSoup() if (!game) { - logger.error(`chatId: ${chatId} failed to start a new game`) + logger.error("新游戏启动失败", { chatId }) await message.updateOrReply( cardGender.genErrorCard(SoupGameMessage.startFailed) ) @@ -103,13 +103,13 @@ const startOrStopGame = async ( } const res = await db.soupGame.create(newSoupGame) if (!res) { - logger.error(`chatId: ${chatId} failed to create a new game`) + logger.error("游戏创建失败", { chatId }) await message.updateOrReply( cardGender.genErrorCard(SoupGameMessage.startFailed) ) return } - logger.info(`chatId: ${chatId} created a new game`) + logger.info("新游戏创建成功", { chatId, gameId: res.id }) // 回复用户模型的消息 await message.updateOrReply( cardGender.genCard("markdownSuccessCard", { @@ -137,7 +137,7 @@ const chat2Soup = async (ctx: Context) => { message.setReplyMessage(messageId, "text") const activeGame = await db.soupGame.getActiveOneByChatId(chatId) if (!activeGame) { - logger.info(`chatId: ${chatId} has no active game`) + logger.info("没有找到活跃的游戏", { chatId }) return } await message.updateOrReply("模型生成中...") @@ -148,7 +148,7 @@ const chat2Soup = async (ctx: Context) => { history: "", }) if (!res) { - logger.error(`chatId: ${chatId} failed to get soup result`) + logger.error("获取汤面结果失败", { chatId }) await message.updateOrReply(SoupGameMessage.chatFailed) return } diff --git a/db/base/index.ts b/db/base/index.ts index 742097f..79809f8 100644 --- a/db/base/index.ts +++ b/db/base/index.ts @@ -56,12 +56,17 @@ class PbToolBase { ) => { try { const result = await fn() - this.logger.debug(`PocketBase ${operation} 成功 [${this.dbName}]`) + this.logger.debug(`PocketBase ${operation} 成功`, { + collection: this.dbName, + operation, + }) return result } catch (err: any) { - this.logger.error( - `PocketBase ${operation} 失败 [${this.dbName}]: ${err.message}` - ) + this.logger.error(`PocketBase ${operation} 失败`, { + collection: this.dbName, + operation, + error: err.message, + }) return null } } @@ -78,7 +83,7 @@ class PbToolBase { * ``` */ public create = async (data: Partial) => { - this.logger.info(`创建${this.dbName}记录`) + this.logger.info(`创建记录`, { collection: this.dbName, data }) return this.managePbError( () => this.pbClient.collection(this.dbName).create(data), "create" @@ -99,7 +104,7 @@ class PbToolBase { * ``` */ public get = async (id: string, options?: RecordOptions) => { - this.logger.info(`获取${this.dbName}记录 [ID: ${id}]`) + this.logger.info(`获取记录`, { collection: this.dbName, id, options }) return this.managePbError( () => this.pbClient.collection(this.dbName).getOne(id, options), "get" @@ -125,7 +130,7 @@ class PbToolBase { data: Partial, options?: RecordOptions ) => { - this.logger.info(`更新${this.dbName}记录 [ID: ${id}]`) + this.logger.info(`更新记录`, { collection: this.dbName, id, data, options }) return this.managePbError( () => this.pbClient.collection(this.dbName).update(id, data, options), "update" @@ -145,7 +150,7 @@ class PbToolBase { * ``` */ public delete = async (id: string, options?: CommonOptions) => { - this.logger.info(`删除${this.dbName}记录 [ID: ${id}]`) + this.logger.info(`删除记录`, { collection: this.dbName, id, options }) return this.managePbError( () => this.pbClient.collection(this.dbName).delete(id, options), "delete" @@ -168,9 +173,12 @@ class PbToolBase { * ``` */ public list = async (options?: RecordFullListOptions) => { - const filterInfo = options?.filter ? ` [过滤: ${options.filter}]` : "" - const sortInfo = options?.sort ? ` [排序: ${options.sort}]` : "" - this.logger.info(`获取${this.dbName}记录列表${filterInfo}${sortInfo}`) + this.logger.info(`获取记录列表`, { + collection: this.dbName, + filter: options?.filter, + sort: options?.sort, + options, + }) return this.managePbError( () => this.pbClient.collection(this.dbName).getFullList(options), "list" @@ -194,7 +202,11 @@ class PbToolBase { filter: string, options?: RecordListOptions ) => { - this.logger.info(`获取${this.dbName}第一条匹配记录 [过滤: ${filter}]`) + this.logger.info(`获取第一条匹配记录`, { + collection: this.dbName, + filter, + options, + }) return this.managePbError( () => this.pbClient.collection(this.dbName).getFirstListItem(filter, options), diff --git a/db/chat/index.ts b/db/chat/index.ts index 0cad199..74a4e82 100644 --- a/db/chat/index.ts +++ b/db/chat/index.ts @@ -87,12 +87,12 @@ class ChatDB extends PbToolBase { public getByCtx = async ({ larkService, larkBody }: Context) => { const { chatId } = larkBody if (!chatId) { - this.logger.error(`chatId is empty`) + this.logger.error("chatId 为空") return null } const chat = await this.getOneByChatId(chatId) if (chat) return chat - this.logger.info(`chat ${chatId} not found, try to get from lark`) + this.logger.info("群聊不在数据库里,尝试从飞书获取", { chatId }) const chatInfo = await larkService.chat.getChatInfo(chatId) if (!chatInfo || chatInfo.code !== 0) return null const { name, avatar, chat_mode } = chatInfo.data diff --git a/index.ts b/index.ts index e21b672..f6769f2 100644 --- a/index.ts +++ b/index.ts @@ -27,8 +27,14 @@ const bunServer = Bun.serve({ path.exact("/sheet") || path.startsWith("/micro_app") ) { - logger.info(`${req.method} ${req.url}`) - logger.debug(`req body: ${ctx.text}`) + // 使用结构化日志,适合JSON模式 + logger.info("收到请求", { + method: req.method, + url: req.url, + }) + logger.debug("请求体内容", { + body: ctx.text, + }) } // 逻辑处理 try { @@ -48,16 +54,18 @@ const bunServer = Bun.serve({ return genResp.healthCheck("hello, there is egg, glade to serve you!") } catch (error: any) { // 错误处理 - logger.error(error.message) + logger.error("服务器错误", { + message: error.message, + stack: error.stack, + }) return genResp.serverError(error.message || "server error") } }, - error(error) { - logger.error(`Error: ${error}`) - logger.error(`Stack: ${error.stack}`) - return new Response("Internal Error", { status: 500 }) - }, port: 3000, }) -logger.info(`Listening on ${bunServer.hostname}:${bunServer.port}`) +// 使用结构化日志记录服务启动信息 +logger.info("服务器启动", { + hostname: bunServer.hostname, + port: bunServer.port, +}) diff --git a/package.json b/package.json index 5a7d21d..38df706 100644 --- a/package.json +++ b/package.json @@ -38,9 +38,9 @@ }, "dependencies": { "@egg/hooks": "^1.2.0", - "@egg/lark-msg-tool": "^1.21.0", - "@egg/logger": "^1.6.0", - "@egg/net-tool": "^1.32.2", + "@egg/lark-msg-tool": "^1.21.1", + "@egg/logger": "^1.7.0", + "@egg/net-tool": "^1.32.3", "@egg/path-tool": "^1.4.1", "@langchain/core": "^0.3.42", "@langchain/langgraph": "^0.2.56", diff --git a/routes/bot/actionMsg.ts b/routes/bot/actionMsg.ts index ff5e91c..adaf1c2 100644 --- a/routes/bot/actionMsg.ts +++ b/routes/bot/actionMsg.ts @@ -14,7 +14,7 @@ const manageAction = async (ctx: Context) => { const { cardGroup } = actionValue as { cardGroup: keyof typeof GROUP_MAP } - logger.info(`Got lark action cardGroup: ${cardGroup}`) + logger.info("获取到飞书卡片Action", { cardGroup }) if (!cardGroup) return const func = GROUP_MAP[cardGroup] as (ctx: Context) => Promise if (!func) return diff --git a/routes/bot/eventMsg.ts b/routes/bot/eventMsg.ts index 3fedd29..8c0c1e9 100644 --- a/routes/bot/eventMsg.ts +++ b/routes/bot/eventMsg.ts @@ -15,11 +15,11 @@ const filterIllegalMsg = async (ctx: Context): Promise => { const { body, logger, larkService, larkBody } = ctx const { chatId, msgType, msgText } = larkBody // 没有chatId的消息不处理 - logger.info(`bot req chatId: ${chatId}`) + logger.info("接收到机器人请求", { chatId }) if (!chatId) return true // 获取msgType - logger.info(`bot req msgType: ${msgType}`) + logger.info("处理机器人消息类型", { msgType }) // 放行纯文本消息 if (msgType === "text") { // 过滤艾特全体成员的消息 @@ -32,14 +32,14 @@ const filterIllegalMsg = async (ctx: Context): Promise => { // 发表情包就直接发回去 if (msgType === "sticker") { - logger.info(`got a sticker message, chatId: ${chatId}`) + logger.info("收到表情包消息", { chatId }) const content = body?.event?.message?.content larkService.message.send("chat_id", chatId, "sticker", content) } // 非表情包其他的信息都不处理 else { - logger.info(`got a illegal message, chatId: ${chatId}`) + logger.info("收到不支持的消息类型", { chatId, msgType }) larkService.message.sendText2Chat( chatId, "哇!这是什么东东?我只懂普通文本啦![可爱]" @@ -62,13 +62,13 @@ const manageIntent = async (ctx: Context) => { larkBody: { msgText, chatId }, larkCard, } = ctx - logger.info(`bot req text: ${msgText}`) + logger.info("收到文本消息内容", { msgText }) await message.updateOrReply( larkCard.genPendingCard("正在理解您的意图,请稍等...") ) try { const intentRes = await intentAgent.agent(ctx) - logger.info(`intentRes: ${JSON.stringify(intentRes)}`) + logger.info("意图分析结果", { intentRes }) // 链接总结 if (intentAgent.isBriefing(intentRes)) { reportAgent @@ -145,7 +145,7 @@ const manageIntent = async (ctx: Context) => { break } } catch (error) { - logger.error(`manageIntent error: ${error}`) + logger.error("意图分析处理失败", { error }) await message.updateOrReply(larkCard.genErrorCard(`意图分析失败`)) } } diff --git a/routes/bot/index.ts b/routes/bot/index.ts index c7bb959..e95b038 100644 --- a/routes/bot/index.ts +++ b/routes/bot/index.ts @@ -8,7 +8,7 @@ import { manageEventMsg } from "./eventMsg" * @returns {Promise} 返回响应对象 */ export const manageBotReq = async (ctx: Context): Promise => { - const { body, larkBody } = ctx + const { body, larkBody, logger } = ctx // 检查请求体是否为空 if (!body) { @@ -17,7 +17,7 @@ export const manageBotReq = async (ctx: Context): Promise => { // 验证机器人 if (body.type === "url_verification") { - ctx.logger.info(`bot challenge: ${body.challenge}`) + logger.info("机器人验证", { challenge: body.challenge }) return Response.json({ challenge: body.challenge }) } diff --git a/routes/microApp/index.ts b/routes/microApp/index.ts index 59dddfc..e66de22 100644 --- a/routes/microApp/index.ts +++ b/routes/microApp/index.ts @@ -10,10 +10,10 @@ import { Context } from "../../types" */ const manageLogin = async (ctx: Context) => { const { req, genResp, logger, requestId } = ctx - logger.info("micro app login") const url = new URL(req.url) const code = url.searchParams.get("code") const appName = url.searchParams.get("app_name") + logger.info("小程序登录", { code, appName }) if (!code) { return genResp.badRequest("code not found") } @@ -38,7 +38,7 @@ const manageLogin = async (ctx: Context) => { message, } = await larkService.user.code2Login(code) - logger.debug(`get user session: ${JSON.stringify(data)}`) + logger.debug("获取到用户信息", { data }) if (resCode !== 0) { return genResp.serverError(message) @@ -54,9 +54,13 @@ const manageLogin = async (ctx: Context) => { */ const manageBatchUser = async (ctx: Context) => { const { body, genResp, logger, requestId } = ctx - logger.info("batch get user info") if (!body) return genResp.badRequest("req body is empty") const { user_ids, user_id_type, app_name } = body + logger.info("批量获取用户信息", { + ids: user_ids, + type: user_id_type, + app: app_name, + }) if (!user_ids) { return genResp.badRequest("user_ids not found") } @@ -83,7 +87,7 @@ const manageBatchUser = async (ctx: Context) => { user_id_type ) - logger.debug(`batch get user info: ${JSON.stringify(data)}`) + logger.debug("批量获取用户信息成功", { data }) if (code !== 0) { return genResp.serverError(message) diff --git a/routes/modelProxy/index.ts b/routes/modelProxy/index.ts index 4a50801..c8a3519 100644 --- a/routes/modelProxy/index.ts +++ b/routes/modelProxy/index.ts @@ -9,7 +9,7 @@ export const manageModelProxyReq = async (ctx: Context) => { const { req, headers, logger, path } = ctx if (!path.exact("/v1/models")) { const auth = headers.get("Authorization") - logger.info(`Start Model Proxy, Authorization: ${auth}`) + logger.info("开始模型代理转发", { Authorization: auth }) if (!auth || auth !== "Bearer sk-21a2ce1c2ee94bc2933798eac1bbcadc") { return ctx.genResp.forbidden("Authorization required") } @@ -46,7 +46,7 @@ export const manageModelProxyReq = async (ctx: Context) => { const { readable, writable } = new TransformStream() response.body ?.pipeTo(writable) - .catch((err) => logger.error("Stream error:", err)) + .catch((err) => logger.error("流式响应传输失败", { error: err.message })) return new Response(readable, { status: response.status, diff --git a/schedule/byteMonitor.ts b/schedule/byteMonitor.ts index b22e7bc..be731d9 100644 --- a/schedule/byteMonitor.ts +++ b/schedule/byteMonitor.ts @@ -125,7 +125,7 @@ const translateHTML = async (ctx: Context, rawHtml: string) => { const uniqueTexts = [...new Set(needTranslateText)] - logger.debug(`uniqueTexts: ${uniqueTexts}`) + logger.debug("需要翻译的文本", { uniqueTexts }) // 翻译,拆分为多个请求以避免超长 const chunkSize = 20 @@ -214,7 +214,7 @@ const writeHtml = async (html: string, version: number) => { const byteMonitor = async () => { const ctx = await genContextManually() const { logger, larkService, appInfo } = ctx - logger.info("byteMonitor start") + logger.info("开始翻译bytes.dev页面") try { const latestId = await getLatestId() if (!latestId) throw new Error("getLatestId empty") @@ -229,12 +229,10 @@ const byteMonitor = async () => { `页面链接:https://mi-chat-fe.cnbj1.mi-fds.com/mi-chat-fe/bytes/${newId}.html`, "byteMonitor 更新" ) - } catch (error) { - console.error(error) - const errorMessage = `byteMonitor error: ${error}` - logger.error(errorMessage) + } catch (error: any) { + logger.error("bytes翻译失败", { error: error.message }) } finally { - logger.info("byteMonitor finished") + logger.info("bytes翻译结束") } } diff --git a/schedule/fmMonitor.ts b/schedule/fmMonitor.ts index 926a16a..d0573ae 100644 --- a/schedule/fmMonitor.ts +++ b/schedule/fmMonitor.ts @@ -34,7 +34,7 @@ const diffPbContent = async (title: string): Promise => { */ const fmMonitor = async (): Promise => { const { larkService, logger, appInfo } = await genContextManually() - logger.info("fmMonitor start") + logger.info("观棋有语监控开始") try { const title = await getLatestTitle() if (!title) throw new Error("getLatestTitle empty") @@ -48,10 +48,10 @@ const fmMonitor = async (): Promise => { title, "fmMonitor 节目更新" ) - logger.info("fmMonitor success") - } catch (error) { + logger.info("观棋有语监控成功") + } catch (error: any) { + logger.info("观棋有语监控失败", { error: error.message }) const errorMessage = `fmMonitor error: ${error}` - logger.error(errorMessage) await larkService.message.sendText2Chat(appInfo.errChatId, errorMessage) } } diff --git a/schedule/zhongNotify.ts b/schedule/zhongNotify.ts index aa8a3a8..90fde96 100644 --- a/schedule/zhongNotify.ts +++ b/schedule/zhongNotify.ts @@ -18,7 +18,7 @@ const getScheduleStatus = () => { */ const sendZhongNotify = async () => { const { larkService, logger, appInfo } = await genContextManually() - logger.info("sendZhongNotify start") + logger.info("钟哥每日提醒开始") try { const status = getScheduleStatus() await larkService.message.sendText2Chat( @@ -26,10 +26,10 @@ const sendZhongNotify = async () => { `钟哥今天是${status}哦~`, "zhongNotify 每日提醒" ) - logger.info("sendZhongNotify success") - } catch (error) { + logger.info("钟哥每日提醒发送成功") + } catch (error: any) { + logger.error("钟哥每日提醒发送失败", { error: error.message }) const errorMessage = `sendZhongNotify error: ${error}` - logger.error(errorMessage) await larkService.message.sendText2Chat(appInfo.errChatId, errorMessage) } } diff --git a/test/archive/getApiKey.ts b/test/archive/getApiKey.ts index 0d1cd68..a4cdaf3 100644 --- a/test/archive/getApiKey.ts +++ b/test/archive/getApiKey.ts @@ -1,13 +1,12 @@ import initAppConfig from "../../constant/config" import DB from "../../db" -import pbClient from "../../db/pbClient" import { genContextManually } from "../../utils/genContext" await initAppConfig() const ctx = await genContextManually() -const dbInstance = new DB(pbClient, ctx.logger) +const dbInstance = new DB(ctx.logger) const res = await dbInstance.apiKey.getWithApp("uwnpzb9hvoft28h") diff --git a/utils/llm/index.ts b/utils/llm/index.ts index 7de1405..15bc258 100644 --- a/utils/llm/index.ts +++ b/utils/llm/index.ts @@ -50,14 +50,14 @@ const invoke = async ( try { result = await attemptInvoke() break - } catch (e) { - logger.error(`🚀 ~ invoke ~ attemptInvoke ~ e: ${e}`) + } catch (e: any) { + logger.error(`调用LLM模型失败`, { promptName, error: e.message }) attempts++ } } while (attempts < 3) if (!result) { - logger.error("Failed to invoke after 3 attempts") + logger.error("多次调用LLM模型失败", { promptName, attempts: 3 }) return "" } @@ -92,8 +92,8 @@ const timeParser = async (userInput: string, requestId: string) => { requestId )) as string return JSON.parse(res.replaceAll("`", "")) - } catch (e) { - logger.error(`🚀 ~ timeParser ~ invokeParser ~ e: ${e}`) + } catch (e: any) { + logger.error("时间解析失败", { userInput, error: e.message }) // 如果解析失败,则返回空字符串 return { s: "", e: "" } }