Browse Source

🎈 perf: 完善乐跑日志输出

Pchen. 9 months ago
parent
commit
d40e332ab6
1 changed files with 68 additions and 31 deletions
  1. 68 31
      lib/Lepao/Lepao.js

+ 68 - 31
lib/Lepao/Lepao.js

@@ -12,9 +12,11 @@ class Lepao {
     }
     }
 
 
     async getPath(account, vip) {
     async getPath(account, vip) {
+        this.logger.info(`${account}开始获取路径`)
         const accountSql = 'SELECT area, max_distance, min_distance, sex FROM lepao_account WHERE student_num = ?'
         const accountSql = 'SELECT area, max_distance, min_distance, sex FROM lepao_account WHERE student_num = ?'
         const rows = await db.query(accountSql, [account])
         const rows = await db.query(accountSql, [account])
         if (!rows || rows.length === 0) {
         if (!rows || rows.length === 0) {
+            this.logger.error(`${account}无法获取账号数据`)
             throw new Error('无法获取账号数据')
             throw new Error('无法获取账号数据')
         }
         }
 
 
@@ -24,14 +26,10 @@ class Lepao {
         let min = Number(min_distance) || 2.00
         let min = Number(min_distance) || 2.00
         if (sex === 2) {
         if (sex === 2) {
             max = Number(max_distance) || 4.00
             max = Number(max_distance) || 4.00
-            // min = Number(min_distance) || 1.60
             min = 1.60
             min = 1.60
         }
         }
 
 
-        // if (vip !== 1) {
-        //     if (area) throw new Error('指定乐跑跑区为 VIP 专用功能,请先开通 VIP')
-        //     if (max !== 4.00 || min !== 2.00 ) throw new Error('指定乐跑距离区间为 VIP 专用功能,请先开通 VIP')
-        // }
+        this.logger.info(`${account}路径参数: area=${area ?? '随机'}, max_distance=${max}, min_distance=${min}`)
 
 
         let pathSql = 'SELECT id FROM path_data WHERE state = 1 AND distance < ? AND distance > ? '
         let pathSql = 'SELECT id FROM path_data WHERE state = 1 AND distance < ? AND distance > ? '
         const pathParams = [max, min]
         const pathParams = [max, min]
@@ -41,53 +39,58 @@ class Lepao {
             pathParams.push(area)
             pathParams.push(area)
         }
         }
 
 
-        pathSql += '  ORDER BY count ASC LIMIT 1'
+        pathSql += ' ORDER BY count ASC LIMIT 1'
 
 
         const paths = await db.query(pathSql, pathParams)
         const paths = await db.query(pathSql, pathParams)
         if (!paths || paths.length === 0) {
         if (!paths || paths.length === 0) {
+            this.logger.error(`${account}未找到符合条件的路线`)
             throw new Error('未找到符合条件的路线,请改变路径选择条件')
             throw new Error('未找到符合条件的路线,请改变路径选择条件')
         }
         }
 
 
         const randomPath = paths[0]
         const randomPath = paths[0]
 
 
         const updateSql = 'UPDATE path_data SET count = count + 1 WHERE id = ?'
         const updateSql = 'UPDATE path_data SET count = count + 1 WHERE id = ?'
-        db.query(updateSql, [randomPath.id])
-
+        await db.query(updateSql, [randomPath.id])
+        this.logger.info(`${account}路径选中id=${randomPath.id},计数加1成功`)
         return randomPath.id
         return randomPath.id
     }
     }
 
 
