定位 Node.js 日志中的错误,通常可以按下面几个层次来做:看日志内容 → 定位代码 → 复现与验证 → 加监控和日志。下面给你一套实用思路。
Node.js 崩溃或报错一般会有类似内容:
Error: Cannot read property 'x' of undefined
at getUser (/app/service/user.js:23:15)
at processTicksAndRejections (node:internal/process/task_queues:95:5)
重点看:
TypeError / ReferenceError / SyntaxError / RangeErrorUnhandledPromiseRejectionWarningerr不要只用 console.log,用日志库:
winstonpinobunyan示例(pino):
logger.error({ err, userId }, 'user login failed')
好处:
在 HTTP 请求中加 requestId:
app.use((req, res, next) => {
req.requestId = uuid()
next()
})
日志中带上:
logger.error({ requestId: req.requestId, err })
这样你可以:
用 requestId 把一次请求的所有日志串起来
例如:
at getUser (/app/service/user.js:23:15)
直接打开 user.js 第 23 行
expect(() => getUser(null)).toThrow()
console.log('user=', user)
确认:
undefined| 错误 | 常见原因 | 定位点 |
|---|---|---|
| Cannot read property of undefined | 对象未初始化 | 上游数据 / DB 返回 |
| UnhandledPromiseRejection | Promise 没 catch | async/await |
| ECONNREFUSED | 服务连不上 | 数据库 / Redis |
| ETIMEDOUT | 网络慢 | 第三方接口 |
| Memory Leak | 闭包 / 缓存 | heapdump |
Error.captureStackTrace(err)
process.on('uncaughtException', err => {
logger.error({ err }, 'uncaughtException')
})
process.on('unhandledRejection', err => {
logger.error({ err }, 'unhandledRejection')
})
可以:
如果你愿意,可以把具体的 Node.js 错误日志贴出来,我可以直接帮你定位是哪一行、什么原因、怎么改。