-    // 获取跑步次数
     async getRecord(uid, token, school_id, student_id) {
     async getRecord(uid, token, school_id, student_id) {
         try {
         try {
             const reqData = { uid, token, school_id, student_id }
             const reqData = { uid, token, school_id, student_id }
+            this.logger.info(`开始请求获取跑步次数 uid=${uid} student_id=${student_id}`)
             const recordUrl = this.runpy + '/get_record'
             const recordUrl = this.runpy + '/get_record'
             let recordRes = await axios.post(recordUrl, reqData)
             let recordRes = await axios.post(recordUrl, reqData)
             const { data } = recordRes
             const { data } = recordRes
-            console.log(data)
+            this.logger.info(`获取跑步次数返回结果: ${JSON.stringify(data)}`)
             if (!data || data.status !== 1 || !data.data) {
             if (!data || data.status !== 1 || !data.data) {
-                this.logger.info('获取剩余跑步次数失败!')
-                console.log(data)
+                this.logger.warn('获取剩余跑步次数失败,接口返回异常')
                 return
                 return
             }
             }
             return data.data
             return data.data
         } catch (error) {
         } catch (error) {
-            this.logger.error('获取跑步次数失败!')
-            console.log(error.stack)
+            this.logger.error(`获取跑步次数失败: ${error.stack || error.message}`)
             return
             return
         }
         }
     }
     }
 
 
-    // 乐跑入口函数
     async beginLepao(uuid, account, token, uid, school_id, state) {
     async beginLepao(uuid, account, token, uid, school_id, state) {
         try {
         try {
+            this.logger.info(`${account}开始执行乐跑流程`)
             const userPermissionSql = 'SELECT vip, lepao_count FROM users WHERE uuid = ?'
             const userPermissionSql = 'SELECT vip, lepao_count FROM users WHERE uuid = ?'
             const userPermissionData = await db.query(userPermissionSql, [uuid])
             const userPermissionData = await db.query(userPermissionSql, [uuid])
-            if (!userPermissionData || userPermissionData.length !== 1)
-                throw new Error('无法获取用户信息')
-            if (userPermissionData[0].lepao_count < 1)
+            if (!userPermissionData || userPermissionData.length !== 1) {
+                this.logger.error(`${account}无法获取用户信息`)
+                throw new Error('无法获取用户信息,请重试或联系RunForge客服')
+            }
+
+            if (userPermissionData[0].lepao_count < 1) {
+                this.logger.warn(`${account}乐跑次数不足`)
                 throw new Error('用户乐跑次数不足,请购买乐跑套餐!')
                 throw new Error('用户乐跑次数不足,请购买乐跑套餐!')
+            }
 
 
             if (state !== 1) {
             if (state !== 1) {
+                this.logger.warn(`${account}登录状态异常 state=${state}`)
                 return this.sendFailEmail(account, '登录已过期,请尝试使用登录器重新登录')
                 return this.sendFailEmail(account, '登录已过期,请尝试使用登录器重新登录')
             }
             }
 
 
@@ -95,6 +98,7 @@ class Lepao {
             const path_id = await this.getPath(account, userPermissionData[0].vip)
             const path_id = await this.getPath(account, userPermissionData[0].vip)
 
 
             // 更换跑区
             // 更换跑区
+            this.logger.info(`${account}开始更换跑区,path_id=${path_id}`)
             const zoneUrl = this.runpy + '/set_zone'
             const zoneUrl = this.runpy + '/set_zone'
             const ossData = { uid, token, school_id, student_id: account, random_id: path_id }
             const ossData = { uid, token, school_id, student_id: account, random_id: path_id }
 
 
@@ -102,40 +106,50 @@ class Lepao {
                 const zoneRes = await axios.post(zoneUrl, ossData)
                 const zoneRes = await axios.post(zoneUrl, ossData)
                 const { data } = zoneRes
                 const { data } = zoneRes
 
 
+                this.logger.info(`${account}更换跑区返回结果: ${JSON.stringify(data)}`)
+
                 if (!data || data.status !== 1 || !data.data) {
                 if (!data || data.status !== 1 || !data.data) {
                     this.setStatusFail(account)
                     this.setStatusFail(account)
                     throw new Error(data?.info || '未知错误,请尝试重新登录')
                     throw new Error(data?.info || '未知错误,请尝试重新登录')
                 }
                 }
-
             } catch (error) {
             } catch (error) {
+                this.logger.error(`${account}更换跑区失败: ${error.stack || error.message}`)
                 throw error
                 throw error
             }
             }
 
 
             // 上传 OSS
             // 上传 OSS
+            this.logger.info(`${account}开始上传OSS记录`)
             const ossUrl = this.runpy + '/upload_oss_file'
             const ossUrl = this.runpy + '/upload_oss_file'
             let oss_path
             let oss_path
 
 
             try {
             try {
                 const ossRes = await axios.post(ossUrl, ossData)
                 const ossRes = await axios.post(ossUrl, ossData)
                 const { data } = ossRes
                 const { data } = ossRes
+                this.logger.info(`${account}上传OSS记录返回结果: ${JSON.stringify(data)}`)
                 if (!data || data.code !== 200 || !data.oss_path) {
                 if (!data || data.code !== 200 || !data.oss_path) {
                     throw new Error('请检查登录是否过期,并尝试更新乐跑登录状态')
                     throw new Error('请检查登录是否过期,并尝试更新乐跑登录状态')
                 }
                 }
                 oss_path = data.oss_path
                 oss_path = data.oss_path
+                this.logger.info(`${account}上传OSS记录成功!oss_path:${oss_path}`)
             } catch (error) {
             } catch (error) {
                 this.setStatusFail(account)
                 this.setStatusFail(account)
-                this.logger.error(`上传OSS记录失败,请检查登录是否过期。${error.stack || error.message}`)
+                this.logger.error(`${account}上传OSS记录失败,请检查登录是否过期。${error.stack || error.message}`)
                 throw new Error('请检查登录是否过期')
                 throw new Error('请检查登录是否过期')
             }
             }
 
 
             // 扣除乐跑次数
             // 扣除乐跑次数
+            this.logger.info(`${account}开始扣减乐跑次数`)
             const useLepaoCountSql = 'UPDATE users SET lepao_count = lepao_count - 1 WHERE uuid  = ?'
             const useLepaoCountSql = 'UPDATE users SET lepao_count = lepao_count - 1 WHERE uuid  = ?'
             await db.query(useLepaoCountSql, [uuid])
             await db.query(useLepaoCountSql, [uuid])
+            this.logger.info(`${account}扣减乐跑次数完成`)
 
 
             // 晚上10点后提前
             // 晚上10点后提前
             let run_end_time = Math.floor(Date.now() / 1000)
             let run_end_time = Math.floor(Date.now() / 1000)
             let hour = new Date().getHours()
             let hour = new Date().getHours()
-            if (hour >= 22) run_end_time -= 18000
+            if (hour >= 22) {
+                this.logger.info(`${account}当前时间为${hour}点,调整run_end_time提前5小时`)
+                run_end_time -= 18000
+            }
 
 
             const lepaoData = {
             const lepaoData = {
                 uid,
                 uid,
@@ -147,13 +161,16 @@ class Lepao {
                 run_end_time
                 run_end_time
             }
             }
 
 
-            this.logger.info(lepaoData)
+            this.logger.info(`${account}乐跑请求参数构造完成:`)
+            this.logger.info(JSON.stringify(lepaoData))
 
 
             // 绑定乐跑数据
             // 绑定乐跑数据
+            this.logger.info(`${account}开始绑定乐跑数据`)
             const lepaoUrl = this.runpy + '/bind_data'
             const lepaoUrl = this.runpy + '/bind_data'
             try {
             try {
                 const lepaoRes = await axios.post(lepaoUrl, lepaoData)
                 const lepaoRes = await axios.post(lepaoUrl, lepaoData)
                 const { data } = lepaoRes
                 const { data } = lepaoRes
+                this.logger.info(`${account}绑定乐跑数据返回结果: ${JSON.stringify(data)}`)
 
 
                 if (!data || data.status !== 1 || !data.data) {
                 if (!data || data.status !== 1 || !data.data) {
                     this.setStatusFail(account)
                     this.setStatusFail(account)
@@ -164,12 +181,15 @@ class Lepao {
 
 
                 // 获取剩余跑步次数
                 // 获取剩余跑步次数
                 const recordData = await this.getRecord(uid, token, school_id, account)
                 const recordData = await this.getRecord(uid, token, school_id, account)
+                this.logger.info(`${account}获取剩余跑步次数结果: ${JSON.stringify(recordData)}`)
+
+                let term_num = recordData?.term_num || 0
+                let total_num = recordData?.total_num || 30
 
 
-                let term_num = recordData.term_num || 0
-                let total_num = recordData.total_num || 30
                 if (data.data.record_failed_reason === '') {
                 if (data.data.record_failed_reason === '') {
                     await this.sendSuccessEmail(account, data.data, term_num, total_num)
                     await this.sendSuccessEmail(account, data.data, term_num, total_num)
                 } else {
                 } else {
+                    this.logger.warn(`${account}乐跑失败,原因: ${data.data.record_failed_reason}`)
                     await this.sendFailEmail(account, data.data.record_failed_reason)
                     await this.sendFailEmail(account, data.data.record_failed_reason)
                     await this.lepaoFail(uuid)
                     await this.lepaoFail(uuid)
                 }
                 }
@@ -177,13 +197,16 @@ class Lepao {
                 let recordSql = 'UPDATE lepao_account SET term_num = ?, total_num = ? WHERE student_num = ?'
                 let recordSql = 'UPDATE lepao_account SET term_num = ?, total_num = ? WHERE student_num = ?'
                 let recordRows = await db.query(recordSql, [term_num, total_num, account])
                 let recordRows = await db.query(recordSql, [term_num, total_num, account])
                 if (!recordRows || recordRows.affectedRows !== 1)
                 if (!recordRows || recordRows.affectedRows !== 1)
-                    this.logger.info('更新乐跑次数失败!')
+                    this.logger.warn(`${account}更新乐跑次数失败`)
+                else
+                    this.logger.info(`${account}更新乐跑次数成功 term_num=${term_num}, total_num=${total_num}`)
             } catch (error) {
             } catch (error) {
+                this.logger.error(`${account}绑定乐跑数据失败: ${error.stack || error.message}`)
                 await this.lepaoFail(uuid)
                 await this.lepaoFail(uuid)
                 throw error
                 throw error
             }
             }
-
         } catch (error) {
         } catch (error) {
+            this.logger.error(`${account}乐跑流程异常: ${error.stack || error.message}`)
             await this.sendFailEmail(account, error.message || '未知错误,请尝试重新登录')
             await this.sendFailEmail(account, error.message || '未知错误,请尝试重新登录')
         }
         }
     }
     }
@@ -191,18 +214,22 @@ class Lepao {
     async addRecord(account, result, path_id) {
     async addRecord(account, result, path_id) {
         try {
         try {
             const time = Date.now()
             const time = Date.now()
+            this.logger.info(`${account}添加乐跑记录,path_id=${path_id}`)
             const sql = 'INSERT INTO lepao_record (time, lepao_account, result, path_id) VALUES (?, ?, ?, ?)'
             const sql = 'INSERT INTO lepao_record (time, lepao_account, result, path_id) VALUES (?, ?, ?, ?)'
             await db.query(sql, [time, account, result, path_id])
             await db.query(sql, [time, account, result, path_id])
+            this.logger.info(`${account}添加乐跑记录成功`)
         } catch (error) {
         } catch (error) {
-            this.logger.error(error.stack || error.message)
+            this.logger.error(`添加乐跑记录失败: ${error.stack || error.message}`)
         }
         }
     }
     }
 
 
     async sendSuccessEmail(account, lepaoData, term_num, total_num) {
     async sendSuccessEmail(account, lepaoData, term_num, total_num) {
         try {
         try {
+            this.logger.info(`${account}发送乐跑成功邮件`)
             const emailSql = 'SELECT name, email FROM lepao_account WHERE student_num = ?'
             const emailSql = 'SELECT name, email FROM lepao_account WHERE student_num = ?'
             const rows = await db.query(emailSql, [account])
             const rows = await db.query(emailSql, [account])
             if (!rows || rows.length === 0) {
             if (!rows || rows.length === 0) {
+                this.logger.error(`${account}查找用户邮箱失败`)
                 throw new Error('查找用户邮箱失败')
                 throw new Error('查找用户邮箱失败')
             }
             }
 
 
@@ -215,25 +242,30 @@ class Lepao {
             }
             }
 
 
             await EmailTemplate.lepaoSuccess(rows[0].email, data)
             await EmailTemplate.lepaoSuccess(rows[0].email, data)
+            this.logger.info(`${account}乐跑成功邮件发送完成`)
 
 
-            // 乐跑目标完成后
             if (total_num === term_num) {
             if (total_num === term_num) {
+                this.logger.info(`${account}乐跑目标完成,发送乐跑结束邮件并关闭自动乐跑`)
                 await EmailTemplate.lepaoOver(rows[0].email, data)
                 await EmailTemplate.lepaoOver(rows[0].email, data)
                 let overSql = 'UPDATE lepao_account SET auto_run = 0 WHERE student_num = ?'
                 let overSql = 'UPDATE lepao_account SET auto_run = 0 WHERE student_num = ?'
                 let overRows = await db.query(overSql, [account])
                 let overRows = await db.query(overSql, [account])
                 if (!overRows || overRows.affectedRows !== 1)
                 if (!overRows || overRows.affectedRows !== 1)
-                    this.logger.info(`乐跑结束后关闭自动乐跑失败!`)
+                    this.logger.warn(`${account}乐跑结束后关闭自动乐跑失败`)
+                else
+                    this.logger.info(`${account}自动乐跑关闭成功`)
             }
             }
         } catch (error) {
         } catch (error) {
-            this.logger.error(error.stack || error.message)
+            this.logger.error(`发送成功邮件失败: ${error.stack || error.message}`)
         }
         }
     }
     }
 
 
     async sendFailEmail(account, reason) {
     async sendFailEmail(account, reason) {
         try {
         try {
+            this.logger.info(`${account}发送乐跑失败邮件,原因: ${reason}`)
             const emailSql = 'SELECT name, email FROM lepao_account WHERE student_num = ?'
             const emailSql = 'SELECT name, email FROM lepao_account WHERE student_num = ?'
             const rows = await db.query(emailSql, [account])
             const rows = await db.query(emailSql, [account])
             if (!rows || rows.length == 0) {
             if (!rows || rows.length == 0) {
+                this.logger.error(`${account}查找用户邮箱失败`)
                 throw new Error('查找用户邮箱失败')
                 throw new Error('查找用户邮箱失败')
             }
             }
 
 
@@ -244,15 +276,18 @@ class Lepao {
             }
             }
 
 
             await EmailTemplate.lepaoFail(rows[0].email, data)
             await EmailTemplate.lepaoFail(rows[0].email, data)
+            this.logger.info(`${account}乐跑失败邮件发送完成`)
         } catch (error) {
         } catch (error) {
-            this.logger.error(error.stack || error.message)
+            this.logger.error(`发送失败邮件失败: ${error.stack || error.message}`)
         }
         }
     }
     }
 
 
     async lepaoFail(uuid) {
     async lepaoFail(uuid) {
         try {
         try {
+            this.logger.info(`返还用户 ${uuid} 乐跑次数`)
             const sql = 'UPDATE users SET lepao_count = lepao_count + 1 WHERE uuid  = ?'
             const sql = 'UPDATE users SET lepao_count = lepao_count + 1 WHERE uuid  = ?'
             await db.query(sql, [uuid])
             await db.query(sql, [uuid])
+            this.logger.info(`返还用户 ${uuid} 乐跑次数成功`)
         } catch (error) {
         } catch (error) {
             this.logger.error(`返还用户 ${uuid} 乐跑次数时出错: ${error.stack || error.message}`)
             this.logger.error(`返还用户 ${uuid} 乐跑次数时出错: ${error.stack || error.message}`)
         }
         }
@@ -260,8 +295,10 @@ class Lepao {
 
 
     async setStatusFail(account) {
     async setStatusFail(account) {
         try {
         try {
+            this.logger.info(`${account}设置账号为未启用`)
             const sql = 'UPDATE lepao_account SET state = 0 WHERE student_num  = ?'
             const sql = 'UPDATE lepao_account SET state = 0 WHERE student_num  = ?'
             await db.query(sql, [account])
             await db.query(sql, [account])
+            this.logger.info(`${account}账号状态设置为未启用成功`)
         } catch (error) {
         } catch (error) {
             this.logger.error(`设置用户 ${account} state时出错: ${error.stack || error.message}`)
             this.logger.error(`设置用户 ${account} state时出错: ${error.stack || error.message}`)
         }
         }