├── assets ├── 1.1.1.png ├── 1.1.2.png ├── 1.1.3.jpg ├── 1.2.1.png ├── 1.2.2.png ├── 1.2.3.png ├── 2.1.1.jpg ├── 2.2.1.png ├── 2.2.2.png ├── 2.2.3.png ├── 2.2.4.png ├── 2.3.1.png ├── 3.1.1.png ├── 3.1.2.png ├── 3.1.3.png ├── 3.1.4.png ├── 3.3.1.jpg ├── 3.3.2.jpg ├── 3.3.3.jpg ├── 3.3.4.jpg ├── 3.3.5.jpg ├── 4.2.1.png ├── 4.2.2.png ├── 4.2.3.png ├── 4.2.4.png ├── 4.3.1.png ├── 4.3.2.png ├── 4.3.3.png ├── 4.3.4.png ├── 4.3.5.png ├── 4.4.1.jpg ├── 4.4.2.jpg ├── 5.1.1.png ├── 5.1.2.png ├── 5.1.3.png ├── 5.2.1.png ├── 5.2.2.png ├── 5.2.3.png ├── 5.2.4.png ├── 5.2.5.png ├── 5.2.6.png ├── 6.3.1.png ├── 6.3.2.png ├── 6.3.3.png ├── 6.3.4.png ├── 6.4.1.jpg ├── 6.4.2.jpg ├── 6.4.3.jpg ├── 6.4.4.jpg ├── 6.4.5.jpg ├── 6.4.6.jpg ├── 6.5.1.jpg ├── 6.5.2.jpg ├── 6.5.3.png ├── 6.5.4.png ├── 6.5.5.png ├── 6.5.6.png ├── 6.5.7.png ├── 7.1.1.png ├── 7.1.2.png ├── 7.1.3.png ├── 7.1.4.png ├── 7.1.5.png ├── 7.1.6.png ├── 7.1.7.png ├── 7.1.8.png ├── 7.1.9.png ├── 7.2.1.png ├── 7.2.2.png ├── 7.2.3.png ├── 7.2.4.png ├── 7.2.5.png ├── 7.2.6.png ├── 7.2.7.png ├── 7.2.8.png ├── 8.1.1.png ├── 8.1.2.png ├── 8.2.1.png ├── 8.2.2.png ├── 8.2.3.png ├── 8.2.4.png ├── alipay.png └── wechat.jpeg ├── 8.1 node-clinic.md ├── 5.1 NewRelic.md ├── 4.2 Chrome DevTools.md ├── README.md ├── 7.2 Telegraf + InfluxDB + Grafana(下).md ├── 5.2 Elastic APM.md ├── 8.2 alinode.md ├── 2.4 cpu-memory-monitor.md ├── 2.2 heapdump.md ├── 6.3 ELK.md ├── 4.1 Source Map.md ├── 6.5 Sentry.md ├── 1.2 v8-profiler.md ├── 3.3 Node@8.md ├── 6.4 OpenTracing + Jaeger.md ├── 2.3 memwatch-next.md ├── 4.4 debug + repl2 + power-assert.md ├── 7.1 Telegraf + InfluxDB + Grafana(上).md ├── 3.1 Async + Await.md ├── 2.1 gcore + llnode.md ├── 4.3 Visual Studio Code.md ├── 1.1 perf + FlameGraph.md ├── 6.2 async_hooks.md ├── 3.4 Rust Addons.md ├── 6.1 koa-await-breakpoint.md ├── 4.5 supervisor-hot-reload.md └── 3.2 Error Stack.md /assets/1.1.1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/1.1.1.png -------------------------------------------------------------------------------- /assets/1.1.2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/1.1.2.png -------------------------------------------------------------------------------- /assets/1.1.3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/1.1.3.jpg -------------------------------------------------------------------------------- /assets/1.2.1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/1.2.1.png -------------------------------------------------------------------------------- /assets/1.2.2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/1.2.2.png -------------------------------------------------------------------------------- /assets/1.2.3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/1.2.3.png -------------------------------------------------------------------------------- /assets/2.1.1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/2.1.1.jpg -------------------------------------------------------------------------------- /assets/2.2.1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/2.2.1.png -------------------------------------------------------------------------------- /assets/2.2.2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/2.2.2.png -------------------------------------------------------------------------------- /assets/2.2.3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/2.2.3.png -------------------------------------------------------------------------------- /assets/2.2.4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/2.2.4.png -------------------------------------------------------------------------------- /assets/2.3.1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/2.3.1.png -------------------------------------------------------------------------------- /assets/3.1.1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/3.1.1.png -------------------------------------------------------------------------------- /assets/3.1.2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/3.1.2.png -------------------------------------------------------------------------------- /assets/3.1.3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/3.1.3.png -------------------------------------------------------------------------------- /assets/3.1.4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/3.1.4.png -------------------------------------------------------------------------------- /assets/3.3.1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/3.3.1.jpg -------------------------------------------------------------------------------- /assets/3.3.2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/3.3.2.jpg -------------------------------------------------------------------------------- /assets/3.3.3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/3.3.3.jpg -------------------------------------------------------------------------------- /assets/3.3.4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/3.3.4.jpg -------------------------------------------------------------------------------- /assets/3.3.5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/3.3.5.jpg -------------------------------------------------------------------------------- /assets/4.2.1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/4.2.1.png -------------------------------------------------------------------------------- /assets/4.2.2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/4.2.2.png -------------------------------------------------------------------------------- /assets/4.2.3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/4.2.3.png -------------------------------------------------------------------------------- /assets/4.2.4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/4.2.4.png -------------------------------------------------------------------------------- /assets/4.3.1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/4.3.1.png -------------------------------------------------------------------------------- /assets/4.3.2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/4.3.2.png -------------------------------------------------------------------------------- /assets/4.3.3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/4.3.3.png -------------------------------------------------------------------------------- /assets/4.3.4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/4.3.4.png -------------------------------------------------------------------------------- /assets/4.3.5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/4.3.5.png -------------------------------------------------------------------------------- /assets/4.4.1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/4.4.1.jpg -------------------------------------------------------------------------------- /assets/4.4.2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/4.4.2.jpg -------------------------------------------------------------------------------- /assets/5.1.1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/5.1.1.png -------------------------------------------------------------------------------- /assets/5.1.2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/5.1.2.png -------------------------------------------------------------------------------- /assets/5.1.3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/5.1.3.png -------------------------------------------------------------------------------- /assets/5.2.1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/5.2.1.png -------------------------------------------------------------------------------- /assets/5.2.2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/5.2.2.png -------------------------------------------------------------------------------- /assets/5.2.3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/5.2.3.png -------------------------------------------------------------------------------- /assets/5.2.4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/5.2.4.png -------------------------------------------------------------------------------- /assets/5.2.5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/5.2.5.png -------------------------------------------------------------------------------- /assets/5.2.6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/5.2.6.png -------------------------------------------------------------------------------- /assets/6.3.1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/6.3.1.png -------------------------------------------------------------------------------- /assets/6.3.2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/6.3.2.png -------------------------------------------------------------------------------- /assets/6.3.3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/6.3.3.png -------------------------------------------------------------------------------- /assets/6.3.4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/6.3.4.png -------------------------------------------------------------------------------- /assets/6.4.1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/6.4.1.jpg -------------------------------------------------------------------------------- /assets/6.4.2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/6.4.2.jpg -------------------------------------------------------------------------------- /assets/6.4.3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/6.4.3.jpg -------------------------------------------------------------------------------- /assets/6.4.4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/6.4.4.jpg -------------------------------------------------------------------------------- /assets/6.4.5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/6.4.5.jpg -------------------------------------------------------------------------------- /assets/6.4.6.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/6.4.6.jpg -------------------------------------------------------------------------------- /assets/6.5.1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/6.5.1.jpg -------------------------------------------------------------------------------- /assets/6.5.2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/6.5.2.jpg -------------------------------------------------------------------------------- /assets/6.5.3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/6.5.3.png -------------------------------------------------------------------------------- /assets/6.5.4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/6.5.4.png -------------------------------------------------------------------------------- /assets/6.5.5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/6.5.5.png -------------------------------------------------------------------------------- /assets/6.5.6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/6.5.6.png -------------------------------------------------------------------------------- /assets/6.5.7.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/6.5.7.png -------------------------------------------------------------------------------- /assets/7.1.1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/7.1.1.png -------------------------------------------------------------------------------- /assets/7.1.2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/7.1.2.png -------------------------------------------------------------------------------- /assets/7.1.3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/7.1.3.png -------------------------------------------------------------------------------- /assets/7.1.4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/7.1.4.png -------------------------------------------------------------------------------- /assets/7.1.5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/7.1.5.png -------------------------------------------------------------------------------- /assets/7.1.6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/7.1.6.png -------------------------------------------------------------------------------- /assets/7.1.7.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/7.1.7.png -------------------------------------------------------------------------------- /assets/7.1.8.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/7.1.8.png -------------------------------------------------------------------------------- /assets/7.1.9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/7.1.9.png -------------------------------------------------------------------------------- /assets/7.2.1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/7.2.1.png -------------------------------------------------------------------------------- /assets/7.2.2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/7.2.2.png -------------------------------------------------------------------------------- /assets/7.2.3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/7.2.3.png -------------------------------------------------------------------------------- /assets/7.2.4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/7.2.4.png -------------------------------------------------------------------------------- /assets/7.2.5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/7.2.5.png -------------------------------------------------------------------------------- /assets/7.2.6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/7.2.6.png -------------------------------------------------------------------------------- /assets/7.2.7.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/7.2.7.png -------------------------------------------------------------------------------- /assets/7.2.8.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/7.2.8.png -------------------------------------------------------------------------------- /assets/8.1.1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/8.1.1.png -------------------------------------------------------------------------------- /assets/8.1.2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/8.1.2.png -------------------------------------------------------------------------------- /assets/8.2.1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/8.2.1.png -------------------------------------------------------------------------------- /assets/8.2.2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/8.2.2.png -------------------------------------------------------------------------------- /assets/8.2.3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/8.2.3.png -------------------------------------------------------------------------------- /assets/8.2.4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/8.2.4.png -------------------------------------------------------------------------------- /assets/alipay.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/alipay.png -------------------------------------------------------------------------------- /assets/wechat.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JacksonTian/node-in-debugging/HEAD/assets/wechat.jpeg -------------------------------------------------------------------------------- /8.1 node-clinic.md: -------------------------------------------------------------------------------- 1 | [node-clinic](https://github.com/nearform/node-clinic)(简称 clinic) 是一个开箱即用的 Node.js 应用诊断工具。 2 | 3 | 首先,安装 Node.js@9+ 4 | 5 | ```sh 6 | $ nvm install 9.6.1 7 | ``` 8 | 9 | 全局安装 clinic: 10 | 11 | ```sh 12 | $ npm i clinic -g 13 | ``` 14 | 15 | 创建测试代码: 16 | 17 | **app.js** 18 | 19 | ```js 20 | const Paloma = require('paloma') 21 | const app = new Paloma() 22 | 23 | function sleep (ms) { 24 | const future = Date.now() + ms 25 | while (Date.now() < future); 26 | } 27 | 28 | app.use(() => { 29 | sleep(50) 30 | }) 31 | 32 | app.listen(3000) 33 | ``` 34 | 35 | 使用 clinic doctor 启动并诊断 Node.js 应用: 36 | 37 | ```sh 38 | $ clinic doctor -- node app.js 39 | ``` 40 | 41 | 使用 ab 压测: 42 | 43 | ```sh 44 | $ ab -c 10 -n 200 "http://localhost:3000/" 45 | ``` 46 | 47 | CTRL+C 终止测试程序,终端打印出: 48 | 49 | ``` 50 | Warning: Trace event is an experimental feature and could change at any time. 51 | ^Canalysing data 52 | generated HTML file is 51485.clinic-doctor.html 53 | ``` 54 | 55 | 浏览器打开 51485.clinic-doctor.html,如下所示: 56 | 57 | ![](./assets/8.1.1.png) 58 | 59 | **可以看出**:Event Loop 被阻塞,CPU Usage 也居高不下,一定是有 CPU 密集计算,与我们的测试代码吻合。 60 | 61 | clinic 也给出了猜测和解决方案,我们尝试使用 clinic flame 生成火焰图: 62 | 63 | ```sh 64 | $ clinic flame -- node app.js 65 | ``` 66 | 67 | 也可以用以下命令代替: 68 | 69 | ```sh 70 | $ clinic flame --collect-only -- node app.js # 只收集数据 71 | $ clinic flame --visualize-only PID.flamegraph # 将数据生成火焰图 72 | ``` 73 | 74 | 使用同样的 ab 命令压测后,生成的火焰图如下: 75 | 76 | ![](./assets/8.1.2.png) 77 | 78 | **可以看出**:app.js 第 4 行的 sleep 函数占用了大量的 CPU 计算。 79 | 80 | ## 参考链接 81 | 82 | - https://www.nearform.com/blog/introducing-node-clinic-a-performance-toolkit-for-node-js-developers/ 83 | 84 | 上一节:[7.2 Telegraf + InfluxDB + Grafana(下)](https://github.com/nswbmw/node-in-debugging/blob/master/7.2%20Telegraf%20%2B%20InfluxDB%20%2B%20Grafana(%E4%B8%8B).md) 85 | 86 | 下一节:[8.2 alinode](https://github.com/nswbmw/node-in-debugging/blob/master/8.2%20alinode.md) 87 | -------------------------------------------------------------------------------- /5.1 NewRelic.md: -------------------------------------------------------------------------------- 1 | [NewRelic](https://newrelic.com/) 是一个老牌的应用性能监测工具,提供 14 天免费试用,本文将讲解如何使用 NewRelic 监控代码的性能。 2 | 3 | 测试代码: 4 | 5 | **app.js** 6 | 7 | ```js 8 | require('newrelic') 9 | 10 | const crypto = require('crypto') 11 | const express = require('express') 12 | const app = express() 13 | const createUser = require('./routes/users').createUser 14 | 15 | app.get('/', (req, res) => { 16 | const salt = crypto.randomBytes(128).toString('base64') 17 | const hash = crypto.pbkdf2Sync(String(Math.random()), salt, 10000, 512, 'sha512').toString('hex') 18 | res.json({ salt, hash }) 19 | }) 20 | 21 | app.get('/error', (req, res, next) => { 22 | next(new Error('error!!!')) 23 | }) 24 | 25 | app.post('/users/:user', async (req, res) => { 26 | const user = await createUser(req.params.user, 18) 27 | res.json(user) 28 | }) 29 | 30 | app.listen(3000) 31 | ``` 32 | 33 | **routes/users.js** 34 | 35 | ```js 36 | const Mongolass = require('mongolass') 37 | const mongolass = new Mongolass('mongodb://localhost:27017/test') 38 | const User = mongolass.model('User') 39 | 40 | exports.createUser = async function (ctx) { 41 | const name = ctx.query.name || 'default' 42 | const age = +ctx.query.age || 18 43 | const user = await createUser(name, age) 44 | ctx.status = user 45 | } 46 | 47 | async function createUser (name, age) { 48 | const user = (await User.create({ 49 | name, 50 | age 51 | })).ops[0] 52 | return user 53 | } 54 | ``` 55 | 56 | ## 使用 NewRelic 57 | 58 | 首先,注册一个 [NewRelic](https://newrelic.com/signup) 账号。创建一个应用,如下所示: 59 | 60 | ![](./assets/5.1.1.png) 61 | 62 | 选择 APM,进入下一步,选择 Node.js 应用,并拿到 license key: 63 | 64 | ![](./assets/5.1.2.png) 65 | 66 | 在 Node.js 中使用 NewRelic 步骤如下: 67 | 68 | ```sh 69 | $ npm i newrelic --save # 安装 NewRelic 的 Node.js SDK 70 | $ cp node_modules/newrelic/newrelic.js . # 将默认配置文件拷贝到根目录下 71 | ``` 72 | 73 | 修改 newrelic.js,app_name 填写你的应用名(如:api),license_key 填写刚才生成的 license key。 74 | 75 | 启动测试程序,并发起几个请求,稍等几分钟,NewRelic 的后台将会收到并展示一些数据(如:吞吐量,请求的 Urls,错误率、Apdex score 等等): 76 | 77 | ![](./assets/5.1.3.png) 78 | 79 | 试用版功能有限,升级到付费版可使用更多功能,如:数据库分析、错误分析甚至 Node.js VM 监控(如:CPU、内存、GC、Event Loop)等等。 80 | 81 | 类似的其他 APM 有: 82 | 83 | - [AppDynamics](https://www.appdynamics.com/) 84 | - [OneAPM](oneapm.com) 85 | - [DataDog](https://www.datadoghq.com/monitor-nodejs/) 86 | - [atatus](https://www.atatus.com/) 87 | - [opbeat](https://opbeat.com/nodejs ) 88 | 89 | 用法大同小异,这里就不一一介绍了。 90 | 91 | 上一节:[4.5 supervisor-hot-reload](https://github.com/nswbmw/node-in-debugging/blob/master/4.5%20supervisor-hot-reload.md) 92 | 93 | 下一节:[5.2 Elastic APM](https://github.com/nswbmw/node-in-debugging/blob/master/5.2%20Elastic%20APM.md) 94 | -------------------------------------------------------------------------------- /4.2 Chrome DevTools.md: -------------------------------------------------------------------------------- 1 | 调试是每个程序员必备的技能,因此选择合适的调试工具能极大的方便我们调试代码。Node.js 的调试方式也有很多,常见的如: 2 | 3 | 1. 万能的 console.log 4 | 2. debugger 5 | 3. node-inspector 6 | 7 | 以上本文都不会涉及,因为: 8 | 9 | 1. console.log 就不用说了 10 | 2. debugger 不推荐使用,因为: 11 | 1. 使用繁琐,需手动打点 12 | 2. 若忘记删除 debugger,会引起性能问题 13 | 3. node-inspector 已经退出历史舞台。node@6.3 以后,Node.js 内置了一个调试器,可以结合 Chrome DevTools 使用,而且比 node-inspector 更强大 14 | 15 | 下面就讲讲 Chrome DevTools 的用法。 16 | 17 | ## Chrome DevTools 18 | 19 | 创建示例代码: 20 | 21 | **app.js** 22 | 23 | ```js 24 | const Paloma = require('paloma') 25 | const app = new Paloma() 26 | 27 | app.use(ctx => { 28 | ctx.body = 'hello world!' 29 | }) 30 | 31 | app.listen(3000) 32 | ``` 33 | 34 | 运行: 35 | 36 | ```sh 37 | $ node --inspect app.js 38 | ``` 39 | 40 | **注意:**如果想让代码在第一行就暂停执行,需要使用 --inspect-brk 参数启动,即 `node --inspect-brk app.js`。 41 | 42 | 打开 Chrome 浏览器,访问 chrome://inspect,如下所示: 43 | 44 | ![](./assets/4.2.1.png) 45 | 46 | 点击 Remote Target 下的 inspect,选择 Sources,如下所示: 47 | 48 | ![](./assets/4.2.2.png) 49 | 50 | 使用方式跟 node-inspector 类似,可以添加断点,然后在 Console 里面直接输入变量名打印该变量的值。如下所示,在第 6 行添加断点,然后通过 `curl localhost:3000?name=nswbmw`,代码执行到第 6 行暂停执行,在 Console 里打印 ctx.query 的值: 51 | 52 | ![](./assets/4.2.3.png) 53 | 54 | **Tips**:将鼠标悬浮在某个变量上,也会显示它的值,如 ctx。 55 | 56 | 展开右侧的 debugger 有更多的功能,如单步执行、单步进入、单步退出等等,这里不再详细讲解。 57 | 58 | ## [NIM](https://chrome.google.com/webstore/detail/nim-node-inspector-manage/gnhhdgbaldcilmgcpfddgdbkhjohddkj) 59 | 60 | 每次调试 Node.js 都要打开隐藏那么深的入口烦不烦?还好我们有 [NIM](https://chrome.google.com/webstore/detail/nim-node-inspector-manage/gnhhdgbaldcilmgcpfddgdbkhjohddkj)。NIM(Node Inspector Manager)是一个 Chrome 插件,可以方便我们快捷的打开 DevTools,也可以设置自动发现并打开 DevTools。 61 | 62 | ![](./assets/4.2.4.png) 63 | 64 | ## [inspect-process](https://github.com/jaridmargolin/inspect-process) 65 | 66 | NIM 也麻烦?那你可能需要 [inspect-process](https://github.com/jaridmargolin/inspect-process)。 67 | 68 | 全局安装: 69 | 70 | ```sh 71 | $ npm i inspect-process -g 72 | ``` 73 | 74 | 使用: 75 | 76 | ```sh 77 | $ inspect app.js 78 | ``` 79 | 80 | inspect-process 会自动调起 Chrome DevTools,然后定位到 app.js,其余用法跟 Chrome DevTools 一致。 81 | 82 | ## process._debugProcess 83 | 84 | 如果一个 Node.js 进程已经启动,没有添加 --inspect 参数,我们不想重启(会丢失现场)又想调试怎么办?幸好我们有 process._debugProcess。使用方法: 85 | 86 | 1. 通过 ps 命令或者 `pgrep -n node` 查看当前启动的 Node.js 进程的 pid,如:53911 87 | 2. 打开新的终端,运行:`node -e "process._debugProcess(53911)"`,原来的 Node.js 进程会打印出:Debugger listening on ws://127.0.0.1:9229/2331fa07-32af-45eb-a1a8-bead7a0ab905 88 | 3. 调出 Chrome DevTools 进行调试 89 | 90 | ## 参考链接 91 | 92 | - [https://medium.com/@paul_irish/debugging-node-js-nightlies-with-chrome-devtools-7c4a1b95ae27](https://medium.com/@paul_irish/debugging-node-js-nightlies-with-chrome-devtools-7c4a1b95ae27) 93 | 94 | 上一节:[4.1 Source Map](https://github.com/nswbmw/node-in-debugging/blob/master/4.1%20Source%20Map.md) 95 | 96 | 下一节:[4.3 Visual Studio Code](https://github.com/nswbmw/node-in-debugging/blob/master/4.3%20Visual%20Studio%20Code.md) 97 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## node-in-debugging 2 | 3 | 《Node.js 调试指南》是本人整理的从事 Node.js 开发这几年的一些调试经验和思路,希望授人以鱼也能授人以渔。 4 | 5 | ## 开发环境 6 | 7 | - MacOS|Linux(Ubuntu@16.04 64位) 8 | - Node.js@8.9.4 9 | 10 | ## 目录 11 | 12 | - CPU 篇 13 | - [perf + FlameGraph](https://github.com/nswbmw/node-in-debugging/blob/master/1.1%20perf%20%2B%20FlameGraph.md) 14 | - [v8-profiler](https://github.com/nswbmw/node-in-debugging/blob/master/1.2%20v8-profiler.md) 15 | - 内存篇 16 | - [gcore + llnode](https://github.com/nswbmw/node-in-debugging/blob/master/2.1%20gcore%20%2B%20llnode.md) 17 | - [heapdump](https://github.com/nswbmw/node-in-debugging/blob/master/2.2%20heapdump.md) 18 | - [memwatch-next](https://github.com/nswbmw/node-in-debugging/blob/master/2.3%20memwatch-next.md) 19 | - [cpu-memory-monitor](https://github.com/nswbmw/node-in-debugging/blob/master/2.4%20cpu-memory-monitor.md) 20 | - 代码篇 21 | - [Async + Await](https://github.com/nswbmw/node-in-debugging/blob/master/3.1%20Async%20%2B%20Await.md) 22 | - [Error Stack](https://github.com/nswbmw/node-in-debugging/blob/master/3.2%20Error%20Stack.md) 23 | - [Node@8](https://github.com/nswbmw/node-in-debugging/blob/master/3.3%20Node%408.md) 24 | - [Rust Addons](https://github.com/nswbmw/node-in-debugging/blob/master/3.4%20Rust%20Addons.md) 25 | - 调试篇 26 | - [Source Map](https://github.com/nswbmw/node-in-debugging/blob/master/4.1%20Source%20Map.md) 27 | - [Chrome DevTools](https://github.com/nswbmw/node-in-debugging/blob/master/4.2%20Chrome%20DevTools.md) 28 | - [Visual Studio Code](https://github.com/nswbmw/node-in-debugging/blob/master/4.3%20Visual%20Studio%20Code.md) 29 | - [debug + repl2 + power-assert](https://github.com/nswbmw/node-in-debugging/blob/master/4.4%20debug%20%2B%20repl2%20%2B%20power-assert.md) 30 | - [supervisor-hot-reload](https://github.com/nswbmw/node-in-debugging/blob/master/4.5%20supervisor-hot-reload.md) 31 | - APM 篇 32 | - [NewRelic](https://github.com/nswbmw/node-in-debugging/blob/master/5.1%20NewRelic.md) 33 | - [Elastic APM](https://github.com/nswbmw/node-in-debugging/blob/master/5.2%20Elastic%20APM.md) 34 | - 日志篇 35 | - [koa-await-breakpoint](https://github.com/nswbmw/node-in-debugging/blob/master/6.1%20koa-await-breakpoint.md) 36 | - [async_hooks](https://github.com/nswbmw/node-in-debugging/blob/master/6.2%20async_hooks.md) 37 | - [ELK](https://github.com/nswbmw/node-in-debugging/blob/master/6.3%20ELK.md) 38 | - [OpenTracing + Jaeger](https://github.com/nswbmw/node-in-debugging/blob/master/6.4%20OpenTracing%20%2B%20Jaeger.md) 39 | - [Sentry](https://github.com/nswbmw/node-in-debugging/blob/master/6.5%20Sentry.md) 40 | - 监控篇 41 | - [Telegraf + InfluxDB + Grafana(上)](https://github.com/nswbmw/node-in-debugging/blob/master/7.1%20Telegraf%20%2B%20InfluxDB%20%2B%20Grafana(%E4%B8%8A).md) 42 | - [Telegraf + InfluxDB + Grafana(下)](https://github.com/nswbmw/node-in-debugging/blob/master/7.2%20Telegraf%20%2B%20InfluxDB%20%2B%20Grafana(%E4%B8%8B).md) 43 | - 工具篇 44 | - [node-clinic](https://github.com/nswbmw/node-in-debugging/blob/master/8.1%20node-clinic.md) 45 | - [alinode](https://github.com/nswbmw/node-in-debugging/blob/master/8.2%20alinode.md) 46 | 47 | ## 捐赠 48 | 49 | 支付宝 | 微信 50 | ------|------ 51 | ![](./assets/alipay.png) | ![](./assets/wechat.jpeg) 52 | -------------------------------------------------------------------------------- /7.2 Telegraf + InfluxDB + Grafana(下).md: -------------------------------------------------------------------------------- 1 | 上一小节主要讲解了 Telegraf(StatsD) + InfluxDB + Grafana 的搭建和基本用法,以及创建了请求量和响应时间两种图表。这一小节讲解几个高级用法: 2 | 3 | 1. 如何将 Grafana(监控) 跟 ELK(日志) 结合起来 4 | 2. Grafana 监控报警 5 | 3. 脚本一键生成图表 6 | 7 | ## Grafana + ELK 8 | 9 | 在观察 Grafana 监控时,发现某个 api 接口响应时间突然有一个尖刺,这个时候想查一查到底什么原因导致的,前面介绍过 koa-await-breakpoint + ELK 的用法,是否可以结合 Grafana 使用呢?答案是可以的。 10 | 11 | 因为涉及的代码量大,笔者写了一个 demo 托管到了 GitHub 上,有两个 repo,分别为: 12 | 13 | - [grafana-to-elk](https://github.com/nswbmw/grafana-to-elk):包含 web server 和模拟请求的 client,分别将统计信息发送到 StatsD 和将日志发送到 ELK。 14 | - [grafana-to-elk-extension](https://github.com/nswbmw/grafana-to-elk-extension):Chrome 扩展,作用是: 15 | - 格式化从 Grafana 跳转到 ELK 的时间范围 16 | - 添加 requestId 的链接 17 | - 高亮显示重要的字段 18 | 19 | 首先 clone 到本地: 20 | 21 | ```sh 22 | $ git clone https://github.com/nswbmw/grafana-to-elk.git 23 | $ git clone https://github.com/nswbmw/grafana-to-elk-extension.git 24 | ``` 25 | 26 | 测试步骤如下: 27 | 28 | 1. 按照 7.2 小节启动 Telegraf(StatsD) + InfluxDB + Grafana 29 | 30 | 2. 按照 6.3 小节启动 ELK 31 | 32 | 3. 到 grafana-to-elk 目录下运行: 33 | ```sh 34 | $ npm i 35 | $ node server 36 | ``` 37 | 起另外一个终端运行: 38 | ```sh 39 | $ node client 40 | ``` 41 | 此时,ELK 应该有日志了。 42 | 43 | 4. 加载 Chrome 扩展。打开 Chrome 扩展程序页 -> 加载已解压的扩展程序... -> 加载 grafana-to-elk-extension(非测试环境需要修改 manifest.json 的 matches 字段)。 44 | 45 | 5. 回到 Grafana 的『getHome 响应时间』图表,进入编辑页的 General tab,如下填写: 46 | ![](./assets/7.2.1.png) 47 | 保存,图表的左上角会出现一个类似分享的按钮,鼠标悬浮到上面出现 Go to ELK,点击跳转到 ELK。 48 | 49 | 6. ELK 显示如下: 50 | ![](./assets/7.2.2.png)grafana-to-elk-extension 插件自动处理并跳转到对应 Grafana 中的时间段并且查询出了我们关心的结果。点击第一个 requestId,将会跳转并显示该请求所有的日志,如下所示: 51 | ![](./assets/7.2.3.png) 52 | 错误请求的日志: 53 | ![](./assets/7.2.4.png) 54 | 55 | ## 监控报警 56 | 57 | Grafana 有内置的监控报警,设置步骤如下: 58 | 59 | 1. 进入 Alerting -> Notifications 页,点击 New Notification 添加新的报警组,如下所示: 60 | ![](./assets/7.2.5.png) 61 | 2. 回到『getHome 响应时间』图表,进入编辑页的 Alert tab,点击 Create Alert 创建报警规则,如下所示: 62 | ![](./assets/7.2.6.png) 63 | **报警规则**:每 60s 检查一次过去 1min 的 mean(B 在 Metrics 里面代表了别名为 mean 折线图)折线图的平均值是否大于 50,如果是则触发报警。 64 | **注意**:如需发邮件,需要设置 Grafana 的 [SMTP settings](http://docs.grafana.org/installation/configuration/#smtp)。 65 | 66 | 我们还可以给 『getHome 请求量』设置错误报警监控,如下所示: 67 | 68 | ![](./assets/7.2.7.png) 69 | 70 | 每 60s 检查一次过去 1min 是否有 400 报错,如果有则触发报警,其中 B 代表了别名为 400 的折线图。 71 | 72 | **Tips**:报警信息可以发送到 Email、Slack、DingTalk 或者 Webhook 等等。报警内容可以包含图表的截图,需要配置 [external image uploader](http://docs.grafana.org/installation/configuration/#external-image-storage)。 73 | 74 | ## 脚本一键生成图表 75 | 76 | 我们只创建了一个接口的两种(请求量和响应时间)图表,还要设置 link、alert 等等就很麻烦了。如果我们的 api 有几百个接口,岂不是灾难了。 77 | 78 | Grafana 虽然有 Template 的功能,但我们接下来讲一个奇技淫巧。 79 | 80 | 我们在保存图表的时候从 Chrome DevTools 的 Network 看到发起了一个 Ajax 请求,如下所示: 81 | 82 | ![](./assets/7.2.8.png) 83 | 84 | dashboard 就是包含了当前仪表盘页所有图表的完整 JSON,其中: 85 | 86 | - dashboard:包含一到多行 row 87 | - rows:一行 row 包含一到多个 panel 88 | - panels:一个 panel 是一个具体的图表 89 | 90 | 拿到这个 JSON 我们就可以不断尝试修改它,然后用 axios 带上浏览器拿到的 Cookie 发送到图中的 url,模拟浏览器的保存操作,这里就不再展开讲解了。 91 | 92 | ## 参考链接 93 | 94 | - http://docs.grafana.org/alerting/notifications/ 95 | 96 | 上一节:[7.1 Telegraf + InfluxDB + Grafana(上)](https://github.com/nswbmw/node-in-debugging/blob/master/7.1%20Telegraf%20%2B%20InfluxDB%20%2B%20Grafana(%E4%B8%8A).md) 97 | 98 | 下一节:[8.1 node-clinic](https://github.com/nswbmw/node-in-debugging/blob/master/8.1%20node-clinic.md) 99 | -------------------------------------------------------------------------------- /5.2 Elastic APM.md: -------------------------------------------------------------------------------- 1 | Elastic APM 是 Elastic 公司开源的一款 APM 工具,目前还处于 Beta 阶段,它有以下几个优势: 2 | 3 | 1. 开源。你可以免费使用,像使用 ELK 一样。 4 | 2. 功能完善。API 比较完善,有 Agent、Transaction、Trace,默认创建响应时间和每分钟请求数两种图表,且可以使用 Kibana 的 Filter 过滤生成关心的数据的图表。 5 | 3. 监控与日志统一。Elastic APM 依赖 ElasticSearch + Kibana,所以可以结合 ELK 使用,可在 Kibana 查看监控然后直接查询日志。 6 | 7 | Elastic APM 架构如下: 8 | 9 | ![](./assets/5.2.1.png) 10 | 11 | **可以看出**:APM Agent(即在应用端引入的探针)将收集的日志发送到 APM Server(Go 写的 HTTP 服务),APM Server 将数据存储到 ElasticSearch,然后通过 Kibana 展示。 12 | 13 | Kibana 展示如下: 14 | 15 | ![](./assets/5.2.2.png) 16 | 17 | ## 安装并启动 ELK 18 | 19 | 我们使用 docker 安装并启动 ELK,运行如下命令: 20 | 21 | ```sh 22 | $ docker run -p 5601:5601 \ 23 | -p 9200:9200 \ 24 | -p 5044:5044 \ 25 | -it --name elk sebp/elk 26 | ``` 27 | 28 | ## 安装并启动 APM Server 29 | 30 | 首先,下载 [APM Server](https://www.elastic.co/downloads/apm/apm-server) 解压。然后运行以下命令: 31 | 32 | ```sh 33 | $ ./apm-server setup # 导入 APM 仪表盘到 Kibana 34 | $ ./apm-server -e # 启动 APM Server,默认监听 8200 端口 35 | ``` 36 | 37 | 浏览器打开 localhost:5601,进入 Dashboard 页,如下所示: 38 | 39 | ![](./assets/5.2.3.png) 40 | 41 | ## 测试代码 42 | 43 | ```js 44 | const apm = require('elastic-apm-node').start({ 45 | appName: 'test' 46 | }) 47 | 48 | const Paloma = require('paloma') 49 | const app = new Paloma() 50 | 51 | app.route({ method: 'GET', path: '/', controller (ctx) { 52 | apm.setTransactionName(`${ctx.method} ${ctx._matchedRoute}`) 53 | ctx.status = 200 54 | }}) 55 | 56 | app.route({ method: 'GET', path: '/:name', controller (ctx) { 57 | apm.setTransactionName(`${ctx.method} ${ctx._matchedRoute}`) 58 | ctx.status = 200 59 | }}) 60 | 61 | app.listen(3000) 62 | ``` 63 | 64 | 运行该程序,发起两个请求: 65 | 66 | ```sh 67 | $ curl localhost:3000/ 68 | $ curl localhost:3000/nswbmw 69 | ``` 70 | 71 | 等待一会,Kibana 展示如下: 72 | 73 | ![](./assets/5.2.4.png) 74 | 75 | 在 Elastic APM 中,有两个术语: 76 | 77 | - transaction:一组 traces 的集合,如:一个 HTTP 请求 78 | - trace:一个事件及持续时间,如:一个 SQL 查询 79 | 80 | ## 错误日志 81 | 82 | 我们来测试下 Elastic APM 的错误收集功能。修改测试代码为: 83 | 84 | ```js 85 | const apm = require('elastic-apm-node').start({ 86 | appName: 'test' 87 | }) 88 | 89 | const Paloma = require('paloma') 90 | const app = new Paloma() 91 | 92 | app.use(async (ctx, next) => { 93 | try { 94 | await next() 95 | } catch (e) { 96 | apm.captureError(e) 97 | ctx.status = 500 98 | ctx.message = e.message 99 | } 100 | }) 101 | 102 | app.route({ method: 'GET', path: '/', controller: function indexRouter (ctx) { 103 | apm.setTransactionName(`${ctx.method} ${ctx._matchedRoute}`) 104 | throw new Error('error!!!') 105 | }}) 106 | 107 | app.listen(3000) 108 | ``` 109 | 110 | 重启测试程序,并发起一次请求。回到 Kibana,点击 Dashboard -> [APM] Errors 可以看到错误日志记录(自动聚合)和图表,如下所示: 111 | 112 | ![](./assets/5.2.5.png) 113 | 114 | 点击 View Error Details 进入错误详情页,如下所示: 115 | 116 | ![](./assets/5.2.6.png) 117 | 118 | **可以看出**:错误日志中展示了错误代码及行数,上下几行代码,父级函数名和所在文件等信息。 119 | 120 | ## 参考链接 121 | 122 | - https://www.elastic.co/guide/en/apm/agent/nodejs/0.x/index.html 123 | - https://www.elastic.co/guide/en/apm/agent/nodejs/0.x/custom-stack.html 124 | 125 | 上一节:[5.1 NewRelic](https://github.com/nswbmw/node-in-debugging/blob/master/5.1%20NewRelic.md) 126 | 127 | 下一节:[6.1 koa-await-breakpoint](https://github.com/nswbmw/node-in-debugging/blob/master/6.1%20koa-await-breakpoint.md) 128 | -------------------------------------------------------------------------------- /8.2 alinode.md: -------------------------------------------------------------------------------- 1 | ## 什么是 alinode ? 2 | 3 | > Node.js 性能平台(原 alinode)是面向中大型 Node.js 应用提供性能监控、安全提醒、故障排查、性能优化 等服务的整体性解决方案。alinode 团队凭借对 Node.js 内核深入的理解,提供完善的工具链和服务,协助客户主动、快速发现和定位线上问题。 4 | 5 | ## 创建 alinode 应用 6 | 7 | 访问官网 http://alinode.aliyun.com/,登录后点击『创建新应用』,创建一个名为 test_alinode 的应用。 8 | 9 | 进入设置页面,如下所示: 10 | 11 | ![](./assets/8.2.1.png) 12 | 13 | App ID 和 App Secret 后面会用到。 14 | 15 | ## 安装 alinode 16 | 17 | alinode 整套服务由 alinode 运行时、agenthub(原 agentx + commdx 命令集)、服务平台组成,所以在自己的服务器上部署时需要安装 alinode 运行时和 agenthub。 18 | 19 | 我们使用交互式一键安装 alinode 和 agenthub: 20 | 21 | ```sh 22 | $ uname -a # 阿里云 ECS Ubuntu@16.04 23 | Linux nswbmw 4.4.0-105-generic #128-Ubuntu SMP Thu Dec 14 12:42:11 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux 24 | $ wget https://raw.githubusercontent.com/aliyun-node/alinode-all-in-one/master/alinode_all.sh 25 | $ bash -i alinode_all.sh # App ID 和 App Secret 填写上面生成的 26 | ... 27 | $ node -p 'process.alinode' # 查看 alinode 版本 28 | ``` 29 | 30 | **注意**:如果遇到 wget 报错 `wget: unable to resolve host address 'raw.githubusercontent.com'`,需要修改 DNS 配置,在 /etc/resolv.conf 最上面添加 `nameserver 8.8.8.8`。 31 | 32 | 生成 yourconfig.json 配置文件如下: 33 | 34 | ```json 35 | { 36 | "server": "agentserver.node.aliyun.com:8080", 37 | "appid": "xxx", 38 | "secret": "xxx", 39 | "logdir": "/tmp/", 40 | "reconnectDelay": 10, 41 | "heartbeatInterval": 60, 42 | "reportInterval": 60, 43 | "error_log": [], 44 | "packages": [] 45 | } 46 | ``` 47 | 48 | 使用该配置启动 agenthub: 49 | 50 | ```sh 51 | $ nohup agenthub yourconfig.json & 52 | ``` 53 | 54 | agenthub 将以常驻进程的方式运行。 55 | 56 | ## 测试代码 57 | 58 | 我们使用 alinode 演示如何调试内存泄漏的问题。 59 | 60 | **server.js** 61 | 62 | ```js 63 | const Paloma = require('paloma') 64 | const session = require('koa-generic-session') 65 | const app = new Paloma() 66 | 67 | app.keys = ['some secret'] 68 | app.use(session()) 69 | 70 | class User { 71 | constructor () { 72 | this.name = new Array(1e6).join('*') 73 | } 74 | } 75 | 76 | app.use((ctx) => { 77 | ctx.session.user = new User() 78 | ctx.status = 204 79 | }) 80 | 81 | app.listen(3000) 82 | ``` 83 | 84 | 这段代码内存泄露的原因是:koa-generic-session 默认将 session 信息存储到了内存中。 85 | 86 | **client.js** 87 | 88 | ```js 89 | const axios = require('axios') 90 | 91 | setInterval(() => { 92 | axios.get('http://localhost:3000') 93 | }, 1000) 94 | ``` 95 | 96 | 起两个终端分别运行 : 97 | 98 | ```sh 99 | $ ENABLE_NODE_LOG=YES node server # 开启 alinode 的 log 功能,使得 agenthub 可以监控内核级的性能数据 100 | $ node client # 1s 发起一次请求 101 | ``` 102 | 103 | 过一会就可以在 alinode 控制台看到数据了,如下所示: 104 | 105 | ![](./assets/8.2.2.png) 106 | 107 | 可以看出,alinode 监控了: 108 | 109 | - 异常日志 110 | - 慢 HTTP 日志 111 | - 模块依赖 112 | - 系统监控数据(包含非常详尽的图表数据) 113 | - Memory 114 | - CPU 115 | - Load 116 | - QPS 117 | - GC 118 | - Apdex 119 | - Apdex detail 120 | - node 进程数 121 | - 磁盘 122 | 123 | 124 | 点击『堆快照』生成一个 heapsnapshot 文件,点击左侧『文件』查看刚才生成的堆快照: 125 | 126 | ![](./assets/8.2.3.png) 127 | 128 | 转储后点击『分析』,选择『对象簇视图』的树状列表,展开如下所示: 129 | 130 | ![](./assets/8.2.4.png) 131 | 132 | **可以看出**:MemoryStore 的 sessions 对象中存储了 97 个 session,并且每个 session.user 上有一个 name 字段是长字符串。 133 | 134 | **Tips**:你也可以选择『devtools 分析』或者下载下来使用 Chrome DevTools 分析,效果是一样的。 135 | 136 | alinode 支持抓取并在线分析四种性能数据: 137 | 138 | - 堆快照 139 | - 堆时间线 140 | - CPU profile 141 | - GC Trace 142 | 143 | 本文就不一一演示了。 144 | 145 | alinode 如此强大,而且免费使用,可以说是开发 Node.js 应用必不可少的好伙伴了。 146 | 147 | ## 参考链接 148 | 149 | - http://alinode.aliyun.com/ 150 | 151 | - https://www.aliyun.com/product/nodejs 152 | 153 | - https://github.com/aliyun-node/agenthub 154 | 155 | - https://cnodejs.org/topic/561f289b4928c5872abc18ee 156 | 157 | 上一节:[8.1 node-clinic](https://github.com/nswbmw/node-in-debugging/blob/master/8.1%20node-clinic.md) 158 | -------------------------------------------------------------------------------- /2.4 cpu-memory-monitor.md: -------------------------------------------------------------------------------- 1 | 前面介绍了 heapdump 和 memwatch-next 的用法,但在实际使用时并不那么方便,你总不能一直盯着服务器状况,发现内存持续增长并超过了你心里的阈值时,手动的去触发 Memory Dump 吧?大多数情况下当你发现问题时,已经错过了现场。 2 | 3 | 那你可能需要 [cpu-memory-monitor](https://github.com/nswbmw/cpu-memory-monitor)。顾名思义,这个模块可以用来监控 CPU 和 Memory 的使用情况,并可以根据配置策略自动 dump CPU 的使用情况(cpuprofile)和内存快照(heapsnapshot)。 4 | 5 | ## 使用方法 6 | 7 | 我们先来看看 cpu-memory-monitor 怎么使用,其实很简单,只需要在进程启动的入口文件引入以下代码即可: 8 | 9 | ```js 10 | require('cpu-memory-monitor')({ 11 | cpu: { 12 | interval: 1000, 13 | duration: 30000, 14 | threshold: 60, 15 | profileDir: '/tmp', 16 | counter: 3, 17 | limiter: [5, 'hour'] 18 | } 19 | }) 20 | ``` 21 | 22 | **含义**:每 **1000ms**(interval)检查一次 CPU 使用情况,如果发现连续 **3**(counter)次 CPU 使用率大于 **60%**(threshold),则 dump **30000ms**(duration) CPU 的使用情况,生成 `cpu-${process.pid}-${Date.now()}.cpuprofile` 到 **/tmp**(profileDir) 目录下,**1**(limiter[1]) 小时最多 dump **5**(limiter[0]) 次。 23 | 24 | 上面是自动 dump CPU 使用情况的策略。Memory 的同理: 25 | 26 | ```js 27 | require('cpu-memory-monitor')({ 28 | memory: { 29 | interval: 1000, 30 | threshold: '1.2gb', 31 | profileDir: '/tmp', 32 | counter: 3, 33 | limiter: [3, 'hour'] 34 | } 35 | }) 36 | ``` 37 | 38 | **含义**:每 **1000ms**(interval) 检查一次 Memory 使用情况,如果发现连续 **3**(counter) 次 Memory 大于 **1.2gb**(threshold),则 dump 一次 Memory,生成 `memory-${process.pid}-${Date.now()}.heapsnapshot` 到 **/tmp**(profileDir) 目录下,**1**(limiter[1]) 小时最多 dump **3**(limiter[0]) 次。 39 | 40 | **注意**:memory 的配置没有 duration 参数,因为 Memroy 的 dump 只是某一时刻而不是一段时间的。 41 | 42 | 那聪明的你肯定会问了:能不能 cpu 和 memory 配置一块用?比如: 43 | 44 | ```js 45 | require('cpu-memory-monitor')({ 46 | cpu: { 47 | interval: 1000, 48 | duration: 30000, 49 | threshold: 60, 50 | ... 51 | }, 52 | memory: { 53 | interval: 10000, 54 | threshold: '1.2gb', 55 | ... 56 | } 57 | }) 58 | ``` 59 | 60 | 答案是:**可以,但不要这么做。**因为可能会出现这种情况:内存高了 -> 达到阈值,触发 Memory Dump/GC -> 导致了 CPU 高 -> 达到阈值,触发 CPU Dump -> 堆积的请求越来越多(比如内存中堆积了很多 SQL 查询)-> 触发 Memory Dump -> 雪崩。 61 | 62 | 通常情况下,只需要用其中一种就可以了。 63 | 64 | ## 源代码解读 65 | 66 | cpu-memory-monitor 的源代码不过百余行,大体逻辑如下: 67 | 68 | ```js 69 | ... 70 | const processing = { 71 | cpu: false, 72 | memory: false 73 | } 74 | 75 | const counter = { 76 | cpu: 0, 77 | memory: 0 78 | } 79 | 80 | function dumpCpu(cpuProfileDir, cpuDuration) { ... } 81 | function dumpMemory(memProfileDir) { ... } 82 | 83 | module.exports = function cpuMemoryMonitor(options = {}) { 84 | ... 85 | if (options.cpu) { 86 | const cpuTimer = setInterval(() => { 87 | if (processing.cpu) { 88 | return 89 | } 90 | pusage.stat(process.pid, (err, stat) => { 91 | if (err) { 92 | clearInterval(cpuTimer) 93 | return 94 | } 95 | if (stat.cpu > cpuThreshold) { 96 | counter.cpu += 1 97 | if (counter.cpu >= cpuCounter) { 98 | memLimiter.removeTokens(1, (limiterErr, remaining) => { 99 | if (limiterErr) { 100 | return 101 | } 102 | if (remaining > -1) { 103 | dumpCpu(cpuProfileDir, cpuDuration) 104 | counter.cpu = 0 105 | } 106 | }) 107 | } else { 108 | counter.cpu = 0 109 | } 110 | } 111 | }) 112 | }, cpuInterval) 113 | } 114 | 115 | if (options.memory) { 116 | ... 117 | memwatch.on('leak', () => { 118 | dumpMemory(...) 119 | }) 120 | } 121 | } 122 | ``` 123 | 124 | **可以看出**:cpu-memory-monitor 没有用到什么新鲜的东西,还是之前讲解过的 v8-profiler、heapdump、memwatch-next 组合使用而已。 125 | 126 | 有几点需要注意下: 127 | 128 | 1. 只有传入了 cpu 或者 memory 的配置,才会去监听相应的 CPU 或者 Memory。 129 | 2. 传入 memory 配置时,用了 memwatch-next 额外监听了 leak 事件,也会 dump Memory,格式是 `leak-memory-${process.pid}-${Date.now()}.heapsnapshot`。 130 | 3. 顶部引入了 heapdump,所以即使没有 memory 配置,也可以通过 `kill -USR2 ` 手动触发 Memory Dump。 131 | 132 | 上一节:[2.3 memwatch-next](https://github.com/nswbmw/node-in-debugging/blob/master/2.3%20memwatch-next.md) 133 | 134 | 下一节:[3.1 Async + Await](https://github.com/nswbmw/node-in-debugging/blob/master/3.1%20Async%20%2B%20Await.md) 135 | -------------------------------------------------------------------------------- /2.2 heapdump.md: -------------------------------------------------------------------------------- 1 | [heapdump](https://github.com/bnoordhuis/node-heapdump) 是一个 dump V8 堆信息的工具。[v8-profiler](https://github.com/node-inspector/v8-profiler) 也包含了此功能,这两个工具的原理都是一致的,都是 v8::Isolate::GetCurrent()->GetHeapProfiler()->TakeHeapSnapshot(title, control)。heapdump 的使用简单些,下面我们以 heapdump 为例讲解如何分析 Node.js 内存泄漏。 2 | 3 | 我们用一段经典的内存泄漏代码当作我们的测试代码,代码如下: 4 | 5 | **app.js** 6 | 7 | ```js 8 | const heapdump = require('heapdump') 9 | let leakObject = null 10 | let count = 0 11 | 12 | setInterval(function testMemoryLeak() { 13 | const originLeakObject = leakObject 14 | const unused = function () { 15 | if (originLeakObject) { 16 | console.log('originLeakObject') 17 | } 18 | } 19 | leakObject = { 20 | count: String(count++), 21 | leakStr: new Array(1e7).join('*'), 22 | leakMethod: function () { 23 | console.log('leakMessage') 24 | } 25 | } 26 | }, 1000) 27 | ``` 28 | 29 | 为什么这段程序会发生内存泄漏呢?首先我们要明白闭包的原理: 30 | 31 | **同一个函数内部的闭包作用域只有一个,所有闭包共享。在执行函数的时候,如果遇到闭包,会创建闭包作用域内存空间,将该闭包所用到的局部变量添加进去,然后再遇到闭包,会在之前创建好的作用域空间添加此闭包会用到而前闭包没用到的变量。函数结束,清除没有被闭包作用域引用的变量。** 32 | 33 | **这段代码内存泄露原因是**:testMemoryLeak 函数内有两个闭包:unused 和 leakMethod。unused 这个闭包引用了父作用域中的 originLeakObject 变量,如果没有后面的 leakMethod,则会在函数结束后清除,闭包作用域也跟着清除了。因为后面的 leakObject 是全局变量,即 leakMethod 是全局变量,它引用的闭包作用域(包含了 unused 所引用的 originLeakObject)不会释放。而随着 testMemoryLeak 不断调用,originLeakObject 指向前一次的 leakObject,下次的 leakObject.leakMethod 又会引用之前的 originLeakObject,从而形成一个闭包引用链,而 leakStr 是一个大字符串,得不到释放,从而造成内存泄漏。 34 | 35 | **解决方法**:在 testMemoryLeak 函数内部最后添加 `originLeakObject = null` 即可。 36 | 37 | 运行测试代码: 38 | 39 | ```sh 40 | $ node app 41 | ``` 42 | 43 | 然后先后执行**两**次: 44 | 45 | ```sh 46 | $ kill -USR2 `pgrep -n node` 47 | ``` 48 | 49 | 目录下产生了两个 heapsnapshot 文件: 50 | 51 | ``` 52 | heapdump-100427359.61348.heapsnapshot 53 | heapdump-100438986.797085.heapsnapshot 54 | ``` 55 | 56 | ## Chrome DevTools 57 | 58 | 我们使用 Chrome DevTools 来分析前面生成的 heapsnapshot 文件。调出 Chrome DevTools -> Memory -> Load,按顺序依次加载前面生成的 heapsnapshot 文件。点击第二个堆快照,左上角有个下拉菜单,有四个选项: 59 | 60 | 1. Summary:以构造函数名分类显示 61 | 2. Comparison:比较多个快照之间的差异 62 | 3. Containment:查看整个 GC 路径 63 | 4. Statistics:以饼状图显示内存占用信息 64 | 65 | 通常我们只会用前两个,第三个一般用不到,因为展开在 Summary 和 Comparison 中的每一项,都可以看到从 GC roots 到这个对象的路径。第四个选项只能看到内存占用比,如下图所示: 66 | 67 | ![](./assets/2.2.1.png) 68 | 69 | 切换到 Summary 页,可以看到有 5 个属性: 70 | 71 | 1. Contructor:构造函数名,如 Object、Module、Socket,(array)、(string)、(regexp) 等加了括号的分别代表内置的 Array、String、Regexp 72 | 2. Distance:到 GC roots (GC 根对象)的距离。GC 根对象在浏览器中一般是 window 对象,在 Node.js 中是 global 对象。距离越大,说明引用越深,则有必要重点关注一下,极有可能是内存泄漏的对象 73 | 3. Objects count:对象个数 74 | 4. Shallow Size:对象自身大小,不包括它引用的对象 75 | 5. Retained Size:对象自身大小和它引用对象的大小,即该对象被 GC 之后所能回收的内存大小 76 | 77 | **Tips**: 一个对象的 Retained Size = 该对象的 Shallow Size + 该对象可直接或间接引用到的对象的 Shallow Size 之和。Shallow Size == Retained Size 的有 (boolean)、(number)、(string),它们无法引用其他值,并且始终是叶子节点。 78 | 79 | 我们点击 Retained Size 选择降序展示,可以看到 (closure) 这一项引用的内容达到 98%,继续展开如下: 80 | 81 | ![](./assets/2.2.2.png) 82 | 83 | **可以看出**:一个 leakStr 占了 8% 的内存,而 leakMethod 引用了 81% 的内存。对象保留树(Retainers,老版本 Chrome 叫 Object's retaining tree)展示了对象的 GC path,如上图点击 leakStr(Distance 是 13),Retainers 会自动展开,Distance 从 13 递减到 1。 84 | 85 | 我们继续展开 leakMethod,如下所示: 86 | 87 | ![](./assets/2.2.3.png) 88 | 89 | **可以看出**:有一个 count="10" 的 originLeakObject 的 leakMethod 函数的 context(即上下文) 引用了一个 count="9" 的 originLeakObject 对象,而这个 originLeakObject 对象的 leakMethod 函数的 context 又引用了 count="8" 的 originLeakObject 对象,以此类推。而每个 originLeakObject 对象上都有一个大字符串 leakStr(占用 8% 内存),从而造成内存泄漏,符合我们之前的推断。 90 | 91 | **Tips:**背景色是黄色的,表示这个对象在 JavaScript 中还存在引用,所以可能没有被清除。如果是红色的,表示的是这个对象在 JavaScript 中不存在引用,但是依然存活在内存中,一般常见于 DOM 对象,它们存放的位置和 JavaScript 中对象还是有不同的,在 Node.js 中很少遇见。 92 | 93 | ## 对比快照 94 | 95 | 切换到 Comparison 视图下,可以看到一些 #New、#Deleted、#Delta 等属性,+ 和 - 代表相对于比较的堆快照而言。我们对比第二个快照和第一个快照,从下图可以看出,(string) 增加的最多: 96 | 97 | ![](./assets/2.2.4.png) 98 | 99 | ## 参考链接 100 | 101 | - https://blog.meteor.com/an-interesting-kind-of-javascript-memory-leak-8b47d2e7f156 102 | - https://www.zhihu.com/question/56806069 103 | - http://taobaofed.org/blog/2016/04/15/how-to-find-memory-leak/ 104 | - https://developers.google.com/web/tools/chrome-devtools/memory-problems/memory-101 105 | 106 | 上一节:[2.1 gcore + llnode](https://github.com/nswbmw/node-in-debugging/blob/master/2.1%20gcore%20%2B%20llnode.md) 107 | 108 | 下一节:[2.3 memwatch-next](https://github.com/nswbmw/node-in-debugging/blob/master/2.3%20memwatch-next.md) 109 | -------------------------------------------------------------------------------- /6.3 ELK.md: -------------------------------------------------------------------------------- 1 | ELK 是 ElasticSearch + Logstash + Kibana 这套组合工具的简称。 2 | 3 | - ElasticSearch:是一个开源的基于 Lucene 之上实现的一个分布式搜索引擎,也是一个存储引擎(如:日志),它的特点有:分布式,零配置,自动发现,索引自动分片,索引副本机制,restful 风格接口,多数据源,自动搜索负载等。 4 | - Logstash:开源的日志收集工具,它可以对日志进行收集、分析、过滤,并将其存储(如:ElasticSearch)供以后使用。 5 | - Kibana:开源和免费的可视化工具,可以为 ElasticSearch 提供的日志分析友好的 Web 界面,可以汇总、分析和搜索重要数据日志。 6 | 7 | ## 安装 ELK 8 | 9 | 我们使用 docker 安装 ELK,运行如下命令: 10 | 11 | ```sh 12 | $ docker run -p 5601:5601 \ 13 | -p 9200:9200 \ 14 | -p 5044:5044 \ 15 | -p 15044:15044/udp \ 16 | -it --name elk sebp/elk 17 | ``` 18 | 19 | 进入容器: 20 | 21 | ```sh 22 | $ docker exec -it elk /bin/bash 23 | ``` 24 | 25 | 运行以下命令设置 logstash 的 input 和 output: 26 | 27 | ```sh 28 | # /opt/logstash/bin/logstash --path.data /tmp/logstash/data \ 29 | -e 'input { udp { codec => "json" port => 15044 } } output { elasticsearch { hosts => ["localhost"] } }' 30 | ``` 31 | 32 | 这里我们启动一个 15044 udp 端口,用来接收通过 UDP 发送到 Logstash 的日志。 33 | 34 | 浏览器打开 localhost:5601,如下所示: 35 | 36 | ![](./assets/6.3.1.png) 37 | 38 | 目前还没有指定 index(ElasticSearch 的 index 类似 MySQL/MongoDB 中的 database),即日志来源。下面我们尝试往 ELK 写入一些日志。 39 | 40 | ## 使用 ELK 41 | 42 | 我们仍然使用 koa-await-breakpoint 为例,来演示如何将日志发送到 ELK。 43 | 44 | **app.js** 45 | 46 | ```js 47 | const koaAwaitBreakpoint = require('koa-await-breakpoint')({ 48 | name: 'api', 49 | files: ['./routes/*.js'], 50 | store: require('./logger') 51 | }) 52 | 53 | const Paloma = require('paloma') 54 | const app = new Paloma() 55 | 56 | app.use(koaAwaitBreakpoint) 57 | app.route({ method: 'POST', path: '/users', controller: require('./routes/user').createUser }) 58 | 59 | app.listen(3000) 60 | ``` 61 | 62 | **logger.js** 63 | 64 | ```js 65 | const Logstash = require('logstash-client') 66 | 67 | const logstash = new Logstash({ 68 | type: 'udp', 69 | host: 'localhost', 70 | port: 15044 71 | }) 72 | 73 | module.exports = { 74 | save (log) { 75 | if (log.error) { 76 | log.errMsg = log.error.message 77 | log.errStack = log.error.stack 78 | } 79 | logstash.send(log) 80 | } 81 | } 82 | ``` 83 | 84 | **routes/user.js** 85 | 86 | ```js 87 | const Mongolass = require('mongolass') 88 | const mongolass = new Mongolass('mongodb://localhost:27017/test') 89 | const User = mongolass.model('User') 90 | const Post = mongolass.model('Post') 91 | const Comment = mongolass.model('Comment') 92 | 93 | exports.createUser = async function (ctx) { 94 | const name = ctx.query.name || 'default' 95 | const age = +ctx.query.age || 18 96 | await createUser(name, age) 97 | ctx.status = 204 98 | } 99 | 100 | async function createUser (name, age) { 101 | const user = (await User.create({ 102 | name, 103 | age 104 | })).ops[0] 105 | await createPost(user) 106 | } 107 | 108 | async function createPost (user) { 109 | const post = (await Post.create({ 110 | uid: user._id, 111 | title: 'post', 112 | content: 'post' 113 | })).ops[0] 114 | 115 | await createComment(user, post) 116 | } 117 | 118 | async function createComment (user, post) { 119 | await Comment.create({ 120 | userId: user._id, 121 | postId: post._id, 122 | content: 'comment' 123 | }) 124 | } 125 | ``` 126 | 127 | 运行: 128 | 129 | ```sh 130 | $ curl -XPOST localhost:3000/users 131 | ``` 132 | 133 | 此时,刷新 Kibana 如下所示: 134 | 135 | ![](./assets/6.3.2.png) 136 | 137 | 初次使用需要配置 Kibana 从 ElasticSearch 的哪些 index 搜索日志,我们在 `Index pattern` 处填 `logstash-*`,然后点击 Next step。下一步的 `Time Filter field name` 选择 timestamp 点击 Create index pattern 完成配置。 138 | 139 | **注意**:我们选择 timestamp 而不是默认的 @timestamp,因为 koa-await-breakpoint 的日志中有 timestamp 字段。 140 | 141 | 点击左侧目录 Discover,我们发现已经有日志了。分别点击左侧出现的 Available Fields 的 fn、type、step、take,然后按 step 升序展示,如下所示: 142 | 143 | ![](./assets/6.3.3.png) 144 | 145 | 是不是一目了然!每个请求每一步的函数及其执行时间都记录下来了。 146 | 147 | 修改 routes/users.js 的 createComment,throw 一个 `new Error('test')`。重启程序并发起一个请求,ELK 显示如下: 148 | 149 | ![](./assets/6.3.4.png) 150 | 151 | **Tips**: 实际应用中会有非常多的日志,我们可以通过 requestId 找到一个请求的所有日志,第 7.2 小节会讲解。 152 | 153 | ELK 非常强大,基本能满足所有日志查询需求,查询语法使用 lucene 语法,花个 10 分钟就能大体上手。Kibana 还能创建各种仪表盘和聚合图表,还请读者自己动手尝试。 154 | 155 | ## 参考文献 156 | 157 | - http://blog.51cto.com/baidu/1676798 158 | - http://elk-docker.readthedocs.io 159 | 160 | 上一节:[6.2 async_hooks](https://github.com/nswbmw/node-in-debugging/blob/master/6.2%20async_hooks.md) 161 | 162 | 下一节:[6.4 OpenTracing + Jaeger](https://github.com/nswbmw/node-in-debugging/blob/master/6.4%20OpenTracing%20%2B%20Jaeger.md) 163 | -------------------------------------------------------------------------------- /4.1 Source Map.md: -------------------------------------------------------------------------------- 1 | Source Map 想必大家并不陌生,在前端开发中通常要压缩 js, css,减少体积,加快网页显示。但带来的后果是如果出现错误,导致无法定位错误,Source Map 应用而生。举个例子, jQuery 1.9 引入了 Source Map,打开 http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js,最后一行是这样的: 2 | 3 | ```js 4 | //@ sourceMappingURL=jquery.min.map 5 | ``` 6 | 7 | 这就是 Source Map。它是一个独立的 map(其实就是 JSON) 文件,通常与源码在同一个目录下。 8 | 9 | Source Map 用在以下几个场景: 10 | 11 | 1. 压缩代码,减小体积。比如 jQuery 1.9 的源码,压缩前是 252KB,压缩后是 32KB。 12 | 2. 多个文件合并,减少 HTTP 请求数,针对前端而言。 13 | 3. 其他语言编译成 JavaScript,如:CoffeeScript、TypeScript 等。 14 | 15 | 本文只讲解如何使用 Source Map,关于 map 文件中字段的含义本文不会解释,有兴趣的请查看参考链接中的文章。接下来我们在 Node.js 环境下以场景 1、3 为例,分别介绍 uglify-es 和 TypeScript 如何结合 Source Map 使用。 16 | 17 | ## uglify-es 18 | 19 | uglify-js 是最常用的 js 代码压缩工具,但只支持到 ES5,uglify-es 支持 ES6+ 并且兼容 uglify-js,所以本文使用 uglify-es。 20 | 21 | source-map-support 是一个在 Node.js 环境下支持 Source Map 的模块。 22 | 23 | 安装 uglify-es 和 source-map-support: 24 | 25 | ```sh 26 | $ npm i uglify-es -g 27 | $ npm i source-map-support 28 | ``` 29 | 30 | 创建测试代码: 31 | 32 | **app.js** 33 | 34 | ```js 35 | require('source-map-support').install() 36 | 37 | function sayHello (name) { 38 | throw new Error('error!!!') 39 | console.log(`Hello, ${name}`) 40 | } 41 | 42 | sayHello('World') 43 | ``` 44 | 45 | 使用 uglify-es 压缩代码文件并生成 map 文件: 46 | 47 | ```sh 48 | $ uglifyjs app.js -o app.min.js --source-map "url=app.min.js.map" 49 | ``` 50 | 51 | 生成 app.min.js 和 app.min.js.map 文件,内容分别如下: 52 | 53 | **app.min.js** 54 | 55 | ```js 56 | require("source-map-support").install();function sayHello(name){throw new Error("error!!!");console.log(`Hello, ${name}`)}sayHello("World"); 57 | //# sourceMappingURL=app.min.js.map 58 | ``` 59 | 60 | **app.min.js.map** 61 | 62 | ```json 63 | {"version":3,"sources":["app.js"],"names":["require","install","sayHello","name","Error","console","log"],"mappings":"AAAAA,QAAQ,sBAAsBC,UAE9B,SAASC,SAAUC,MACjB,MAAM,IAAIC,MAAM,YAChBC,QAAQC,cAAcH,QAGxBD,SAAS"} 64 | ``` 65 | 66 | 此时运行 app.min.js 可以显示正确的错误栈: 67 | 68 | ```js 69 | $ node app.min.js 70 | 71 | /Users/nswbmw/Desktop/test/app.js:4 72 | throw new Error('error!!!') 73 | ^ 74 | Error: error!!! 75 | at sayHello (/Users/nswbmw/Desktop/test/app.js:4:9) 76 | ``` 77 | 78 | 如果删除 app.min.js 最后那行注释,重新运行则无法显示正确的错误栈: 79 | 80 | ```js 81 | $ node app.min.js 82 | 83 | /Users/nswbmw/Desktop/test/app.min.js:1 84 | require("source-map-support").install();function sayHello(name){throw new Error("error!!!");console.log(`Hello, ${name}`)}sayHello("World"); 85 | ^ 86 | Error: error!!! 87 | at sayHello (/Users/nswbmw/Desktop/test/app.min.js:1:71) 88 | ``` 89 | 90 | source-map-support 是通过 Error.prepareStackTrace 实现的,前面讲解过它的用法,这里不再赘述。 91 | 92 | ## TypeScript 93 | 94 | 全局安装 TypeScript: 95 | 96 | ```sh 97 | $ npm i typescript -g 98 | ``` 99 | 100 | 创建测试代码: 101 | 102 | **app_ts.ts** 103 | 104 | ```typescript 105 | declare function require(name: string) 106 | require('source-map-support').install() 107 | 108 | function sayHello (name: string): any { 109 | throw new Error('error!!!') 110 | } 111 | 112 | sayHello('World') 113 | ``` 114 | 115 | 运行: 116 | 117 | ```sh 118 | $ tsc --sourceMap app_ts.ts 119 | ``` 120 | 121 | 生成 app_ts.js 和 app_ts.js.map,运行 app_ts.js 如下: 122 | 123 | ```js 124 | $ node app_ts.js 125 | 126 | /Users/nswbmw/Desktop/test/app_ts.ts:5 127 | throw new Error('error!!!') 128 | ^ 129 | Error: error!!! 130 | at sayHello (/Users/nswbmw/Desktop/test/app_ts.ts:5:9) 131 | ``` 132 | 133 | ## source-map-support 高级用法 134 | 135 | 我们可以在调用 install 方法时传入一个 retrieveSourceMap 参数,用来自定义处理 Source Map: 136 | 137 | ```js 138 | require('source-map-support').install({ 139 | retrieveSourceMap: function(source) { 140 | if (source === 'compiled.js') { 141 | return { 142 | url: 'original.js', 143 | map: fs.readFileSync('compiled.js.map', 'utf8') 144 | } 145 | } 146 | return null 147 | } 148 | }) 149 | ``` 150 | 151 | 比如将所有 map 文件缓存到内存中,而不是磁盘上。 152 | 153 | ## 参考链接 154 | 155 | - http://www.ruanyifeng.com/blog/2013/01/javascript_source_map.html 156 | - https://yq.aliyun.com/articles/73529 157 | - https://github.com/v8/v8/wiki/Stack-Trace-API 158 | - https://github.com/evanw/node-source-map-support 159 | 160 | 上一节:[3.4 Rust Addons](https://github.com/nswbmw/node-in-debugging/blob/master/3.4%20Rust%20Addons.md) 161 | 162 | 下一节:[4.2 Chrome DevTools](https://github.com/nswbmw/node-in-debugging/blob/master/4.2%20Chrome%20DevTools.md) 163 | -------------------------------------------------------------------------------- /6.5 Sentry.md: -------------------------------------------------------------------------------- 1 | ## Sentry 是什么? 2 | 3 | Sentry [官网](sentry.io)介绍: 4 | 5 | > Sentry’s real-time error tracking gives you insight into production deployments and information to reproduce and fix crashes. 6 | 7 | **简言之**:Sentry 是一个开源的实时错误日志收集平台。 8 | 9 | ## 安装 Sentry 10 | 11 | 我们使用 Docker 安装并启动 Sentry,步骤如下: 12 | 13 | 1. 启动一个 Redis 容器,命名为 sentry-redis: 14 | 15 | ```sh 16 | $ docker run -d --name sentry-redis redis 17 | ``` 18 | 19 | 2. 启动一个 Postgres 容器,命名为 sentry-postgres: 20 | 21 | ```sh 22 | $ docker run -d \ 23 | --name sentry-postgres \ 24 | -e POSTGRES_PASSWORD=secret \ 25 | -e POSTGRES_USER=sentry \ 26 | postgres 27 | ``` 28 | 29 | 3. 生成一个 Sentry 的 secret key: 30 | 31 | ```sh 32 | $ docker run --rm sentry config generate-secret-key 33 | ``` 34 | 35 | 将下面的 都替换掉上面生成的 secret key。 36 | 37 | 4. 如果是新的数据库(即第一次运行),需要运行 upgrade: 38 | 39 | ```sh 40 | $ docker run -it --rm \ 41 | -e SENTRY_SECRET_KEY='' \ 42 | --link sentry-postgres:postgres \ 43 | --link sentry-redis:redis \ 44 | sentry upgrade 45 | ``` 46 | 47 | 如下,按步骤填写自己的信息: 48 | 49 | ![](./assets/6.5.1.jpg) 50 | 51 | 最终创建了一个超级管理员和一个默认的名为 sentry 的组织(organization)。 52 | 53 | 5. 启动 Sentry,并对外暴露 9000 端口: 54 | 55 | ```sh 56 | $ docker run -d \ 57 | --name my-sentry \ 58 | -e SENTRY_SECRET_KEY='' \ 59 | --link sentry-redis:redis \ 60 | --link sentry-postgres:postgres \ 61 | -p 9000:9000 \ 62 | sentry 63 | ``` 64 | 65 | 6. 启动 Celery cron 和 Celery workers: 66 | 67 | ```sh 68 | $ docker run -d \ 69 | --name sentry-cron \ 70 | -e SENTRY_SECRET_KEY='' \ 71 | --link sentry-postgres:postgres \ 72 | --link sentry-redis:redis \ 73 | sentry run cron 74 | ``` 75 | 76 | ```sh 77 | $ docker run -d \ 78 | --name sentry-worker-1 \ 79 | -e SENTRY_SECRET_KEY='' \ 80 | --link sentry-postgres:postgres \ 81 | --link sentry-redis:redis \ 82 | sentry run worker 83 | ``` 84 | 85 | **Tips**:Celery 是 Python 写的一个分布式任务调度模块。 86 | 87 | 7. 完成! 88 | 89 | 浏览器打开 localhost:9000 就能看到 Sentry 的登录页面了。 90 | 91 | ![](./assets/6.5.2.jpg) 92 | 93 | 首次登录需要填写一些必要信息 ,如下所示:![](./assets/6.5.3.png) 94 | 95 | 点击 Continue 进入 Sentry 仪表盘(Dashboard)。点击右上角 New Project 创建一个项目,选择 Node.js 并填写项目名称为 API,然后 Create Project 创建项目。如下所示: ![](./assets/6.5.4.png) 96 | 97 | 创建成功后进入 Node.js 使用示例页面,我们选择使用 Koa 测试,右侧选择 Koa: 98 | 99 | ![](./assets/6.5.5.png) 100 | 101 | 上图是 koa@1 的示例代码,我们以 Paloma(基于 koa@2)为例,编写测试代码: 102 | 103 | ```js 104 | const Raven = require('raven') 105 | const Paloma = require('paloma') 106 | const app = new Paloma() 107 | 108 | Raven.config(DSN).install() 109 | 110 | app.on('error', (err) => { 111 | Raven.captureException(err, function (err, eventId) { 112 | console.log('Reported error ' + eventId) 113 | }) 114 | }) 115 | 116 | app.use((ctx) => { 117 | throw new Error('test') 118 | }) 119 | 120 | app.listen(3000) 121 | ``` 122 | 123 | **Tips**:DSN 替换为第 10 步截图中的 `http://xxx@localhost:9000/2`,DSN 既告诉客户端 Sentry 服务器地址,也用来当做身份认证的 token。 124 | 125 | 运行以上测试代码,访问 localhost:3000,错误信息会发送给 Sentry。Sentry 展示如下: 126 | 127 | ![](./assets/6.5.6.png) 128 | 129 | 点进去可以看到详细的信息: 130 | 131 | ![](./assets/6.5.7.png) 132 | 133 | Sentry 还有许多功能比如:错误的归类、展示错误的频率柱状图、将错误指派给组织中的某个人、给错误添加标签、查看这类错误事件的历史、标记错误为已解决、在错误下发表评论、警报等等功能,更多配置见 Project Settings。 134 | 135 | ## koa-raven 136 | 137 | 笔者将 Raven 封装成 Koa 的一个中间件。使用如下: 138 | 139 | ```js 140 | const raven = require('koa-raven') 141 | const Paloma = require('paloma') 142 | const app = new Paloma() 143 | 144 | app.use(raven(DSN)) 145 | 146 | app.use((ctx) => { 147 | throw new Error('test') 148 | }) 149 | 150 | app.listen(3000) 151 | ``` 152 | 153 | 或者使用 ctx.raven: 154 | 155 | ```js 156 | const raven = require('koa-raven') 157 | const Paloma = require('paloma') 158 | const app = new Paloma() 159 | 160 | app.use(raven(DSN)) 161 | 162 | app.use((ctx) => { 163 | try { 164 | throw new Error('test') 165 | } catch (e) { 166 | ctx.raven.captureException(e, { extra: { name: 'tom' } }) 167 | ctx.status = 500 168 | ctx.body = e.stack 169 | } 170 | }) 171 | 172 | app.listen(3000) 173 | ``` 174 | 175 | 上一节:[6.4 OpenTracing + Jaeger](https://github.com/nswbmw/node-in-debugging/blob/master/6.4%20OpenTracing%20%2B%20Jaeger.md) 176 | 177 | 下一节:[7.1 Telegraf + InfluxDB + Grafana(上)](https://github.com/nswbmw/node-in-debugging/blob/master/7.1%20Telegraf%20%2B%20InfluxDB%20%2B%20Grafana(%E4%B8%8A).md) 178 | -------------------------------------------------------------------------------- /1.2 v8-profiler.md: -------------------------------------------------------------------------------- 1 | 我们知道 Node.js 是基于 v8 引擎的,v8 暴露了一些 profiler api,所以我们可以通过 [v8-profiler](https://github.com/node-inspector/v8-profiler) 收集一些运行时数据(如:CPU 和内存)。本文将介绍如何使用 v8-profiler 分析 CPU 的使用情况。 2 | 3 | ## v8-profiler 4 | 5 | 创建测试代码: 6 | 7 | **app.js** 8 | 9 | ```js 10 | const fs = require('fs') 11 | const crypto = require('crypto') 12 | const Bluebird = require('bluebird') 13 | const profiler = require('v8-profiler') 14 | const Paloma = require('paloma') 15 | const app = new Paloma() 16 | 17 | app.route({ method: 'GET', path: '/encrypt', controller: function encryptRouter (ctx) { 18 | const password = ctx.query.password || 'test' 19 | const salt = crypto.randomBytes(128).toString('base64') 20 | const encryptedPassword = crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha512').toString('hex') 21 | 22 | ctx.body = encryptedPassword 23 | }}) 24 | 25 | app.route({ method: 'GET', path: '/cpuprofile', async controller (ctx) { 26 | //Start Profiling 27 | profiler.startProfiling('CPU profile') 28 | await Bluebird.delay(30000) 29 | //Stop Profiling after 30s 30 | const profile = profiler.stopProfiling() 31 | profile.export() 32 | .pipe(fs.createWriteStream(`cpuprofile-${Date.now()}.cpuprofile`)) 33 | .on('finish', () => profile.delete()) 34 | ctx.status = 204 35 | }}) 36 | 37 | app.listen(3000) 38 | ``` 39 | 40 | `GET /encrypt` 有一个 CPU 密集型计算函数 crypto.pbkdf2Sync,`GET /cpuprofile` 用来收集 30s 的 v8 log 然后 dump 到一个文件。 41 | 42 | 运行该程序,然后起两个终端窗口。一个运行: 43 | 44 | ```sh 45 | $ curl localhost:3000/cpuprofile 46 | ``` 47 | 48 | 触发 CPU profiling,接着另一个立即运行: 49 | 50 | ```sh 51 | $ ab -c 20 -n 2000 "http://localhost:3000/encrypt?password=123456" 52 | ``` 53 | 54 | 触发 CPU 密集计算。 55 | 56 | 最后生成 cpuprofile-xxx.cpuprofile 文件,文件内容其实就是一个大的 JSON 对象,大体如下: 57 | 58 | ```json 59 | { 60 | "typeId": "CPU", 61 | "uid": "1", 62 | "title": "CPU profile", 63 | "head": 64 | { "functionName": "(root)", 65 | "url": "", 66 | "lineNumber": 0, 67 | "callUID": 154, 68 | "bailoutReason": "", 69 | "id": 1, 70 | "scriptId": 0, 71 | "hitCount": 0, 72 | "children": [ ... ] }, 73 | "startTime": 276245, 74 | "endTime": 276306, 75 | "samples": [ ... ], 76 | "timestamps": [ ... ] 77 | } 78 | ``` 79 | 80 | 这个 JSON 对象记录了函数调用栈、路径、时间戳和其他一些信息,samples 节点数组和 timestamps 节点数组中的时间戳是一一对应的,并且 samples 节点数组中的每一个值,其实对应了 head 节点的深度优先遍历 ID。这里我们不深究每个字段的含义,下面我们来看如何可视化这些数据。 81 | 82 | ## 1. Chrome DevTools 83 | 84 | Chrome 自带了分析 CPU profile 日志的工具。打开 Chrome -> 调出开发者工具(DevTools) -> 点击右上角三个点的按钮 -> More tools -> JavaScript Profiler -> Load,加载刚才生成的 cpuprofile 文件。左上角下拉菜单可选三种模式: 85 | 86 | 1. Chart:显示按时间顺序排列的火焰图 87 | 2. Heavy (Bottom Up):按照函数对性能的影响排列,同时可以检查函数的调用路径 88 | 3. Tree (Top Down):显示调用结构的总体状况,从调用堆栈的顶端开始 89 | 90 | 这里我们选 Tree (Top Down) 模式,按 Total Time 降序排列。可以看到有三列,分别为: 91 | 92 | 1. Self Time:函数调用所花的时间,仅包含函数本身的声明,不包含任何子函数执行时间 93 | 2. Total Time:函数调用所花的总时间,包含函数本身的声明及所有子函数执行时间 94 | 3. Function:函数名及路径,可展开查看子函数 95 | 96 | 一句话解释:**父函数的 Total Time = 父函数的 Self Time + 所有子函数的 Total Time。** 97 | 98 | 我们不断地展开,并定位到了 encryptRouter,如下图所示: 99 | 100 | ![](./assets/1.2.1.png) 101 | 102 | **可以看出**:我们定位到了 encryptRouter 这个路由,并且这个路由中 exports.pbkdf2Sync 占据了绝大部分 CPU 时间。 103 | 104 | ## 2. 火焰图 105 | 106 | 我们也可以用火焰图来展示 cpuprofile 数据。首先全局安装 flamegraph 这个模块: 107 | 108 | ```sh 109 | $ npm i flamegraph -g 110 | ``` 111 | 112 | 运行以下命令将 cpuprofile 文件生成 svg 文件: 113 | 114 | ```sh 115 | $ flamegraph -t cpuprofile -f cpuprofile-xxx.cpuprofile -o cpuprofile.svg 116 | ``` 117 | 118 | 浏览器打开 cpuprofile.svg,如下所示: 119 | 120 | ![](./assets/1.2.2.png) 121 | 122 | **可以看出**:我们定位到了 app.js 第 8 行,即 encryptRouter 这个路由,并且这个路由中 exports.pbkdf2Sync 占据了绝大部分 CPU 时间。 123 | 124 | ## 3. v8-analytics 125 | 126 | [v8-analytics](https://github.com/hyj1991/v8-analytics) 是社区开源的一个解析 v8-profiler 和 heapdump 等模块生成的 CPU & heap-memory 日志的工具。提供以下功能: 127 | 128 | - V8 引擎逆优化或者优化失败的函数标红展示以及优化失败原因展示 129 | - 函数执行时长超过预期标红展示 130 | - 当前项目中可疑的内存泄漏点展示 131 | 132 | 我们以上述第二条功能为例,使用 v8-analytics 分析 CPU 使用情况。 133 | 134 | 首先,全局安装 v8-analytics: 135 | 136 | ```sh 137 | $ npm i v8-analytics -g 138 | ``` 139 | 140 | 使用以下命令只查看执行时间大于 200ms 的函数: 141 | 142 | ```sh 143 | $ va timeout cpuprofile-xxx.cpuprofile 200 --only 144 | ``` 145 | 146 | 截图如下: 147 | 148 | ![](./assets/1.2.3.png) 149 | 150 | **可以看出**:我们依然能够定位到 encryptRouter 和 exports.pbkdf2Sync。 151 | 152 | ## 参考链接 153 | 154 | - https://developers.google.com/web/tools/chrome-devtools/rendering-tools/js-execution 155 | - http://www.ebaytechblog.com/2016/06/15/igniting-node-js-flames/ 156 | - https://cnodejs.org/topic/58b562f97872ea0864fee1a7 157 | - https://github.com/hyj1991/v8-analytics/blob/master/README_ZH.md 158 | 159 | 上一节:[1.1 perf + FlameGraph](https://github.com/nswbmw/node-in-debugging/blob/master/1.1%20perf%20%2B%20FlameGraph.md) 160 | 161 | 下一节:[2.1 gcore + llnode](https://github.com/nswbmw/node-in-debugging/blob/master/2.1%20gcore%20%2B%20llnode.md) 162 | -------------------------------------------------------------------------------- /3.3 Node@8.md: -------------------------------------------------------------------------------- 1 | 如果你想以最简单的方式提升 node 程序的性能,那就升级到 node@8 吧。这不是一个玩笑,多少 js 前辈们前仆后继以血的教训总结出了一长列『Optimization killers』,口耳相传,典型的比如: 2 | 3 | 1. try 里面不要写过多代码,V8 无法优化,最好将这些代码放到一个函数里,然后 try 这个函数 4 | 2. 少用 delete 5 | 3. 少用 arguments 6 | 4. ... 7 | 8 | 然而随着 V8 彻底换上了新的 JIT 编译器—— Turbofan,大多数『Optimization killers』都已经成了过去式。所以在这一小节,我们来扒一扒哪些过去常见的『Optimization killers』已经可以被 V8 优化。 9 | 10 | ## Turbofan + Ignition 11 | 12 | 之前 V8 使用的是名为 Crankshaft 的编译器,这个编译器后来逐渐暴露出一些缺点: 13 | 14 | 1. Doesn’t scale to full, modern JavaScript (try-catch, for-of, generators, async/await, …) 15 | 2. Defaults to deoptimization (performance cliffs, deoptimization loops) 16 | 3. Graph construction, inlining and optimization all mixed up 17 | 4. Tight coupling to fullcodegen / brittle environment tracking 18 | 5. Limited optimization potential / limited static analysis (i.e. type propagation) 19 | 6. High porting overhead 20 | 7. Mixed low-level and high-level semantics of instructions 21 | 22 | 而引入 Turbofan 的好处是: 23 | 24 | 1. Full ESnext language support (try-catch/-finally, class literals, eval, generators, async functions, modules, destructuring, etc.) 25 | 2. Utilize and propagate (static) type information 26 | 3. Separate graph building from optimization / inlining 27 | 4. No deoptimization loops / deoptimization only when really beneficial 28 | 5. Sane environment tracking (also for lazy deoptimization) 29 | 6. Predictable peak performance 30 | 31 | Ignition 是 V8 新引入的解释器,用来将代码编译成简洁的字节码,而不是之前的机器码,大大减少了结果代码,减少系统的内存使用。由于字节码较小,所以可以编译全部源代码,而不用避免编译未使用的代码。也就是说,脚本只需要解析一次,而不是像之前的编译过程那样解析多次。 32 | 33 | 补充一点,之前的 V8 将代码编译成机器码执行,而新的 V8 将代码编译成字节码解释执行,动机是什么呢?可能是: 34 | 35 | 1. 减轻机器码占用的内存空间,即牺牲时间换空间(主要动机) 36 | 2. 提高代码的启动速度 37 | 3. 对 V8 的代码进行重构,降低 V8 的代码复杂度 38 | 39 | ## 版本对应关系 40 | 41 | ``` 42 | node@6 -> V8@5.1 -> Crankshaft 43 | node@8.0-8.2 -> V8@5.8 -> Crankshaft + Turbofan 44 | V8@5.9 -> Turbofan 45 | node@8.3-8.4 -> V8@6.0 -> Turbofan 46 | ``` 47 | 48 | ## try/catch 49 | 50 | 最著名的去优化之一是使用 『try/catch』代码块。下面用四种场景比较不同 V8 版本下执行的效率: 51 | 52 | 1. a function with a try/catch in it (sum with try catch) 53 | 2. a function without any try/catch (sum without try catch) 54 | 3. calling a function within a try block (sum wrapped) 55 | 4. simply calling a function, no try/catch involved (sum function) 56 | 57 | 代码地址:[https://github.com/davidmarkclements/v8-perf/blob/master/bench/try-catch.js](https://github.com/davidmarkclements/v8-perf/blob/master/bench/try-catch.js) 58 | 59 | ![](./assets/3.3.1.jpg) 60 | 61 | **结论**:node@8.3+,在 try 块内写代码的性能损耗可以忽略不计。 62 | 63 | ## delete 64 | 65 | 多年以来,delete 对于任何希望编写高性能 JavaScript 的人来说都是受限制的,我们通常用赋值 undefined 替代。delete 的问题归结为 V8 处理 JavaScript 对象的动态特性和原型链方式,使得属性查找在实现上变得复杂。下面用三种场景比较不同 V8 版本下执行的效率: 66 | 67 | 1. serializing an object after an object’s property has been set to undefined 68 | 2. serializing an object after delete has been used to remove an object’s property which was not the last property added. 69 | 3. serializing an object after delete has been used to remove the object’s most recently added property. 70 | 71 | 代码地址:[https://github.com/davidmarkclements/v8-perf/blob/master/bench/property-removal.js](https://github.com/davidmarkclements/v8-perf/blob/master/bench/property-removal.js) 72 | 73 | ![](./assets/3.3.2.jpg) 74 | 75 | **结论**:在 node@8+ 中 delete 一个对象上的属性比 node@6 快了一倍,node@8.3+ delete 一个对象上最后一个属性几乎与赋值 undefined 同样快了。 76 | 77 | ## arguments 78 | 79 | 我们知道 arguments 是个类数组,所以通常我们要使用 `Array.prototype.slice.call(arguments)` 将它转化成数组再使用,这样会有一定的性能损耗。下面用四种场景比较不同 V8 版本下执行的效率: 80 | 81 | 1. Exposing the arguments object to another function - no array conversion (leaky arguments) 82 | 2. Making a copy of the arguments object using the Array.prototype.slice tricks (Array prototype.slice arguments) 83 | 3. Using a for loop and copying each property across (for-loop copy arguments) 84 | 4. Using the EcmaScript 2015 spread operator to assign an array of inputs to a reference (spread operator) 85 | 86 | 代码地址:[https://github.com/davidmarkclements/v8-perf/blob/master/bench/arguments.js](https://github.com/davidmarkclements/v8-perf/blob/master/bench/arguments.js) 87 | 88 | ![](./assets/3.3.3.jpg) 89 | 90 | **结论**:node@8.3+ 使用对象展开运算符是除了直接使用 arguments 最快的方案,对于 node@8.2- 版本,我们应该使用一个 for 循环将 key 从 arguments 复制到一个新的(预先分配的)数组中。总之,是时候抛弃 Array.prototype.slice.call 了。 91 | 92 | ## async 93 | 94 | V8@5.7 发布后,原生的 async 函数跟 Promise 一样快了,同时 Promise 性能相比 V8@5.6 也快了一倍。如图: 95 | 96 | ![](./assets/3.3.4.jpg) 97 | 98 | ## 不会优化的特性 99 | 100 | 并不是说上了 Turbofan 就能优化所有的 JavaScript 语法,有些语法 V8 也是不会去优化的(也没有必要),如: 101 | 102 | 1. debugger 103 | 2. eval 104 | 3. with 105 | 106 | 拿 debugger 为例,比较使用和不使用 debugger 时的性能。 107 | 108 | 代码地址:[https://github.com/davidmarkclements/v8-perf/blob/master/bench/debugger.js](https://github.com/davidmarkclements/v8-perf/blob/master/bench/debugger.js) 109 | 110 | ![](./assets/3.3.5.jpg) 111 | 112 | **结论**:在所有测试的 V8 版本中,debugger 一直都很慢,所以记得打断点测试完后一定要删掉 debugger。 113 | 114 | ## 总结 115 | 116 | 1. 使用最新 LTS 版本的 Node.js 117 | 2. 关注 V8 团队的博客——[https://v8project.blogspot.com](https://v8project.blogspot.com/),了解第一手资讯 118 | 3. 清晰的代码远比使用一些奇技淫巧提升一点性能重要得多 119 | 120 | ## 参考链接 121 | 122 | - http://www.infoq.com/cn/news/2016/08/v8-ignition-javascript-inteprete 123 | - 124 | - [https://www.nearform.com/blog/node-js-is-getting-a-new-v8-with-turbofan/](https://www.nearform.com/blog/node-js-is-getting-a-new-v8-with-turbofan/) 125 | - [https://zhuanlan.zhihu.com/p/26669846](https://zhuanlan.zhihu.com/p/26669846) 126 | 127 | 上一节:[3.2 Error Stack](https://github.com/nswbmw/node-in-debugging/blob/master/3.2%20Error%20Stack.md) 128 | 129 | 下一节:[3.4 Rust Addons](https://github.com/nswbmw/node-in-debugging/blob/master/3.4%20Rust%20Addons.md) 130 | -------------------------------------------------------------------------------- /6.4 OpenTracing + Jaeger.md: -------------------------------------------------------------------------------- 1 | ## 什么是 OpenTracing ? 2 | 3 | OpenTracing([opentracing.io](http://opentracing.io/))是一个分布式追踪规范。OpenTracing 通过提供平台无关、厂商无关的 API,为分布式追踪提供统一的概念和数据标准,使得开发人员能够方便的添加(或更换)追踪系统的实现。OpenTracing 定义了几个术语: 4 | 5 | - Span:代表了系统中的一个逻辑工作单元,它具有操作名、操作开始时间以及持续时长。Span 可能会有嵌套或排序,从而对因果关系建模。 6 | - Tags:每个 Span 可以有多个键值对(key: value)形式的 Tags,Tags 是没有时间戳的,支持简单的对 Span 进行注解和补充。 7 | - Logs:每个 Span 可以进行多次 Log 操作,每一次 Log 操作,都需要一个带时间戳的时间名称,以及可选的任意大小的存储结构。 8 | - Trace:代表了系统中的一个数据/执行路径(一个或多个 Span),可以理解成 Span 的有向无环图。 9 | 10 | OpenTracing 还有其他一些概念,这里不过多解释。我们看个传统的调用关系例子: 11 | 12 | ![](./assets/6.4.1.jpg) 13 | 14 | > 在一个分布式系统中,追踪一个事务或者调用流一般如上图所示。虽然这种图对于看清各组件的组合关系是很有用的,但是,它不能很好显示组件的调用时间,是串行调用还是并行调用,如果展现更复杂的调用关系,会更加复杂,甚至无法画出这样的图。另外,这种图也无法显示调用间的时间间隔以及是否通过定时调用来启动调用。一种更有效的展现一个典型的 trace 过程,如下图所示: 15 | 16 | ![](./assets/6.4.2.jpg) 17 | 18 | > 这种展现方式增加显示了执行时间的上下文,相关服务间的层次关系,进程或者任务的串行或并行调用关系。这样的视图有助于发现系统调用的关键路径。通过关注关键路径的执行过程,项目团队可能专注于优化路径中的关键位置,最大幅度的提升系统性能。例如:可以通过追踪一个资源定位的调用情况,明确底层的调用情况,发现哪些操作有阻塞的情况。 19 | 20 | ## 什么是 Jaeger ? 21 | 22 | Jaeger 是 OpenTracing 的一个实现,是 Uber 开源的一个分布式追踪系统,其灵感来源于Dapper 和 OpenZipkin。从 2016 年开始,该系统已经在 Uber 内部得到了广泛的应用,它可以用于微服务架构应用的监控,特性包括分布式上下文传播(Distributed context propagation)、分布式事务监控、根原因分析、服务依赖分析以及性能/延迟优化。该项目已经被云原生计算基金会(Cloud Native Computing Foundation,CNCF)接纳为第 12 个项目。 23 | 24 | ## 启动 Jaeger + Jaeger UI 25 | 26 | 我们使用 Docker 启动 Jaeger + Jaeger UI(Jaeger 可视化 web 控制台),运行如下命令: 27 | 28 | ```sh 29 | $ docker run -d -p5775:5775/udp \ 30 | -p 6831:6831/udp \ 31 | -p 6832:6832/udp \ 32 | -p 5778:5778 \ 33 | -p 16686:16686 \ 34 | -p 14268:14268 \ 35 | jaegertracing/all-in-one:latest 36 | ``` 37 | 38 | 浏览器打开 localhost:16686,如下所示: 39 | 40 | ![](./assets/6.4.3.jpg) 41 | 42 | 现在并没有任何数据,接下来我们看看如何使用 Jaeger 接收并查询日志。 43 | 44 | ## 如何使用 OpenTracing + Jaeger ? 45 | 46 | OpenTracing 和 Jaeger 分别提供了 JavaScript/Node.js 的 SDK: 47 | 48 | - [opentracing/opentracing-javascript](https://github.com/opentracing/opentracing-javascript) 49 | - [jaegertracing/jaeger-client-node](https://github.com/jaegertracing/jaeger-client-node) 50 | 51 | opentracing 示例代码如下: 52 | 53 | ```js 54 | const http = require('http') 55 | const opentracing = require('opentracing') 56 | 57 | // NOTE: the default OpenTracing tracer does not record any tracing information. 58 | // Replace this line with the tracer implementation of your choice. 59 | const tracer = new opentracing.Tracer() 60 | 61 | const span = tracer.startSpan('http_request') 62 | const opts = { 63 | host : 'example.com', 64 | method: 'GET', 65 | port : '80', 66 | path: '/', 67 | } 68 | http.request(opts, res => { 69 | res.setEncoding('utf8') 70 | res.on('error', err => { 71 | // assuming no retries, mark the span as failed 72 | span.setTag(opentracing.Tags.ERROR, true) 73 | span.log({'event': 'error', 'error.object': err, 'message': err.message, 'stack': err.stack}) 74 | span.finish() 75 | }) 76 | res.on('data', chunk => { 77 | span.log({'event': 'data_received', 'chunk_length': chunk.length}) 78 | }) 79 | res.on('end', () => { 80 | span.log({'event': 'request_end'}) 81 | span.finish() 82 | }) 83 | }).end() 84 | ``` 85 | 86 | 有 2 点需要解释下: 87 | 88 | 1. 需要将上面的 `const tracer = new opentracing.Tracer()` 替换成自己的 tracer 实现,即 jaeger 的实现。 89 | 2. 通过 tracer.startSpan 启动一个 Span,span.setTag 设置 Tags,span.log 设置 Logs,span.finish 结束一个 Span。 90 | 91 | 有点类似于我们的手动埋点,只不过变成了一个规范而已。但 OpenTracing 不止如此,上面只是一个 Span 的用法,Span 之间还可以关联调用关系,最后得到一个 DAG(有向无环图)。 92 | 93 | **举个例子**:假如你正在搞微服务,多个服务之间有调用关系(不管是 HTTP 还是 RPC 等),每次调用服务内部可能产生多个 Span,最终会在 Jaeger 控制台页面看到一个完整的 Trace 和 DAG 图(微服务之间的调用关系)。 94 | 95 | jaeger-client-node 使用如下: 96 | 97 | ```js 98 | const tracer = new jaeger.Tracer( 99 | serviceName, 100 | new jaeger.RemoteReporter(new UDPSender()), 101 | new jaeger.RateLimitingSampler(1) 102 | ) 103 | ``` 104 | 105 | 创建一个 tracer 接收 3 个参数: 106 | 107 | 1. serviceName:服务名 108 | 2. Reporter:上报器,即往哪发日志,如上例是通过 UDP 发送日志,默认地址 localhost:6832 109 | 3. Sampler:采样器,即日志如何采样,如上例是限制 1 秒采样一次 110 | 111 | 更多选项这里不再详细介绍,读者可自行去查阅 jaeger-client-node 的文档。 112 | 113 | ## koa-await-breakpoint-jaeger 114 | 115 | 通过上面例子我们知道,使用 Jaeger 需要手动埋点,前面我们介绍了 koa-await-breakpoint 日志自动打点,可自定义 store,koa-await-breakpoint-jaeger 是为 koa-await-breakpoint 写的 store 的 adaptor,实现上有一些小技巧,这里也不过多讲解,有兴趣的可以去看下源码。 116 | 117 | 还是拿 koa-await-breakpoint 的 example 举例,只添加了 2 行代码引入 jaeger 的使用。代码如下: 118 | 119 | **app.js** 120 | 121 | ```js 122 | const JaegerStore = require('koa-await-breakpoint-jaeger') 123 | const koaAwaitBreakpoint = require('koa-await-breakpoint')({ 124 | name: 'api', 125 | files: ['./routes/*.js'], 126 | store: new JaegerStore() 127 | }) 128 | 129 | const Paloma = require('paloma') 130 | const app = new Paloma() 131 | 132 | app.use(koaAwaitBreakpoint) 133 | app.route({ method: 'POST', path: '/users', controller: require('./routes/user').createUser }) 134 | 135 | app.listen(3000) 136 | ``` 137 | 138 | 运行: 139 | 140 | ```sh 141 | $ curl -XPOST localhost:3000/users 142 | ``` 143 | 144 | 刷新 localhost:16686 可以看到已经有日志了,如下所示: 145 | 146 | ![](./assets/6.4.4.jpg) 147 | 148 | 选择 Sercice -> api,Operation -> POST /users,点击 Find Traces 查看所有结果,右侧展示了一条日志,点进去如下所示: 149 | 150 | ![](./assets/6.4.5.jpg) 151 | 152 | **Tips:**可以根据 tags 过滤结果。 153 | 154 | **注意:**Jaeger 是分布式追踪系统,通常用来追踪多个服务之间的调用关系,而这里用来追踪一个服务多个函数之间的调用关系。 155 | 156 | 修改 routes/user.js 的 createComment 函数 throw 一个 `new Error('test')`,重新运行,如下所示: 157 | 158 | ![](./assets/6.4.6.jpg) 159 | 160 | 完美的展现了一个请求到来时,函数之间的调用关系和层级关系以及耗时,甚至函数体和错误栈都有!也可以通过 requestId 去 ELK 查询日志。 161 | 162 | ## 参考文献 163 | 164 | - https://wu-sheng.gitbooks.io/opentracing-io/content/ 165 | - https://segmentfault.com/a/1190000008895129 166 | - http://www.infoq.com/cn/news/2017/11/Uber-open-spurce-Jaeger 167 | 168 | 上一节:[6.3 ELK](https://github.com/nswbmw/node-in-debugging/blob/master/6.3%20ELK.md) 169 | 170 | 下一节:[6.5 Sentry](https://github.com/nswbmw/node-in-debugging/blob/master/6.5%20Sentry.md) 171 | -------------------------------------------------------------------------------- /2.3 memwatch-next.md: -------------------------------------------------------------------------------- 1 | [memwatch-next](https://github.com/marcominetti/node-memwatch) 是一个用来监测 Node.js 的内存泄漏和堆信息比较的模块,以下简称 memwatch。 2 | 3 | 下面我们以一段事件监听器导致内存泄漏的代码为例,讲解如何使用 memwatch。 4 | 5 | 测试代码: 6 | 7 | **app.js** 8 | 9 | ```js 10 | let count = 1 11 | const memwatch = require('memwatch-next') 12 | memwatch.on('stats', (stats) => { 13 | console.log(count++, stats) 14 | }) 15 | memwatch.on('leak', (info) => { 16 | console.log('---') 17 | console.log(info) 18 | console.log('---') 19 | }) 20 | 21 | const http = require('http') 22 | const server = http.createServer((req, res) => { 23 | for (let i = 0; i < 10000; i++) { 24 | server.on('request', function leakEventCallback() {}) 25 | } 26 | res.end('Hello World') 27 | global.gc() 28 | }).listen(3000) 29 | ``` 30 | 31 | 每一个请求到来时,给 server 注册 10000 个 request 事件的监听函数(大量的事件监听函数存储到内存中,造成了内存泄漏),然后手动触发一次 GC。 32 | 33 | 运行该程序: 34 | 35 | ```sh 36 | $ node --expose-gc app.js 37 | ``` 38 | 39 | **注意:**这里添加 --expose-gc 参数启动,这样我们才可以在程序中手动触发 GC。 40 | 41 | memwatch 可以监听两个事件: 42 | 43 | 1. stats:GC 事件,每执行一次 GC,触发该函数,打印 heap 相关信息。如下: 44 | 45 | ```js 46 | { 47 | num_full_gc: 1,// 完整的垃圾回收次数 48 | num_inc_gc: 1,// 增长的垃圾回收次数 49 | heap_compactions: 1,// 内存压缩次数 50 | usage_trend: 0,// 使用趋势 51 | estimated_base: 5350136,// 预期基数 52 | current_base: 5350136,// 当前基数 53 | min: 0,// 最小值 54 | max: 0// 最大值 55 | } 56 | ``` 57 | 58 | 2. leak:内存泄露事件,触发该事件的条件是:连续 5 次 GC 后内存都是增长的。打印如下: 59 | 60 | ```js 61 | { 62 | growth: 4051464, 63 | reason: 'heap growth over 5 consecutive GCs (2s) - -2147483648 bytes/hr' 64 | } 65 | ``` 66 | 67 | 运行: 68 | 69 | ```sh 70 | $ ab -c 1 -n 5 http://localhost:3000/ 71 | ``` 72 | 73 | 输出: 74 | 75 | ```js 76 | (node:20989) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 request listeners added. Use emitter.setMaxListeners() to increase limit 77 | 1 { num_full_gc: 1, 78 | num_inc_gc: 1, 79 | heap_compactions: 1, 80 | usage_trend: 0, 81 | estimated_base: 5720064, 82 | current_base: 5720064, 83 | min: 0, 84 | max: 0 } 85 | 2 { num_full_gc: 2, 86 | num_inc_gc: 1, 87 | heap_compactions: 2, 88 | usage_trend: 0, 89 | estimated_base: 7073824, 90 | current_base: 7073824, 91 | min: 0, 92 | max: 0 } 93 | 3 { num_full_gc: 3, 94 | num_inc_gc: 1, 95 | heap_compactions: 3, 96 | usage_trend: 0, 97 | estimated_base: 7826368, 98 | current_base: 7826368, 99 | min: 7826368, 100 | max: 7826368 } 101 | 4 { num_full_gc: 4, 102 | num_inc_gc: 1, 103 | heap_compactions: 4, 104 | usage_trend: 0, 105 | estimated_base: 8964784, 106 | current_base: 8964784, 107 | min: 7826368, 108 | max: 8964784 } 109 | --- 110 | { growth: 3820272, 111 | reason: 'heap growth over 5 consecutive GCs (0s) - -2147483648 bytes/hr' } 112 | --- 113 | 5 { num_full_gc: 5, 114 | num_inc_gc: 1, 115 | heap_compactions: 5, 116 | usage_trend: 0, 117 | estimated_base: 9540336, 118 | current_base: 9540336, 119 | min: 7826368, 120 | max: 9540336 } 121 | ``` 122 | 123 | **可以看出**:Node.js 已经警告我们事件监听器超过了 11 个,可能造成内存泄露。连续 5 次内存增长触发 leak 事件打印出增长了多少内存(bytes)和预估每小时增长多少 bytes。 124 | 125 | ### Heap Diffing 126 | 127 | memwatch 有一个 HeapDiff 函数,用来对比并计算出两次堆快照的差异。修改测试代码如下: 128 | 129 | ```js 130 | const memwatch = require('memwatch-next') 131 | const http = require('http') 132 | const server = http.createServer((req, res) => { 133 | for (let i = 0; i < 10000; i++) { 134 | server.on('request', function leakEventCallback() {}) 135 | } 136 | res.end('Hello World') 137 | global.gc() 138 | }).listen(3000) 139 | 140 | const hd = new memwatch.HeapDiff() 141 | memwatch.on('leak', (info) => { 142 | const diff = hd.end() 143 | console.dir(diff, { depth: 10 }) 144 | }) 145 | ``` 146 | 147 | 运行这段代码并执行同样的 ab 命令,打印如下: 148 | 149 | ```js 150 | { before: { nodes: 35727, size_bytes: 4725128, size: '4.51 mb' }, 151 | after: { nodes: 87329, size_bytes: 8929792, size: '8.52 mb' }, 152 | change: 153 | { size_bytes: 4204664, 154 | size: '4.01 mb', 155 | freed_nodes: 862, 156 | allocated_nodes: 52464, 157 | details: 158 | [ ... 159 | { what: 'Array', 160 | size_bytes: 530200, 161 | size: '517.77 kb', 162 | '+': 1023, 163 | '-': 510 }, 164 | { what: 'Closure', 165 | size_bytes: 3599856, 166 | size: '3.43 mb', 167 | '+': 50001, 168 | '-': 3 }, 169 | ... 170 | ] 171 | } 172 | } 173 | ``` 174 | 175 | **可以看出**:内存由 4.51mb 涨到了 8.52mb,其中 Closure 和 Array 涨了绝大部分,而我们知道注册事件监听函数的本质就是将事件函数(Closure)push 到相应的数组(Array)里。 176 | 177 | ## HeapDump 178 | 179 | memwatch 结合 heapdump 使用才能发挥更好的作用。通常用 memwatch 监测到发生内存泄漏,用 heapdump 导出多份堆快照,然后用 Chrome DevTools 分析比较,定位内存泄漏元凶。 180 | 181 | 修改代码如下: 182 | 183 | ```js 184 | const memwatch = require('memwatch-next') 185 | const heapdump = require('heapdump') 186 | 187 | const http = require('http') 188 | const server = http.createServer((req, res) => { 189 | for (let i = 0; i < 10000; i++) { 190 | server.on('request', function leakEventCallback() {}) 191 | } 192 | res.end('Hello World') 193 | global.gc() 194 | }).listen(3000) 195 | 196 | dump() 197 | memwatch.on('leak', () => { 198 | dump() 199 | }) 200 | 201 | function dump() { 202 | const filename = `${__dirname}/heapdump-${process.pid}-${Date.now()}.heapsnapshot` 203 | 204 | heapdump.writeSnapshot(filename, () => { 205 | console.log(`${filename} dump completed.`) 206 | }) 207 | } 208 | ``` 209 | 210 | **代码含义**:程序启动后先执行一次 heap dump,当触发 leak 事件时再执行一次 heap dump。运行这段代码并执行同样的 ab 命令,生成两个 heapsnapshot 文件: 211 | 212 | ``` 213 | heapdump-21126-1519545957879.heapsnapshot 214 | heapdump-21126-1519545975702.heapsnapshot 215 | ``` 216 | 217 | 用 Chrome DevTools 加载这两个 heapsnapshot 文件,选择 comparison 比较视图,如下所示: 218 | 219 | ![](./assets/2.3.1.png) 220 | 221 | **可以看出**:增加了 5 万个 leakEventCallback 函数,选中任意一个,可以从 Retainers 中看到更详细的信息,如 GC path 和所在的文件等信息。 222 | 223 | ## 参考链接 224 | 225 | - [https://github.com/marcominetti/node-memwatch](https://github.com/marcominetti/node-memwatch) 226 | 227 | 上一节:[2.2 heapdump](https://github.com/nswbmw/node-in-debugging/blob/master/2.2%20heapdump.md) 228 | 229 | 下一节:[2.4 cpu-memory-monitor](https://github.com/nswbmw/node-in-debugging/blob/master/2.4%20cpu-memory-monitor.md) 230 | -------------------------------------------------------------------------------- /4.4 debug + repl2 + power-assert.md: -------------------------------------------------------------------------------- 1 | 上一小节讲解了如何用使用 VS Code 调试 Node.js 代码,但调试不只是打断点,比如: 2 | 3 | - 如何快速的切换输出的日志类型(或级别)? 4 | - 我只想试一下用 moment 打印出年份是 `moment().format('YYYY')` 还是 `moment().format('yyyy')` 还是两种写法都可以? 5 | - 断言报错:AssertionError: false == true,没啥有用信息,黑人问号??? 6 | 7 | 本文将介绍给大家 3 款实用的调试工具,分别解决以上 3 种情况,提高我们的调试效率。 8 | 9 | ## debug 10 | 11 | debug 是一个小巧却非常实用的日志模块,可以根据环境变量决定打印不同类型(或级别)的日志。直接上代码: 12 | 13 | **app.js** 14 | 15 | ```js 16 | const normalLog = require('debug')('log') 17 | const errorLowLog = require('debug')('error:low') 18 | const errorNormalLog = require('debug')('error:normal') 19 | const errorHighLog = require('debug')('error:high') 20 | 21 | setInterval(() => { 22 | const value = Math.random() 23 | switch (true) { 24 | case value < 0.5: normalLog(value); break 25 | case value >= 0.5 && value < 0.7: errorLowLog(value); break 26 | case value >= 0.7 && value < 0.9: errorNormalLog(value); break 27 | case value >= 0.9: errorHighLog(value); break 28 | default: normalLog(value) 29 | } 30 | }, 1000) 31 | ``` 32 | 33 | 上面代码每一秒生成一个随机数,根据随机数的值模拟不同级别的日志输出: 34 | 35 | - < 0.5:正常日志 36 | - 0.5~0.7:低级别的错误日志 37 | - 0.7~0.9:一般级别的错误日志 38 | - \>= 0.9:严重级别的错误日志 39 | 40 | 运行: 41 | 42 | ```sh 43 | $ DEBUG=* node app.js 44 | ``` 45 | 46 | 打印如下: 47 | 48 | ![](./assets/4.4.1.jpg) 49 | 50 | 可以看出,debug 模块打印的日志相比较于 console.log,有以下几个特点: 51 | 52 | 1. 不同的日志类型分配了不同的颜色加以区分,更直观 53 | 2. 添加了日志类型的前缀 54 | 3. 添加了自上一次该类型日志打印到这次日志打印经历了多长时间的后缀 55 | 56 | debug 模块支持以下用法: 57 | 58 | - DEBUG=*:打印所有类型的日志 59 | - DEBUG=log:只打印 log 类型的日志 60 | - DEBUG=error:*:打印所有以 error: 开头的日志 61 | - DEBUG=error:*,-error:low:打印所有以 error: 开头的并且过滤掉 error:low 类型的日志 62 | 63 | 下面演示一下第 4 种的用法,运行: 64 | 65 | ```sh 66 | $ DEBUG=error:*,-error:low node app.js 67 | ``` 68 | 69 | 打印如下: 70 | 71 | ![](./assets/4.4.2.jpg) 72 | 73 | ## repl2 74 | 75 | 我们在写代码的时候,有时候记不太清某个模块某个方法的具体用法,比如:moment 打印出年份是 `moment().format('YYYY')` 还是 `moment().format('yyyy')` 还是两种写法都可以?lodash 的 `_.pick` 方法能否能接收数组作为参数?这个时候相比较于翻阅官网网站,在 REPL 里试一下可能来得更快,通常步骤是: 76 | 77 | ```sh 78 | $ npm i moment 79 | $ node 80 | > const moment = require('moment') 81 | > moment().format('YYYY') 82 | '2017' 83 | > moment().format('yyyy') 84 | 'yyyy' 85 | ``` 86 | 87 | 一次还好,这样用次数多了也略微繁琐,repl2 模块便是为了解决这个问题而生。 88 | 89 | repl2 顾名思义是 REPL 的增强版,repl2 会根据一个用户配置(~/.noderc),预先加载模块到 REPL 中,省下了我们手动在 REPL 中 require 模块的过程。 90 | 91 | 全局安装: 92 | 93 | ```sh 94 | $ npm i repl2 -g 95 | ``` 96 | 97 | 使用方式很简单: 98 | 99 | 1. 将常用的模块全局安装,如: 100 | 101 | ```sh 102 | $ npm i lodash validator moment -g 103 | ``` 104 | 105 | 2. 添加配置到 ~/.noderc: 106 | 107 | ```json 108 | { 109 | "lodash": "__", 110 | "moment": "moment", 111 | "validator": "validator" 112 | } 113 | ``` 114 | 115 | 3. 运行 noder: 116 | 117 | ```sh 118 | $ noder 119 | __ = lodash@4.17.4 -> local 120 | moment = moment@2.18.1 -> global 121 | validator = validator@7.0.0 -> global 122 | > moment().format('YYYY') 123 | '2017' 124 | > __.random(0, 5) 125 | 3 126 | > validator.isEmail('foo@bar.com') 127 | true 128 | ``` 129 | 130 | 有几点需要讲解下: 131 | 132 | 1. ~/.noderc 是一个 JSON 文件,key 是模块名字,value 是 require 这个模块后加载到 REPL 中的变量名。这里给 lodash 命名的变量名是 __ 而不是 _,是因为 REPL 中 _ 有特殊含义,表示上一个表达式的结果 133 | 2. repl2 会优先加载当前目录下的模块,没有找到然后再去加载全局安装的模块。上面结果显示 lodash 是从本地目录加载的,因为 test 目录下已经安装了 lodash,其余的模块没有从本地目录找到则尝试从全局 npm 目录加载。如果都没有找到,则不会加载 134 | 135 | ## power-assert 136 | 137 | 我们常用的断言库有: 138 | 139 | - [should.js](https://github.com/shouldjs/should.js) 140 | - [expect.js](https://github.com/Automattic/expect.js) 141 | - [chai](https://github.com/chaijs/chai) 142 | 143 | 但这类断言库都有一些通病: 144 | 145 | 1. 过分追求语义化,API 复杂 146 | 2. 错误信息不足 147 | 148 | 看一段代码: 149 | 150 | **test.js** 151 | 152 | ```js 153 | const assert = require('assert') 154 | const should = require('should') 155 | const expect = require('expect.js') 156 | 157 | const tom = { id: 1, age: 18 } 158 | const bob = { id: 2, age: 20 } 159 | 160 | describe('app.js', () => { 161 | it('assert', () => { 162 | assert(tom.age > bob.age) 163 | }) 164 | it('should.js', () => { 165 | tom.age.should.be.above(bob.age) 166 | }) 167 | it('expect.js', () => { 168 | expect(tom.age).be.above(bob.age) 169 | }) 170 | }) 171 | ``` 172 | 173 | 运行: 174 | 175 | ```sh 176 | $ mocha 177 | ``` 178 | 179 | 结果如下: 180 | 181 | ```js 182 | app.js 183 | 1) assert 184 | 2) should.js 185 | 3) expect.js 186 | 187 | 188 | 0 passing (13ms) 189 | 3 failing 190 | 191 | 1) app.js 192 | assert: 193 | 194 | AssertionError [ERR_ASSERTION]: false == true 195 | + expected - actual 196 | 197 | -false 198 | +true 199 | 200 | at Context.it (test.js:10:5) 201 | 202 | 2) app.js 203 | should.js: 204 | AssertionError: expected 18 to be above 20 205 | at Assertion.fail (node_modules/should/cjs/should.js:275:17) 206 | at Assertion.value (node_modules/should/cjs/should.js:356:19) 207 | at Context.it (test.js:13:23) 208 | 209 | 3) app.js 210 | expect.js: 211 | Error: expected 18 to be above 20 212 | at Assertion.assert (node_modules/expect.js/index.js:96:13) 213 | at Assertion.greaterThan.Assertion.above (node_modules/expect.js/index.js:297:10) 214 | at Function.above (node_modules/expect.js/index.js:499:17) 215 | at Context.it (test.js:16:24) 216 | ``` 217 | 218 | 基本没啥有用信息。这个时候,power-assert 粉墨登场。 219 | 220 | power-assert 使用起来很简单,理论上只用一个 assert 就可以了,而且可以无缝的迁移。 221 | 222 | **注意**:使用 intelli-espower-loader 要求必须将测试文件放到 test/ 目录,所以我们在 test 目录下创建 test/app.js,将原来的 test.js 代码粘贴过去。 223 | 224 | 安装 power-assert 和 intelli-espower-loader,然后运行测试: 225 | 226 | ```sh 227 | $ npm i power-assert intelli-espower-loader --save-dev 228 | $ mocha -r intelli-espower-loader 229 | ``` 230 | 231 | 结果如下: 232 | 233 | ```js 234 | app.js 235 | 1) assert 236 | 2) should.js 237 | 3) expect.js 238 | 239 | 240 | 0 passing (42ms) 241 | 3 failing 242 | 243 | 1) app.js 244 | assert: 245 | 246 | AssertionError [ERR_ASSERTION]: # test/app.js:10 247 | 248 | assert(tom.age > bob.age) 249 | | | | | | 250 | | | | | 20 251 | | | | Object{id:2,age:20} 252 | | 18 false 253 | Object{id:1,age:18} 254 | 255 | + expected - actual 256 | 257 | -false 258 | +true 259 | ... 260 | ``` 261 | 262 | 错误信息非常直观,有两点需要说明下: 263 | 264 | 1. mocha 需要引入 intelli-espower-loader,主要是转译代码,转译之后 `require('assert')` 都不需要改 265 | 2. intelli-espower-loader 可选地在 package.json 添加 directories.test 配置,如: 266 | 267 | ```json 268 | "directories": { 269 | "test": "mytest/" 270 | } 271 | ``` 272 | 273 | 如果没有 directories.test 配置则默认是 `test/`。 274 | 275 | ## 参考链接 276 | 277 | - https://zhuanlan.zhihu.com/p/25956323 278 | - https://www.npmjs.com/package/intelli-espower-loader 279 | 280 | 上一节:[4.3 Visual Studio Code](https://github.com/nswbmw/node-in-debugging/blob/master/4.3%20Visual%20Studio%20Code.md) 281 | 282 | 下一节:[4.5 supervisor-hot-reload](https://github.com/nswbmw/node-in-debugging/blob/master/4.5%20supervisor-hot-reload.md) 283 | -------------------------------------------------------------------------------- /7.1 Telegraf + InfluxDB + Grafana(上).md: -------------------------------------------------------------------------------- 1 | 本文将会讲解如何使用 Telegraf(StatsD) + InfluxDB + Grafana 搭建一套完整的监控系统。 2 | 3 | ## 简介 4 | 5 | [Telegraf](https://github.com/influxdata/telegraf) 是一个使用 Go 语言开发的代理程序,可收集系统和服务或者其他来源(inputs)的数据,并写入到 InfluxDB(outputs)数据库,支持多种 inputs 和 outputs 插件。[StatsD](https://github.com/etsy/statsd) 是一个使用 Node.js 开发的网络守护进程,通过 UDP 或者 TCP 方式收集各种统计信息,包括计数器和定时器等。 6 | 7 | [InfluxDB](https://github.com/influxdata/influxdb) 是一个使用 Go 语言开发的开源的分布式时序、事件和指标数据库,无需外部依赖,其设计目标是实现分布式和水平伸缩扩展。 8 | 9 | [Grafana](https://github.com/grafana/grafana) 是一个使用 Go 语言开发的开源的、功能齐全的、漂亮的仪表盘和图表的编辑器,可用来做日志的分析与展示曲线图(如 api 的请求日志),支持多种 backend,如 ElasticSearch、InfluxDB、OpenTSDB 等等。 10 | 11 | **工作流程**:Telegraf 将 StatsD(inputs) 和 InfluxDB(outputs) 结合起来,即发往 StatsD 的数据,最终通过 Telegraf 写入了 InfluxDB,然后 Grafana 读取 InfluxDB 的数据展示成图表。 12 | 13 | ## 启动 docker-statsd-influxdb-grafana 14 | 15 | 我们使用 Docker 一键启动 Telegraf(StatsD) + InfluxDB + Grafana,节省搭建环境的时间。 16 | 17 | ```sh 18 | $ docker run -d \ 19 | --name docker-statsd-influxdb-grafana \ 20 | -p 3003:3003 \ 21 | -p 3004:8083 \ 22 | -p 8086:8086 \ 23 | -p 22022:22 \ 24 | -p 8125:8125/udp \ 25 | samuelebistoletti/docker-statsd-influxdb-grafana:latest 26 | ``` 27 | 28 | 端口映射关系: 29 | 30 | ``` 31 | Host Container Service 32 | ----------------------------------- 33 | 3003 3003 grafana 34 | 3004 8083 influxdb-admin 35 | 8086 8086 influxdb 36 | 8125 8125 statsd 37 | 22022 22 sshd 38 | ``` 39 | 40 | ## 熟悉 InfluxDB 41 | 42 | 容器启动后,浏览器访问 localhost:3004(以下称为 influxdb-admin),如下所示: 43 | 44 | ![](./assets/7.1.1.png) 45 | 46 | InfluxDB 基本概念: 47 | 48 | - database:数据库 49 | - measurement:数据库中的表 50 | - point:表里面的一行数据,由时间戳(time)、数据(field)和标签(tag)组成 51 | - time:每条数据记录的时间戳,是数据库中的主索引(会自动生成) 52 | - field:各种记录的值(没有索引的属性) 53 | - tag:各种有索引的属性 54 | - ... 55 | 56 | InfluxDB 采用了类 SQL 的查询语法,如: 57 | 58 | - show databases:列出所有数据库 59 | - show measurements:列出当前数据库的所有表 60 | - select * from xxx:列出 xxx 表的所有数据 61 | - ... 62 | 63 | 我们在 Query 中输入: 64 | 65 | ```sql 66 | show databases 67 | ``` 68 | 69 | 查询结果如下: 70 | 71 | ![](./assets/7.1.2.png) 72 | 73 | _interal 是 InfluxDB 内部使用的数据库,telegraf 是我们当前 docker 容器启动后默认创建的测试数据库。 74 | 75 | ## 配置 Grafana 76 | 77 | 浏览器打开 localhost:3003,如下所示: 78 | 79 | ![](./assets/7.1.3.png) 80 | 81 | 输入用户名 root 和密码 root 登录,进入初始化配置页,点击 Add data source 绿色按钮,如下填写: 82 | 83 | ![](./assets/7.1.4.png) 84 | 85 | 点击 Save & Test 保存配置。目前配置好了 Grafana 默认的 datasource 是 InfluxDB,接下来我们创建测试代码,产生测试数据。 86 | 87 | ## node-statsd 88 | 89 | [node-statsd](https://github.com/sivy/node-statsd) 是一个 statsd 的 Node.js client。创建以下测试代码: 90 | 91 | ```js 92 | const StatsD = require('node-statsd') 93 | const statsdClient = new StatsD({ 94 | host: 'localhost', 95 | port: 8125 96 | }) 97 | 98 | setInterval(() => { 99 | const responseTime = Math.floor(Math.random() * 100) 100 | statsdClient.timing('api', responseTime, function (error, bytes) { 101 | if (error) { 102 | console.error(error) 103 | } else { 104 | console.log(`Successfully sent ${bytes} bytes, responseTime ${responseTime}ms`) 105 | } 106 | }) 107 | }, 1000) 108 | ``` 109 | 110 | 运行以上代码,每一秒钟产生一个 0-99 之间的随机值(模拟响应时间,单位毫秒),发送到 StatsD,StatsD 会通过 Telegraf 将这些数据写入 InfluxDB 的 telegraf 数据库。 111 | 112 | 回到 influxdb-admin,点击右上角切换到 telegraf 数据库,然后输入 `show measurements ` 查看已经存在 api 表了,然后输入: 113 | 114 | ```sql 115 | select * from api 116 | ``` 117 | 118 | 查询结果如下: 119 | 120 | ![](./assets/7.1.5.png) 121 | 122 | 可以看出 api 表有以下几个字段: 123 | 124 | - time:InfluxDB 默认添加的时间戳 125 | - 90_percentile:所有记录中从小到大 90% 那个点的值 126 | - count:一次收集的日志数量,可以看出每条记录(point)的 count 值接近或等于 10,而我们的测试代码是 1s 发送一条数据,也就说明 Telegraf 默认设置是 10s 收集一次数据,默认配置的确是这样的,见:https://github.com/samuelebistoletti/docker-statsd-influxdb-grafana/blob/master/telegraf/telegraf.conf 127 | - host:机器地址 128 | - lower:最小的那条记录的值 129 | - mean:所有记录的平均值 130 | - metric_type:metric 类型 131 | - stddev:所有记录的标准差 132 | - upper:最大的那条记录的值 133 | 134 | ## 创建 Grafana 图表 135 | 136 | 回到 Grafana,点击左上角 Grafana 图标的下拉菜单,点击 Dashboards 回到仪表盘页继续完成配置,点击 New dashboard 绿色按钮,然后点击 Graph 类型的图表,创建了一个空的图表,如下所示: 137 | 138 | ![](./assets/7.1.6.png) 139 | 140 | 点击当前图表,选择 Edit,修改几个地方: 141 | 142 | 1. Metrics 配置中选择 FROM -> api 表,SELECT -> field(mean) 字段 143 | 2. Display 配置中 Null value 选择 connected 将每个点连成折线 144 | 145 | 如下所示: 146 | 147 | ![](./assets/7.1.7.png) 148 | 149 | ## 模拟真实环境 150 | 151 | **middlewares/statsd.js** 152 | 153 | ```js 154 | const StatsD = require('node-statsd') 155 | const statsdClient = new StatsD({ 156 | host: 'localhost', 157 | port: 8125 158 | }) 159 | 160 | module.exports = function (routerName) { 161 | return async function statsdMiddleware (ctx, next) { 162 | const start = Date.now() 163 | 164 | try { 165 | await next() 166 | const spent = Date.now() - start 167 | statsdClient.timing(`api_${routerName}`, spent) 168 | } catch (e) { 169 | statsdClient.increment(`api_${routerName}_${e.status || (ctx.status !== 404 ? ctx.status : 500)}`) 170 | throw e 171 | } 172 | } 173 | } 174 | ``` 175 | 176 | **server.js** 177 | 178 | ```js 179 | const Bluebird = require('bluebird') 180 | const Paloma = require('paloma') 181 | const app = new Paloma() 182 | const statsd = require('./middlewares/statsd') 183 | 184 | app.route({ method: 'GET', path: '/', controller: [ 185 | statsd('getHome'), 186 | async (ctx) => { 187 | // 模拟十分之一出错概率 188 | if (Math.random() < 0.1) { 189 | console.error('error') 190 | ctx.throw(400) 191 | } 192 | // 模拟 1-99 毫秒响应时间 193 | const responseTime = Math.floor(Math.random() * 100) 194 | await Bluebird.delay(responseTime) 195 | console.log(`Spent ${responseTime}ms`) 196 | ctx.status = 200 197 | } 198 | ]}) 199 | 200 | app.listen(3000) 201 | ``` 202 | 203 | **client.js** 204 | 205 | ```js 206 | const axios = require('axios') 207 | 208 | setInterval(() => { 209 | // 模拟 1-9 的 tps 210 | const tps = Math.floor(Math.random() * 10) 211 | for (let i = 0; i < tps; i++) { 212 | axios.get('http://localhost:3000') 213 | } 214 | }, 1000) 215 | ``` 216 | 217 | 起两个终端,分别运行: 218 | 219 | ```sh 220 | $ node server.js 221 | $ node client.js 222 | ``` 223 | 224 | 回到 influxdb-admin,输入: 225 | 226 | ```sql 227 | show measurements 228 | ``` 229 | 230 | 可以看到已经有 api_getHome 和 api_getHome_400 表了。回到 Grafana,在一行(row)创建两个图表,分别为: 231 | 232 | - 请求量:包含了正常请求(200)和错误请求(4xx、5xx 等等)tps 的折线图 233 | - 响应时间:正常请求的最低(lower)、平均(mean)、最高(upper)响应时间的折线图 234 | 235 | ![](./assets/7.1.8.png) 236 | 237 | 以『getHome 响应时间』的图表为例,Metrics 配置截图如下: 238 | 239 | ![](./assets/7.1.9.png) 240 | 241 | ## 参考链接 242 | 243 | - https://www.cnblogs.com/shhnwangjian/p/6897216.html 244 | 245 | 上一节:[6.5 Sentry](https://github.com/nswbmw/node-in-debugging/blob/master/6.5%20Sentry.md) 246 | 247 | 下一节:[7.2 Telegraf + InfluxDB + Grafana(下)](https://github.com/nswbmw/node-in-debugging/blob/master/7.2%20Telegraf%20%2B%20InfluxDB%20%2B%20Grafana(%E4%B8%8B).md) 248 | -------------------------------------------------------------------------------- /3.1 Async + Await.md: -------------------------------------------------------------------------------- 1 | 笔者很长一段时间都使用 koa@1 +(generator|bluebird)+ sequelize 这个组合,这个组合并没有什么问题,也很常见,但是到了滥用的地步,导致后来维护和调试都很痛苦。排除掉 sequelize 这个不得不用的模块,从调试 cpuprofile 角度讲讲为什么我认为应该用 async/await + Promise 替代 co + generator|bluebird。 2 | 3 | 我的观点是:**使用原生模块具有更清晰的调用栈**。 4 | 5 | 下面用 4 个例子对比,看下相同逻辑不同代码生成的 cpuprofile 中调用栈的信息。 6 | 7 | **async.js** 8 | 9 | ```js 10 | const fs = require('fs') 11 | const profiler = require('v8-profiler') 12 | 13 | async function A () { 14 | return await Promise.resolve('A') 15 | } 16 | 17 | async function B () { 18 | return await A() 19 | } 20 | 21 | (async function asyncWrap () { 22 | const start = Date.now() 23 | profiler.startProfiling() 24 | while (Date.now() - start < 10000) { 25 | await B() 26 | } 27 | const profile = profiler.stopProfiling() 28 | profile.export() 29 | .pipe(fs.createWriteStream('async.cpuprofile')) 30 | .on('finish', () => { 31 | profile.delete() 32 | console.error('async.cpuprofile export success') 33 | }) 34 | })() 35 | ``` 36 | 37 | 加载运行后生成的 async.cpuprofile,如下所示: 38 | 39 | ![](./assets/3.1.1.png) 40 | 41 | **可以看出**:asyncWrap 中调用了 B 函数,B 函数调用了 A 函数,A 函数中 resolve 了一个值。asyncWrap 中还调用了 stopProfiling 函数。 42 | 43 | **co.js** 44 | 45 | ```js 46 | const fs = require('fs') 47 | const co = require('co') 48 | const profiler = require('v8-profiler') 49 | 50 | function * A () { 51 | return yield Promise.resolve('A') 52 | } 53 | 54 | function * B () { 55 | return yield A() 56 | } 57 | 58 | co(function * coWrap () { 59 | const start = Date.now() 60 | profiler.startProfiling() 61 | while (Date.now() - start < 10000) { 62 | yield B() 63 | } 64 | const profile = profiler.stopProfiling() 65 | profile.export() 66 | .pipe(fs.createWriteStream('co.cpuprofile')) 67 | .on('finish', () => { 68 | profile.delete() 69 | console.error('co.cpuprofile export success') 70 | }) 71 | }) 72 | ``` 73 | 74 | 加载运行后生成的 co.cpuprofile,如下所示: 75 | 76 | ![](./assets/3.1.2.png) 77 | 78 | **可以看出**:调用栈非常深,太多没有用的 co 相关的调用栈。如果 n 个 generator 层层嵌套,就会出现 n 倍的 (anonymous)->onFullfiled->next->toPromise->co->Promise->(anonymous) 调用栈。如果你读过 co 的源码可能知道,这是 co 将 generator 解包的过程。其实这个可以将 `yield generator` 替换成 `yield* generator` 来优化。 79 | 80 | **co_better.js** 81 | 82 | ```js 83 | const fs = require('fs') 84 | const co = require('co') 85 | const profiler = require('v8-profiler') 86 | 87 | function * A () { 88 | return yield Promise.resolve('A') 89 | } 90 | 91 | function * B () { 92 | return yield * A() 93 | } 94 | 95 | co(function * coWrap () { 96 | const start = Date.now() 97 | profiler.startProfiling() 98 | while (Date.now() - start < 10000) { 99 | yield * B() 100 | } 101 | const profile = profiler.stopProfiling() 102 | profile.export() 103 | .pipe(fs.createWriteStream('co_better.cpuprofile')) 104 | .on('finish', () => { 105 | profile.delete() 106 | console.error('co_better.cpuprofile export success') 107 | }) 108 | }) 109 | ``` 110 | 111 | 加载运行后生成的 co_better.cpuprofile,如下所示: 112 | 113 | ![](./assets/3.1.3.png) 114 | 115 | **可以看出**:相比 co.js 调用栈就清晰了很多,不过相比用 async/await 还是多了些 onFulfilled、next。 116 | 117 | **co_bluebird.js** 118 | 119 | ```js 120 | const fs = require('fs') 121 | const co = require('co') 122 | const Promise = require('bluebird') 123 | const profiler = require('v8-profiler') 124 | 125 | function * A () { 126 | return yield Promise.resolve('A') 127 | } 128 | 129 | function * B () { 130 | return yield * A() 131 | } 132 | 133 | co(function * coBluebirdWrap () { 134 | const start = Date.now() 135 | profiler.startProfiling() 136 | while (Date.now() - start < 10000) { 137 | yield * B() 138 | } 139 | const profile = profiler.stopProfiling() 140 | profile.export() 141 | .pipe(fs.createWriteStream('co_bluebird.cpuprofile')) 142 | .on('finish', () => { 143 | profile.delete() 144 | console.error('co_bluebird.cpuprofile export success') 145 | }) 146 | }) 147 | ``` 148 | 149 | 加载运行后生成的 co_bluebird.cpuprofile,如下所示: 150 | 151 | ![](./assets/3.1.4.png) 152 | 153 | **可以看出**:相比较 co_better.js,调用栈中多了许多 bluebird 模块的无用信息。而且这只是非常简单的示例代码,要是复杂的业务逻辑大量使用 Bluebird 代码生成的 cpuprofile,几乎没法看了。 154 | 155 | **结论**:使用 async/await + Promise + 命名函数,具有更清晰的调用栈,让分析 cpuprofile 时不再痛苦。 156 | 157 | 聪明的你可能会问: 158 | 159 | 1. 为什么不建议用 bluebird?原因是: 160 | 1. 随着 V8 不断优化,原生 Promise 性能逐渐提高,bluebird 性能优势不明显 161 | 2. 原生 Promise 的 API 足够用,至少能 cover 大部分使用场景,而且还在不断完善,未来还会添加新的 api,如:Promise.prototype.finally。 162 | 3. 具有更清晰的调用栈 163 | 2. 由于历史遗留原因,现在代码中大量使用了 yield + generator 怎么办? 164 | 1. 将所有 yield generator 替换成 yield * generator 165 | 2. 升级到 node@^8,逐步用 async/await 替换,毕竟 async 函数调用后返回的也是一个 promise 嘛,也是 yieldable 的 166 | 3. 性能比较呢?node@8+ 下 async/await 完胜 co,见参考链接 167 | 168 | ## yield -> yield* 的坑 169 | 170 | 上面讲到可以将 yield generator -> yield * generator,这里面有一个坑,是由于不明白 co 的原理滥用 co 导致的。代码如下: 171 | 172 | ```js 173 | const co = require('co') 174 | 175 | function * genFunc () { 176 | return Promise.resolve('genFunc') 177 | } 178 | 179 | co(function * () { 180 | console.log(yield genFunc()) // => genFunc 181 | console.log(yield * genFunc()) // => Promise { 'genFunc' } 182 | }) 183 | ``` 184 | 185 | **可以看出**:一个 generatorFunction 执行后返回一个 promise,当使用 yield 的时候,co 判断返回了一个 promise 会继续帮我们调用它的 then 得到真正的字符串。如果使用 yield *,即用了语言原生的特性而不经过 co,直接返回一个 promise。 186 | 187 | **解决方法(任选其一)**: 188 | 189 | 1. `function * genFunc` -> `function genFunc`,用 `yield genFunc()` 190 | 2. `return Promise.resolve('genFunc')` ->` return yield Promise.resolve('genFunc')`,用 `yield* genFunc()` 191 | 192 | 不过,建议最终转换到 async/await + Promise 上来,毕竟 co + generator 只是一个过渡产物。 193 | 194 | ## Async + Bluebird 195 | 196 | 如果是使用 async/await + bluebird 的情况呢? 197 | 198 | **async_bluebird.js** 199 | 200 | ```js 201 | const fs = require('fs') 202 | const profiler = require('v8-profiler') 203 | const Promise = require('bluebird') 204 | 205 | async function A () { 206 | return await Promise.resolve('A') 207 | } 208 | 209 | async function B () { 210 | return await A() 211 | } 212 | 213 | (async function asyncBluebirdWrap () { 214 | const start = Date.now() 215 | profiler.startProfiling() 216 | while (Date.now() - start < 10000) { 217 | await B() 218 | } 219 | const profile = profiler.stopProfiling() 220 | profile.export() 221 | .pipe(fs.createWriteStream('async_bluebird.cpuprofile')) 222 | .on('finish', () => { 223 | profile.delete() 224 | console.error('async_bluebird.cpuprofile export success') 225 | }) 226 | })() 227 | ``` 228 | 229 | **结论**:调用栈比 co_blueblird.js 的还乱。 230 | 231 | ## 参考链接 232 | 233 | - [https://medium.com/@markherhold/generators-vs-async-await-performance-806d8375a01a](https://medium.com/%40markherhold/generators-vs-async-await-performance-806d8375a01a) 234 | 235 | 上一节:[2.4 cpu-memory-monitor](https://github.com/nswbmw/node-in-debugging/blob/master/2.4%20cpu-memory-monitor.md) 236 | 237 | 下一节:[3.2 Error Stack](https://github.com/nswbmw/node-in-debugging/blob/master/3.2%20Error%20Stack.md) 238 | -------------------------------------------------------------------------------- /2.1 gcore + llnode.md: -------------------------------------------------------------------------------- 1 | 在开始之前,我们先了解下什么是 Core 和 Core Dump。 2 | 3 | **测试环境** 4 | 5 | ```sh 6 | $ uname -a 7 | Linux nswbmw-VirtualBox 4.13.0-36-generic #40~16.04.1-Ubuntu SMP Fri Feb 16 23:25:58 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux 8 | ``` 9 | 10 | **什么是 Core?** 11 | 12 | > 在使用半导体作为内存材料前,人类是利用线圈当作内存的材料,线圈就叫作 core ,用线圈做的内存就叫作 core memory。如今 ,半导体工业澎勃发展,已经没有人用 core memory 了,不过在许多情况下, 人们还是把记忆体叫作 core 。 13 | 14 | **什么是 Core Dump?** 15 | 16 | > 当程序运行的过程中异常终止或崩溃,操作系统会将程序当时的内存状态记录下来,保存在一个文件中,这种行为就叫做 Core Dump(中文有的翻译成“核心转储”)。我们可以认为 Core Dump 是“内存快照”,但实际上,除了内存信息之外,还有些关键的程序运行状态也会同时 dump 下来,例如寄存器信息(包括程序指针、栈指针等)、内存管理信息、其他处理器和操作系统状态和信息。Core Dump 对于编程人员诊断和调试程序是非常有帮助的,因为对于有些程序错误是很难重现的,例如指针异常,而 Core Dump 文件可以再现程序出错时的情景。 17 | 18 | **开启 Core Dump** 19 | 20 | 在终端中输入: 21 | 22 | ```sh 23 | $ ulimit -c 24 | ``` 25 | 26 | 查看允许 Core Dump 生成的文件的大小,如果是 0 则表示关闭了 Core Dump。使用以下命令开启 Core Dump 功能,并且不限制 Core Dump 生成的文件大小: 27 | 28 | ```sh 29 | $ ulimit -c unlimited 30 | ``` 31 | 32 | 以上命令只针对当前终端环境有效,如果想永久生效,可以修改 /etc/security/limits.conf 文件,如下: 33 | 34 | ![](./assets/2.1.1.jpg) 35 | 36 | ## [gcore](http://man7.org/linux/man-pages/man1/gcore.1.html) 37 | 38 | 我们可以使用 gcore 不重启程序而 dump 出特定进程的 core 文件。gcore 使用方法: 39 | 40 | ```sh 41 | $ gcore [-o filename] pid 42 | ``` 43 | 44 | Core Dump 时,默认会在执行 gcore 命令的目录生成 core. 的文件。 45 | 46 | ## llnode 47 | 48 | 什么是 llnode? 49 | 50 | > Node.js v4.x+ C++ plugin for [LLDB](http://lldb.llvm.org/) - a next generation, high-performance debugger. 51 | 52 | 什么是 LLDB? 53 | 54 | > LLDB is a next generation, high-performance debugger. It is built as a set of reusable components which highly leverage existing libraries in the larger LLVM Project, such as the Clang expression parser and LLVM disassembler. 55 | 56 | 安装 llnode + lldb: 57 | 58 | ```sh 59 | $ sudo apt-get update 60 | 61 | # Clone llnode 62 | $ git clone https://github.com/nodejs/llnode.git ~/llnode && cd ~/llnode 63 | 64 | # Install lldb and headers 65 | $ sudo apt-get install lldb-4.0 liblldb-4.0-dev 66 | 67 | # Initialize GYP 68 | $ git clone https://github.com/bnoordhuis/gyp.git tools/gyp 69 | 70 | # Configure 71 | $ ./gyp_llnode -Dlldb_dir=/usr/lib/llvm-4.0/ 72 | 73 | # Build 74 | $ make -C out/ -j9 75 | 76 | # Install 77 | $ sudo make install-linux 78 | ``` 79 | 80 | **注意:**如果 `sudo apt-get update` 遇到这种错误: 81 | 82 | ``` 83 | W: GPG error: xxx stable Release: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 6DA62DE462C7DA6D 84 | ``` 85 | 86 | 用以下命令解决: 87 | 88 | ```sh 89 | $ sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 6DA62DE462C7DA6D 90 | ``` 91 | 92 | --recv-keys 后面跟的是前面报错提示的 PUBKEY。 93 | 94 | ## 测试 Core Dump 95 | 96 | 下面用一个典型的全局变量缓存导致的内存泄漏的例子来测试 llnode 的用法。代码如下: 97 | 98 | **app.js** 99 | 100 | ```js 101 | const leaks = [] 102 | 103 | function LeakingClass() { 104 | this.name = Math.random().toString(36) 105 | this.age = Math.floor(Math.random() * 100) 106 | } 107 | 108 | setInterval(() => { 109 | for (let i = 0; i < 100; i++) { 110 | leaks.push(new LeakingClass) 111 | } 112 | 113 | console.warn('Leaks: %d', leaks.length) 114 | }, 1000) 115 | ``` 116 | 117 | 一个窗口运行该程序: 118 | 119 | ```sh 120 | $ node app.js 121 | ``` 122 | 123 | 等待几秒,打开另一个窗口运行 gcore: 124 | 125 | ```sh 126 | $ ulimit -c unlimited 127 | $ sudo gcore `pgrep -n node` 128 | ``` 129 | 130 | 生成 core.2763 文件。 131 | 132 | ## 分析 Core 文件 133 | 134 | 使用 lldb 加载刚才生成的 Core 文件: 135 | 136 | ```sh 137 | $ lldb-4.0 -c ./core.2763 138 | (lldb) target create --core "./core.2763" 139 | Core file '/home/nswbmw/test/./core.2763' (x86_64) was loaded. 140 | (lldb) 141 | ``` 142 | 143 | 输入 v8 查看使用文档,有以下几条命令: 144 | 145 | - bt 146 | - findjsinstances 147 | - findjsobjects 148 | - findrefs 149 | - inspect 150 | - nodeinfo 151 | - print 152 | - source 153 | 154 | 运行 `v8 findjsobjects` 查看所有对象实例及总共占内存大小: 155 | 156 | ``` 157 | (lldb) v8 findjsobjects 158 | Instances Total Size Name 159 | ---------- ---------- ---- 160 | ... 161 | 2100 84000 LeakingClass 162 | 8834 39792 (String) 163 | ---------- ---------- 164 | 12088 181320 165 | ``` 166 | 167 | **可以看出**:LeakingClass 有 2100 个实例,占内存 84000 bit。使用 `v8 findjsinstances` 查看所有 LeakingClass 实例: 168 | 169 | ``` 170 | (lldb) v8 findjsinstances LeakingClass 171 | 0x000022aaa118ab19: 172 | 0x000022aaa118acf9: 173 | 0x000022aaa118ade1: 174 | ... 175 | ``` 176 | 177 | 使用 `v8 i` 检索实例具体内容: 178 | 179 | ``` 180 | (lldb) v8 i 0x000022aaa118ab19 181 | 0x000022aaa118ab19:, 183 | .age=}> 184 | (lldb) v8 i 0x000022aaa118acf9 185 | 0x000022aaa118acf9:, 187 | .age=}> 188 | (lldb) v8 i 0x000022aaa118ade1 189 | 0x000022aaa118ade1:, 191 | .age=}> 192 | ``` 193 | 194 | 可以看到每个 LeakingClass 实例的 name 和 age 字段的值。 195 | 196 | 使用 `v8 findrefs` 查看引用: 197 | 198 | ``` 199 | (lldb) v8 findrefs 0x000022aaa118ab19 200 | 0x22aaa1189729: (Array)[0]=0x22aaa118ab19 201 | (lldb) v8 i 0x22aaa1189729 202 | 0x000022aaa1189729:, 204 | [1]=0x000022aaa118acf9:, 205 | [2]=0x000022aaa118ade1:, 206 | [3]=0x000022aaa118aea1:, 207 | [4]=0x000022aaa118af61:, 208 | [5]=0x000022aaa118b021:, 209 | [6]=0x000022aaa118b0e1:, 210 | [7]=0x000022aaa118b1a1:, 211 | [8]=0x000022aaa118b221:, 212 | [9]=0x000022aaa118b2a1:, 213 | [10]=0x000022aaa118b321:, 214 | [11]=0x000022aaa118b3a1:, 215 | [12]=0x000022aaa118b421:, 216 | [13]=0x000022aaa118b4a1:, 217 | [14]=0x000022aaa118b521:, 218 | [15]=0x000022aaa118b5a1:}> 219 | ``` 220 | 221 | **可以看出**:通过一个 LeakingClass 实例的内存地址,我们使用 `v8 findrefs` 找到了引用它的数组的内存地址,然后通过这个地址去检索数组,得到这个数组长度 2100,每一项都是一个 LeakingClass 实例,这不就是我们代码中的 leaks 数组嘛。 222 | 223 | **Tips**: `v8 i` 是 `v8 inspect` 的缩写,`v8 p` 是 `v8 print` 的缩写。 224 | 225 | ## --abort-on-uncaught-exception 226 | 227 | Node.js 中通过添加 --abort-on-uncaught-exception 参数启动,当程序 crash 的时候,会自动 Core Dump,方便『死后验尸』。 228 | 229 | 添加 --abort-on-uncaught-exception 参数启动测试程序: 230 | 231 | ```sh 232 | $ ulimit -c unlimited 233 | $ node --abort-on-uncaught-exception app.js 234 | ``` 235 | 236 | 启动另外一个终端运行: 237 | 238 | ```sh 239 | $ kill -BUS `pgrep -n node` 240 | ``` 241 | 242 | 第一个终端会显示: 243 | 244 | ```sh 245 | Leaks: 100 246 | Leaks: 200 247 | Leaks: 300 248 | Leaks: 400 249 | Leaks: 500 250 | Leaks: 600 251 | Leaks: 700 252 | Leaks: 800 253 | Bus error (core dumped) 254 | ``` 255 | 256 | 调试步骤与上面一致: 257 | 258 | ```sh 259 | $ lldb-4.0 -c ./core 260 | (lldb) target create --core "./core" 261 | Core file '/home/nswbmw/test/./core' (x86_64) was loaded. 262 | (lldb) v8 findjsobjects 263 | Instances Total Size Name 264 | ---------- ---------- ---- 265 | ... 266 | 800 32000 LeakingClass 267 | 7519 38512 (String) 268 | ---------- ---------- 269 | 9440 126368 270 | ``` 271 | 272 | ## 总结 273 | 274 | 我们的测试代码很简单,没有引用任何第三方模块,如果项目较大且引用的模块较多,`v8 findjsobjects` 的结果将难以甄别,这个时候可以多次使用 gcore 进行 Core Dump,对比发现增长的对象,再进行诊断。 275 | 276 | ## 参考链接 277 | 278 | - http://www.cnblogs.com/Anker/p/6079580.html 279 | - http://www.brendangregg.com/blog/2016-07-13/llnode-nodejs-memory-leak-analysis.html 280 | 281 | 上一节:[1.2 v8-profiler](https://github.com/nswbmw/node-in-debugging/blob/master/1.2%20v8-profiler.md) 282 | 283 | 下一节:[2.2 heapdump](https://github.com/nswbmw/node-in-debugging/blob/master/2.2%20heapdump.md) 284 | -------------------------------------------------------------------------------- /4.3 Visual Studio Code.md: -------------------------------------------------------------------------------- 1 | Visual Studio Code(简称 VS Code)是一款微软开源的现代化、跨平台、轻量级的代码编辑器。VS Code 很好很强大,本文将介绍如何使用 VS Code 来调试 Node.js 代码。 2 | 3 | ## 基本调试 4 | 5 | 示例代码: 6 | 7 | **app.js** 8 | 9 | ```js 10 | const Paloma = require('paloma') 11 | const app = new Paloma() 12 | 13 | app.use(ctx => { 14 | ctx.body = 'hello world!' 15 | }) 16 | 17 | app.listen(3000) 18 | ``` 19 | 20 | 用 VS Code 加载 test 文件夹,打开 app.js,然后: 21 | 22 | 1. 点击左侧第 4 个 tab 切换到调试模式 23 | 2. 点击代码第 5 行 `ctx.body='hello world!'` 左侧空白处添加断点 24 | 3. 点击左上角『调试』的绿色三角按钮启动调试 25 | 4. 点击左上角终端图标打开调试控制台 26 | 27 | 最终如下所示: 28 | 29 | ![](./assets/4.3.1.png) 30 | 31 | 从『调试控制台』切换到『终端』,运行: 32 | 33 | ```sh 34 | $ curl localhost:3000 35 | ``` 36 | 37 | 如下所示: 38 | 39 | ![](./assets/4.3.2.png) 40 | 41 | 可以看出,VS Code 基本覆盖了 Chrome DevTools 所有的功能,并且有两个额外的优点: 42 | 43 | 1. 集成了终端,不用再打开新的终端输入命令了 44 | 2. 调试动作里添加了『重启』和『停止』按钮,不用每次修改完代码切回终端去重启了 45 | 46 | 但 VS Code 的强大远不止如此,通过 launch.json 可以配置详细的调试功能。 47 | 48 | ## launch.json 49 | 50 | 上图可以看出,『调试』右边有个下拉菜单,默认是『没有配置』。点击右侧的齿轮状图标,会在项目根目录下创建 .vscode 文件夹及 launch.json 文件。launch.json 内容如下: 51 | 52 | ![](./assets/4.3.3.png) 53 | 54 | 这个默认配置的意思是执行: 55 | 56 | ```sh 57 | $ node ${workspaceFolder}/app.js 58 | ``` 59 | 60 | launch.json 其实就是存储了一些调试相关的配置,VS Code 启动调试时,会读取 launch.json 决定以何种方式调试。launch.json 有以下常用选项: 61 | 62 | 必需字段: 63 | 64 | - type:调试器类型。这里是 node(内置的调试器),如果装了 Go 和 PHP 的扩展后对应的 type 分别为 go 和 php 65 | - request:请求的类型,支持 launch 和 attach。launch 就是以 debug 模式启动调试,attach 就是附加到已经启动的进程开启 debug 模式并调试,跟上一小节提到的用 `node -e "process._debugProcess(PID)"` 作用一样 66 | - name:下拉菜单显示的名字 67 | 68 | 可选字段(括号里表示适用的类型): 69 | 70 | - program:可执行文件或者调试器要运行的文件 (launch) 71 | - args:要传递给调试程序的参数 (launch) 72 | - env:环境变量 (launch) 73 | - cwd:当前执行目录 (launch) 74 | - address:ip 地址 (launch & attach) 75 | - port:端口号 (launch & attach) 76 | - skipFiles:想要忽略的文件,数组类型 (launch & attach) 77 | - processId:进程 PID (attach) 78 | - ... 79 | 80 | 变量替换: 81 | 82 | - ${workspaceFolder}:当前打开工程的路径 83 | - ${file}:当前打开文件的路径 84 | - ${fileBasename}:当前打开文件的名字,包含后缀名 85 | - ${fileDirname}:当前打开文件所在的文件夹的路径 86 | - ${fileExtname}:当前打开文件的后缀名 87 | - ${cwd}:当前执行目录 88 | - ... 89 | 90 | 如果当前打开的文件是 app.js,则以下配置跟默认配置是等效的: 91 | 92 | ```json 93 | { 94 | "version": "0.2.0", 95 | "configurations": [ 96 | { 97 | "type": "node", 98 | "request": "launch", 99 | "name": "启动程序", 100 | "program": "${file}" 101 | } 102 | ] 103 | } 104 | ``` 105 | 106 | 更多 launch.json 选项请查阅: 107 | 108 | - [Debugging in Visual Studio Code](https://code.visualstudio.com/docs/editor/debugging#_launchjson-attributes) 109 | - [Debug Node.js Apps using VS Code](https://code.visualstudio.com/docs/nodejs/nodejs-debugging#_launch-configuration-attributes) 110 | 111 | 下面以 5 个实用的技巧讲解部分 launch.json 配置的作用。 112 | 113 | ## 技巧 1——条件断点 114 | 115 | VS Code 可以添加条件断点,即执行到该行代码满足特定条件后程序才会中断。在断点小红点上右键选择『编辑断点』,可以选择两种条件: 116 | 117 | 1. 表达式:当表达式计算结果为 true 时中断,如设置:`ctx.query.name === 'nswbmw'`,表示当访问 `localhost:3000?name=nswbmw` 时断点才会生效,其余请求断点无效 118 | 2. 命中次数:同样当表达式计算结果为 true 时中断,支持运算符 <, <=, ==, >, >=, %。如: 119 | 1. \>10:执行 10 次以后断点才会生效 120 | 2. <3:只有前 2 次断点会生效 121 | 3. 10:等价于 >=10 122 | 4. %2:隔一次中断一次 123 | 124 | **注意:**可以组合表达式和命中次数条件一起使用。在切换条件类型时,需要将原来的条件清空,否则会添加两种条件。将鼠标悬浮在断点上,可以查看设置了哪些条件。 125 | 126 | ## 技巧 2——skipFiles 127 | 128 | 从上面图中可以看到 VS Code 左侧有一个『调用堆栈』面板,显示了当前断点的调用堆栈,但无法直观的看出哪些是我们项目的代码,哪些是 node_moduels 里模块的代码,而且在点击单步调试时会进入到 node_modules 里。总之,我们不关心 node_modules 里的代码,我们只关心项目本身的代码。这个时候,skipFiles 就派上用场了。 129 | 130 | skipFiles 顾名思义就是忽略我们不关心的文件。修改 launch.json 如下: 131 | 132 | ```json 133 | { 134 | "version": "0.2.0", 135 | "configurations": [ 136 | { 137 | "type": "node", 138 | "request": "launch", 139 | "name": "启动程序", 140 | "program": "${workspaceFolder}/app.js", 141 | "skipFiles": [ 142 | "${workspaceFolder}/node_modules/**/*.js", 143 | "/**/*.js" 144 | ] 145 | } 146 | ] 147 | } 148 | ``` 149 | 150 | 有几点需要解释: 151 | 152 | 1. 支持 ${xxx} 这种变量替换 153 | 2. 支持 glob 模式匹配 154 | 3. 用来忽略 Node.js 核心模块 155 | 156 | 重启调试后,如下所示: 157 | 158 | ![](./assets/4.3.4.png) 159 | 160 | **可以看出**:左侧『调用堆栈』中我们不关心的调用栈都变灰了,而且单步调试也不会进入到 skipFiles 所匹配的文件里。 161 | 162 | ## 技巧 3——自动重启 163 | 164 | 每次修改代码保存后都要手动重启,否则修改后的代码和断点都不会生效。VS Code 开发者们想到了这一点,通过添加配置可以实现修改代码保存后会自动重启调试,需要结合 [nodemon](https://nodemon.io/) 一起使用。 165 | 166 | 首先全局安装 nodemon: 167 | 168 | ```sh 169 | $ npm i nodemon -g 170 | ``` 171 | 172 | 然后修改 launch.json 如下: 173 | 174 | ```json 175 | { 176 | "version": "0.2.0", 177 | "configurations": [ 178 | { 179 | "type": "node", 180 | "request": "launch", 181 | "name": "启动程序", 182 | "runtimeExecutable": "nodemon", 183 | "program": "${workspaceFolder}/app.js", 184 | "restart": true, 185 | "console": "integratedTerminal", 186 | "skipFiles": [ 187 | "${workspaceFolder}/node_modules/**/*.js", 188 | "/**/*.js" 189 | ] 190 | } 191 | ] 192 | } 193 | ``` 194 | 195 | 相比较上一个版本的 launch.json,多了以下几个字段: 196 | 197 | - runtimeExecutable:用什么命令执行 app.js,这里设置为 nodemon 198 | - restart:设置为 true,修改代码保存后会自动重启调试 199 | - console:当点击停止按钮或者修改代码保存后自动重启调试,而 nodemon 是仍然在运行的,通过设置为 console 为 integratedTerminal 可以解决这个问题。此时 VS Code 终端将会打印 nodemon 的 log,可以在终端右侧下拉菜单选择返回第一个终端,然后运行 `curl localhost:3000` 调试 200 | 201 | 对于已经使用 nodemon 运行的程序,如: 202 | 203 | ```sh 204 | $ nodemon --inspect app.js 205 | ``` 206 | 207 | 可使用 attach 模式启动调试,launch.json 如下: 208 | 209 | ```json 210 | { 211 | "version": "0.2.0", 212 | "configurations": [ 213 | { 214 | "name": "Attach to node", 215 | "type": "node", 216 | "request": "attach", 217 | "restart": true, 218 | "processId": "${command:PickProcess}" 219 | } 220 | ] 221 | } 222 | ``` 223 | 224 | 运行 Attach to node 配置进行调试时,VS Code 会列出正在执行的 node 进程及对应 PID 可供选择。也可以通过 address 和 port 参数设置 attach 到具体进程开启调试。 225 | 226 | ## 技巧 4——特定操作系统设置 227 | 228 | 针对不同的操作系统,可能会用到不同的调试配置。可选参数为: 229 | 230 | - windows 231 | - linux 232 | - osx 233 | 234 | 示例: 235 | 236 | ```json 237 | { 238 | "version": "0.2.0", 239 | "configurations": [ 240 | { 241 | "type": "node", 242 | "request": "launch", 243 | "name": "启动调试", 244 | "program": "./node_modules/gulp/bin/gulpfile.js", 245 | "args": ["/path/to/app.js"], 246 | "windows": { 247 | "args": ["\\path\\to\\app.js"] 248 | } 249 | } 250 | ] 251 | } 252 | ``` 253 | 254 | ## 技巧 5——多配置 255 | 256 | configurations 是个数组而不是个对象,这样设计就是为了可以添加多个调试配置。打开 launch.json 点击右下角的『添加配置...』会弹出配置模板,如下所示: 257 | 258 | ![](./assets/4.3.5.png) 259 | 260 | 可以用来配置不同的调试规则,比如最终我们将 launch.json 修改成如下: 261 | 262 | ```json 263 | { 264 | "version": "0.2.0", 265 | "configurations": [ 266 | { 267 | "type": "node", 268 | "request": "attach", 269 | "name": "Attach to node", 270 | "restart": true, 271 | "processId": "${command:PickProcess}" 272 | }, 273 | { 274 | "type": "node", 275 | "request": "launch", 276 | "name": "启动程序", 277 | "runtimeExecutable": "nodemon", 278 | "program": "${workspaceFolder}/app.js", 279 | "restart": true, 280 | "console": "integratedTerminal", 281 | "skipFiles": [ 282 | "${workspaceFolder}/node_modules/**/*.js", 283 | "/**/*.js" 284 | ] 285 | } 286 | ] 287 | } 288 | ``` 289 | 290 | ## 总结 291 | 292 | VS Code 调试功能十分强大,本文只讲解了一些常用的调试功能,其余的调试功能还请读者自行尝试。 293 | 294 | ## 参考链接 295 | 296 | - https://code.visualstudio.com/docs/editor/debugging 297 | - https://code.visualstudio.com/docs/nodejs/nodejs-debugging 298 | 299 | 上一节:[4.2 Chrome DevTools](https://github.com/nswbmw/node-in-debugging/blob/master/4.2%20Chrome%20DevTools.md) 300 | 301 | 下一节:[4.4 debug + repl2 + power-assert](https://github.com/nswbmw/node-in-debugging/blob/master/4.4%20debug%20%2B%20repl2%20%2B%20power-assert.md) 302 | -------------------------------------------------------------------------------- /1.1 perf + FlameGraph.md: -------------------------------------------------------------------------------- 1 | [火焰图](http://www.brendangregg.com/flamegraphs.html)(Flame Graph)想必大家都听过,它可以将 CPU 的使用情况可视化展示,能够直观地帮助我们了解到程序的性能瓶颈。通常要结合操作系统的性能分析工具(profiling tracer)使用,常见的有: 2 | 3 | - Linux:perf, eBPF, SystemTap, and ktap 4 | - Solaris, illumos, FreeBSD:DTrace 5 | - Mac OS X:DTrace and Instruments 6 | - Windows:Xperf.exe 7 | 8 | ## perf 9 | 10 | [perf](http://www.brendangregg.com/linuxperf.html)(也称 perf_events)是 Linux kernal 自带的系统性能分析工具,能够进行函数级与指令级的热点查找。它基于事件采样原理,以性能事件为基础,支持针对处理器相关性能指标与操作系统相关性能指标的性能剖析,常用于性能瓶颈的查找与热点代码的定位。 11 | 12 | 测试机器: 13 | 14 | ```sh 15 | $ uname -a 16 | Linux nswbmw-VirtualBox 4.10.0-28-generic #32~16.04.2-Ubuntu SMP Thu Jul 20 10:19:48 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux 17 | ``` 18 | 19 | **注意:**非 Linux 用户可以用虚拟机安装 Ubuntu 16.04 和 node@8.9.4 后进行后面的操作。 20 | 21 | 安装 perf: 22 | 23 | ```sh 24 | $ sudo apt install linux-tools-common 25 | $ perf # 根据提示安装对应内核版本的 tools, 如下 26 | $ sudo apt install linux-tools-4.10.0-28-generic linux-cloud-tools-4.10.0-28-generic 27 | ``` 28 | 29 | 创建测试目录 ~/test 和测试代码: 30 | 31 | **app.js** 32 | 33 | ```js 34 | const crypto = require('crypto') 35 | const Paloma = require('paloma') 36 | const app = new Paloma() 37 | const users = {} 38 | 39 | app.route({ method: 'GET', path: '/newUser', controller (ctx) { 40 | const username = ctx.query.username || 'test' 41 | const password = ctx.query.password || 'test' 42 | 43 | const salt = crypto.randomBytes(128).toString('base64') 44 | const hash = crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha512').toString('hex') 45 | 46 | users[username] = { salt, hash } 47 | 48 | ctx.status = 204 49 | }}) 50 | 51 | app.route({ method: 'GET', path: '/auth', controller (ctx) { 52 | const username = ctx.query.username || 'test' 53 | const password = ctx.query.password || 'test' 54 | 55 | if (!users[username]) { 56 | ctx.throw(400) 57 | } 58 | const hash = crypto.pbkdf2Sync(password, users[username].salt, 10000, 64, 'sha512').toString('hex') 59 | 60 | if (users[username].hash === hash) { 61 | ctx.status = 204 62 | } else { 63 | ctx.throw(403) 64 | } 65 | }}) 66 | 67 | app.listen(3000) 68 | ``` 69 | 70 | 添加 --perf_basic_prof(或者--perf-basic-prof)参数运行此程序,对应会生成一个 /tmp/perf-.map 的文件。如下: 71 | 72 | ```sh 73 | $ node --perf_basic_prof app.js & 74 | [1] 3590 75 | $ tail /tmp/perf-3590.map 76 | 51b87a7b93e 18 Function:~emitListeningNT net.js:1375 77 | 51b87a7b93e 18 LazyCompile:~emitListeningNT net.js:1375 78 | 51b87a7bad6 39 Function:~emitAfterScript async_hooks.js:443 79 | 51b87a7bad6 39 LazyCompile:~emitAfterScript async_hooks.js:443 80 | 51b87a7bcbe 77 Function:~tickDone internal/process/next_tick.js:88 81 | 51b87a7bcbe 77 LazyCompile:~tickDone internal/process/next_tick.js:88 82 | 51b87a7bf36 12 Function:~clear internal/process/next_tick.js:42 83 | 51b87a7bf36 12 LazyCompile:~clear internal/process/next_tick.js:42 84 | 51b87a7c126 b8 Function:~emitPendingUnhandledRejections internal/process/promises.js:86 85 | 51b87a7c126 b8 LazyCompile:~emitPendingUnhandledRejections internal/process/promises.js:86 86 | ``` 87 | 88 | **三列依次为**:16进制符号地址(symbol addresses)、大小(sizes)和符号名(symbol names)。perf 会尝试查找 /tmp/perf-.map 文件,用来做符号转换,即把 16 进制符号地址转换成人能读懂的符号名。 89 | 90 | **注意**:--perf_basic_prof_only_functions 参数也可以,但经尝试后发现生成的火焰图信息不全(不全的地方显示 [perf-.map]),所以本文使用 —perf_basic_prof,但使用 --perf_basic_prof 有个缺点是会导致 map 文件一直增大,原因是符号(symbols)地址不断变换导致的,用 --perf_basic_prof_only_functions 可以缓解这个问题,如何取舍还请读者自行尝试。 91 | 92 | 接下来 clone 用来生成火焰图的工具: 93 | 94 | ```sh 95 | $ git clone http://github.com/brendangregg/FlameGraph ~/FlameGraph 96 | ``` 97 | 98 | 我们先用 ab 压测: 99 | 100 | ```sh 101 | $ curl "http://localhost:3000/newUser?username=admin&password=123456" 102 | $ ab -k -c 10 -n 2000 "http://localhost:3000/auth?username=admin&password=123456" 103 | ``` 104 | 105 | 新开另一个窗口,在 ab 压测之后立即运行: 106 | 107 | ```sh 108 | $ sudo perf record -F 99 -p 3590 -g -- sleep 30 109 | $ sudo chown root /tmp/perf-3590.map 110 | $ sudo perf script > perf.out 111 | $ ~/FlameGraph/stackcollapse-perf.pl --kernel < ~/perf.out | ~/FlameGraph/flamegraph.pl --color=js --hash> ~/flamegraph.svg 112 | ``` 113 | 114 | **注意**:第一次生成的 svg 可能不太准确,以上步骤最好重复几次,使用第二次及以后生成的 flamegraph.svg。 115 | 116 | 有几点需要解释一下: 117 | 118 | - perf record 119 | - -F 指定了采样频率 99Hz(即每秒 99 次,如果 99 次都返回同一个函数名,那就说明 CPU 这一秒钟都在执行同一个函数,可能存在性能问题) 120 | - -p 指定进程的 pid 121 | - -g 启用 call-graph 记录 122 | - -- sleep 30 指定记录 30s 123 | 124 | - sudo chown root /tmp/perf-3009.map 125 | 126 | - 将 map 文件更改为 root 权限,否则会报这个错: 127 | > File /tmp/perf-PID.map not owned by current user or root, ignoring it (use -f to override). 128 | > Failed to open /tmp/perf-PID.map, continuing without symbols 129 | 130 | - perf record 会将记录的信息保存到当前执行目录的 perf.data 文件里,用 perf script 将信息 dump 到 perf.out 131 | 132 | - --color=js 指定生成针对 js 配色的 svg,即:green == JavaScript, blue == Builtin, yellow == C++, red == system (native user-level, and kernel) 133 | 134 | ab 压测用了 30s 左右,浏览器打开 flamegraph.svg,截取关键部分如下图所示: 135 | ![](./assets/1.1.1.png) 136 | 137 | ## 理解火焰图 138 | 139 | 火焰图含义: 140 | 141 | - 每一个小块代表了一个函数在栈中的位置(即一个栈帧) 142 | - Y 轴代表了栈的深度(栈上的帧数),顶端的小块显示了占据 CPU 的函数。每个小块下面是它的祖先(即父函数) 143 | - X 轴表示总的样例群体。它不像绝大多数图表那样从左到右表示时间的流逝,它们的左右顺序没有特殊含义,仅仅是按照字母表顺序排列 144 | - 小块的宽度表示 CPU 使用时间或者说相对父函数而言使用 CPU 的比率(基于所有样例),越宽代表占用 CPU 的时间越长,或者使用 CPU 很频繁 145 | - 如果采取多线程并发运行取样,取样数量会超过运行时间 146 | 147 | **从上图可以看出**:最上面的绿色小块(即 js 代码)指向 test/app.js:18 行,即 `GET /auth` 这个路由。再往上看,黄色的小块(即 C++ 代码) node::crypto::PBKDF2 占用了大量的 CPU 时间。 148 | 149 | **解决方法**:将同步改为异步,即将 crypto.pbkdf2Sync 改为 crypto.pbkdf2,如下修改: 150 | 151 | ```js 152 | app.route({ method: 'GET', path: '/auth', async controller (ctx) { 153 | const username = ctx.query.username || 'test' 154 | const password = ctx.query.password || 'test' 155 | 156 | if (!users[username]) { 157 | ctx.throw(400) 158 | } 159 | const hash = await new Promise((resolve, reject) => { 160 | crypto.pbkdf2(password, users[username].salt, 10000, 64, 'sha512', (err, derivedKey) => { 161 | if (err) { 162 | return reject(err) 163 | } 164 | resolve(derivedKey.toString('hex')) 165 | }) 166 | }) 167 | 168 | if (users[username].hash === hash) { 169 | ctx.status = 204 170 | } else { 171 | ctx.throw(403) 172 | } 173 | }}) 174 | ``` 175 | 176 | 用 ab 重新压测,结果用了 16s。重新生成的火焰图如下: 177 | 178 | ![](./assets/1.1.2.png) 179 | 180 | **可以看出**:只有左侧极窄的小块可以看到 js 的代码,红色的部分我们不关心也无法优化。那为什么异步比同步的 rps 要高呢?原因是 Node.js 底层的 libuv 用了多个线程做计算任务,这里就不再深入介绍。 181 | 182 | svg 火焰图其他小技巧: 183 | 184 | 1. 点击任意一个小块可以展开,即被点击的小块宽度变宽,它的子函数也按比例变宽,方便查看。 185 | 2. 可点击 svg 右上角的 search 按钮搜索,被搜索的关键词会高亮显示,在有目的查找某个函数时比较有用。 186 | 187 | ## 红蓝差分火焰图 188 | 189 | 虽然我们有了火焰图,但要处理性能回退问题,就要在修改代码前后的火焰图之间,不断切换对比,来找出问题所在。于是 [Brendan D. Gregg](http://www.brendangregg.com/index.html) 又发明了红蓝差分火焰图(red/blue differential flame graphs)。 190 | ![](./assets/1.1.3.jpg) 191 | 192 | **如上所示**:红色表示增长,蓝色表示衰减。 193 | 194 | 红蓝差分火焰图工作原理: 195 | 196 | 1. 抓取修改前的栈 profile1 文件 197 | 2. 抓取修改后的栈 profile2 文件 198 | 3. 使用 profile2 来生成火焰图(这样栈帧的宽度就是以 profile2 文件为基准的) 199 | 4. 使用 2 - 1 的差异来对火焰图重新上色。上色的原则是,如果栈帧在 profile2 中出现出现的次数更多,则标为红色,否则标为蓝色。色彩是根据修改前后的差异来填充的。 200 | 201 | 这样,通过红蓝差分火焰图,我们可以清楚地看到系统性能差异之处。 202 | 203 | 生成红蓝差分火焰图: 204 | 205 | 1. 修改代码前: 206 | 207 | ```sh 208 | $ sudo perf record -F 99 -p -g -- sleep 30 209 | $ sudo chown root /tmp/perf-.map 210 | $ sudo perf script > perf.out1 211 | ``` 212 | 213 | 2. 修改代码后: 214 | 215 | ```sh 216 | $ sudo perf record -F 99 -p -g -- sleep 30 217 | $ sudo chown root /tmp/perf-.map 218 | $ sudo perf script > perf.out2 219 | ``` 220 | 221 | 3. 将 profile 文件进行折叠(fold), 再生成差分火焰图: 222 | 223 | ```sh 224 | $ ~/FlameGraph/stackcollapse-perf.pl ~/perf.out1 > perf.folded1 225 | $ ~/FlameGraph/stackcollapse-perf.pl ~/perf.out2 > perf.folded2 226 | $ ./FlameGraph/difffolded.pl perf.folded1 perf.folded2 | ./FlameGraph/flamegraph.pl > flamegraph_diff.svg 227 | ``` 228 | 229 | **缺点**:如果一个代码执行路径完全消失了,那么在火焰图中就找不到地方来标注蓝色。你只能看到当前的 CPU 使用情况,而不知道为什么会变成这样。 230 | 231 | 一个解决办法是,生成一个相反的差分火焰图,即基于 profile1 生成 1 - 2 的差分火焰图。对应命令如下: 232 | 233 | ```sh 234 | $ ./FlameGraph/difffolded.pl perf.folded2 perf.folded1 | ./FlameGraph/flamegraph.pl --negate > flamegraph_diff2.svg 235 | ``` 236 | 237 | --negate 用于颠倒红/蓝配色。最终我们得到: 238 | 239 | - flamegraph_diff.svg:宽度是以修改前 profile 文件为基准,颜色表明将要发生的情况 240 | - flamegraph_diff2.svg:宽度是以修改后 profile 文件为基准,颜色表明已经发生的情况 241 | 242 | **总结**:红蓝差分火焰图可能只在代码变化不大的情况下使用效果明显,代码变化多了效果可能并不明显。 243 | 244 | ## 参考链接 245 | 246 | - https://yunong.io/2015/11/23/generating-node-js-flame-graphs/ 247 | - http://www.brendangregg.com/perf.html 248 | - http://www.brendangregg.com/blog/2014-09-17/node-flame-graphs-on-linux.html 249 | - https://linux.cn/article-4670-1.html 250 | - http://www.brendangregg.com/blog/2014-11-09/differential-flame-graphs.html 251 | - http://www.ruanyifeng.com/blog/2017/09/flame-graph.html 252 | 253 | 下一节:[1.2 v8-profiler](https://github.com/nswbmw/node-in-debugging/blob/master/1.2%20v8-profiler.md) 254 | -------------------------------------------------------------------------------- /6.2 async_hooks.md: -------------------------------------------------------------------------------- 1 | 上一小节讲解了 koa-await-breakpoint 的用法,但 koa-await-breakpoint 仍然有一个很大的缺憾,即:无法记录除 routes/controllers 之外的函数的执行时间(因为获取不到当前请求的 ctx)。举个更通俗的例子:我在一个路由的 controller 里面调用了 A ,A 调用了其他文件的 B ,B 又调用了其他文件的 C...这是非常常见的用法,但之前使用 koa-await-breakpoint 只能获取 A 的执行时间,无法获取 B 和 C 的执行时间。 2 | 3 | **根本原因在于**:无法知道函数之间的调用关系,即 B 不知道是 A 调用的它,即便知道也不知道是哪次请求到来时执行的 A 调用的它。 4 | 5 | 但是,node@8.1 引入了一个黑魔法——Async Hooks。 6 | 7 | ## Async Hooks 8 | 9 | 我们先看下 async_hooks 是个什么东西。官网介绍: 10 | 11 | > The `async_hooks` module provides an API to register callbacks tracking the lifetime of asynchronous resources created inside a Node.js application. 12 | 13 | **一句话概括**:async_hooks 用来追踪 Node.js 中异步资源的生命周期。 14 | 15 | 我们来看段测试代码: 16 | 17 | ```js 18 | const fs = require('fs') 19 | const async_hooks = require('async_hooks') 20 | 21 | async_hooks.createHook({ 22 | init (asyncId, type, triggerAsyncId, resource) { 23 | fs.writeSync(1, `${type}(${asyncId}): trigger: ${triggerAsyncId}\n`) 24 | }, 25 | destroy (asyncId) { 26 | fs.writeSync(1, `destroy: ${asyncId}\n`); 27 | } 28 | }).enable() 29 | 30 | async function A () { 31 | fs.writeSync(1, `A -> ${async_hooks.executionAsyncId()}\n`) 32 | setTimeout(() => { 33 | fs.writeSync(1, `A in setTimeout -> ${async_hooks.executionAsyncId()}\n`) 34 | B() 35 | }) 36 | } 37 | 38 | async function B () { 39 | fs.writeSync(1, `B -> ${async_hooks.executionAsyncId()}\n`) 40 | process.nextTick(() => { 41 | fs.writeSync(1, `B in process.nextTick -> ${async_hooks.executionAsyncId()}\n`) 42 | C() 43 | C() 44 | }) 45 | } 46 | 47 | function C () { 48 | fs.writeSync(1, `C -> ${async_hooks.executionAsyncId()}\n`) 49 | Promise.resolve().then(() => { 50 | fs.writeSync(1, `C in promise.then -> ${async_hooks.executionAsyncId()}\n`) 51 | }) 52 | } 53 | 54 | fs.writeSync(1, `top level -> ${async_hooks.executionAsyncId()}\n`) 55 | A() 56 | ``` 57 | 58 | async_hooks.createHook 可以注册 4 个方法来跟踪所有异步资源的初始化(init),回调之前(before),回调之后(after),销毁后(destroy)事件,并通过调用 .enable() 启用,调用 .disable() 关闭。 59 | 60 | 这里我们只关心异步资源的初始化和销毁的事件,并使用 `fs.writeSync(1, msg)` 打印到标准输出,writeSync 第一个参数接收文件描述符,1 表示标准输出。为什么不使用 console.log 呢?因为 console.log 是一个异步操作,如果在 init, before, after, destroy 事件处理函数中出现,就会导致无限循环,同理也不能使用任何其他的异步操作。 61 | 62 | 运行该程序,打印如下: 63 | 64 | ``` 65 | top level -> 1 66 | PROMISE(6): trigger: 1 67 | A -> 1 68 | Timeout(7): trigger: 1 69 | TIMERWRAP(8): trigger: 1 70 | A in setTimeout -> 7 71 | PROMISE(9): trigger: 7 72 | B -> 7 73 | TickObject(10): trigger: 7 74 | B in process.nextTick -> 10 75 | C -> 10 76 | PROMISE(11): trigger: 10 77 | PROMISE(12): trigger: 11 78 | C -> 10 79 | PROMISE(13): trigger: 10 80 | PROMISE(14): trigger: 13 81 | C in promise.then -> 12 82 | C in promise.then -> 14 83 | destroy: 7 84 | destroy: 10 85 | destroy: 8 86 | ``` 87 | 88 | 这段程序的打印结果包含了很多信息,我们逐个解释: 89 | 90 | 1. 为了实现对异步资源的跟踪,node 对每一个函数(不论异步还是同步)提供了一个 async scope,我们可以通过调用 `async_hooks.executionAsyncId()` 来获取函数当前的 async scope 的 id(称为 asyncId),通过调用 `async_hooks.triggerAsyncId()` 来获取当前函数调用者的 asyncId。 91 | 2. 异步资源创建时触发 init 事件函数,init 函数中的第一个参数代表该异步资源的 asyncId,type 表示异步资源的类型(如 TCPWRAP, PROMISE, Timeout, Immediate, TickObject 等等),triggerAsyncId 表示该异步资源的调用者的 asyncId。异步资源销毁时触发 destroy 事件函数,该函数只接收一个参数即该异步资源的 asyncId。 92 | 3. 函数调用关系明确。从上面的打印结果我们可以很容易看出(从下往上看) :C(asyncId: 10) 被 B(asyncId: 7) 调用,B(asyncId: 7) 被 A(asyncId: 1) 调用。而且 C 的 promise.then 里面的 asyncId(值为 12/14) 也可以通过 12/14 -> 11/13 -> 10 定位到 C 的 asyncId(值为 10)。 93 | 4. 同步函数每次调用的 asyncId 都一样,如上 C 调用了 2 次,都打印的 C -> 10,与调用方的作用域的 asyncId 一致,即上面打印的 B in process.nextTick -> 10。异步函数每次调用的 asyncId 不一样,如上面打印的 C in promise.then -> 12 和 C in promise.then -> 14。 94 | 5. 最外层作用域的 asyncId 总是 1,每个异步资源创建时 asyncId 全局递增。 95 | 96 | 上面 5 条结论非常重要。接下来我们看看如何使用 async_hooks 改造 koa-await-breakpoint。 97 | 98 | ## 改造 koa-await-breakpoint 99 | 100 | 通过前面结论我们知道,使用 async_hooks 可以通过 asyncId 串起函数的调用关系,但是如何将这些函数的调用链与 koa 接收的每个请求关联起来呢? 101 | 102 | 首先,定义一个全局 Map,存储函数的调用关系: 103 | 104 | ```js 105 | const async_hooks = require('async_hooks') 106 | const asyncIdMap = new Map() 107 | 108 | async_hooks.createHook({ 109 | init (asyncId, type, triggerAsyncId) { 110 | const ctx = getCtx(triggerAsyncId) 111 | if (ctx) { 112 | asyncIdMap.set(asyncId, ctx) 113 | } else { 114 | asyncIdMap.set(asyncId, triggerAsyncId) 115 | } 116 | }, 117 | destroy (asyncId) { 118 | asyncIdMap.delete(asyncId) 119 | } 120 | }).enable() 121 | 122 | function getCtx (asyncId) { 123 | if (!asyncId) { 124 | return 125 | } 126 | if (typeof asyncId === 'object' && asyncId.app) { 127 | return asyncId 128 | } 129 | return getCtx(asyncIdMap.get(asyncId)) 130 | } 131 | ``` 132 | 133 | 有 3 点需要解释: 134 | 135 | 1. 定义了一个全局 Map 存储函数的调用关系,在适当的地方(下面会讲到)将当前请求的 ctx 存储到 Map 中,key 是 asyncId。 136 | 2. 每个异步资源初始化时,会拿 asyncId 尝试往上寻找祖先的 value 是否是 ctx(koa 应用中每个请求的 ctx),如果有则直接设置 value 是 ctx,否则设置为调用者的 asyncId(即 triggerAsyncId)。 137 | 3. destroy 事件函数里直接删除调用关系,保证了不会引起内存泄漏,即杜绝了引用 ctx 没有释放的情况。 138 | 139 | 然后修改 global[loggerName] 如下: 140 | 141 | ```js 142 | global[loggerName] = async function (ctx, fn, fnStr, filename) { 143 | const originalContext = ctx 144 | let requestId = _getRequestId() 145 | 146 | const asyncId = async_hooks.executionAsyncId() 147 | if (!requestId) { 148 | const _ctx = getCtx(asyncId) 149 | if (_ctx) { 150 | ctx = _ctx 151 | requestId = _getRequestId() 152 | } 153 | } else { 154 | asyncIdMap.set(asyncId, ctx) 155 | } 156 | 157 | if (requestId) { 158 | _logger('beforeAwait') 159 | } 160 | const result = await fn.call(originalContext) 161 | if (requestId) { 162 | _logger('afterAwait', result) 163 | } 164 | return result 165 | 166 | function _getRequestId () { 167 | return ctx && ctx.app && _.get(ctx, requestIdPath) 168 | } 169 | 170 | function _logger (type, result) { 171 | ... 172 | } 173 | } 174 | ``` 175 | 176 | 有 2 点需要解释: 177 | 178 | 1. logger 函数传入的第一个参数 ctx,之前是每个请求的 ctx,现在可能是当前执行上下文的 this,所以先将 ctx 赋值给 originalContext,然后通过 `await fn.call(originalContext)` 让函数执行时有正确的上下文。 179 | 2. 如果传入的 ctx 是来自请求的 ctx 且能拿到 requestId,那么将当前 asyncId 和 ctx 写入 Map,如果不是来自请求的 ctx,则尝试从 Map 里往上寻找祖先的 value 是否是 ctx,如果找到则覆盖当前的 ctx 并拿到 requestId。 180 | 181 | 至此,koa-await-breakpoint 全部改造完毕。接下来我们通过一个例子验证下升级后的 koa-await-breakpoint: 182 | 183 | **app.js** 184 | 185 | ```js 186 | const koaAwaitBreakpoint = require('koa-await-breakpoint')({ 187 | files: ['./routes/*.js'] 188 | }) 189 | 190 | const Paloma = require('paloma') 191 | const app = new Paloma() 192 | 193 | app.use(koaAwaitBreakpoint) 194 | app.route({ method: 'POST', path: '/users', controller: require('./routes/user').createUser }) 195 | 196 | app.listen(3000) 197 | ``` 198 | 199 | **routes/users.js** 200 | 201 | ```js 202 | const Mongolass = require('mongolass') 203 | const mongolass = new Mongolass('mongodb://localhost:27017/test') 204 | const User = mongolass.model('User') 205 | const Post = mongolass.model('Post') 206 | const Comment = mongolass.model('Comment') 207 | 208 | exports.createUser = async function (ctx) { 209 | const name = ctx.query.name || 'default' 210 | const age = +ctx.query.age || 18 211 | await createUser(name, age) 212 | ctx.status = 204 213 | } 214 | 215 | async function createUser (name, age) { 216 | const user = (await User.create({ 217 | name, 218 | age 219 | })).ops[0] 220 | await createPost(user) 221 | } 222 | 223 | async function createPost (user) { 224 | const post = (await Post.create({ 225 | uid: user._id, 226 | title: 'post', 227 | content: 'post' 228 | })).ops[0] 229 | 230 | await createComment(user, post) 231 | } 232 | 233 | async function createComment (user, post) { 234 | await Comment.create({ 235 | userId: user._id, 236 | postId: post._id, 237 | content: 'comment' 238 | }) 239 | } 240 | ``` 241 | 242 | 这段代码的意思是:访问创建用户接口时,调用 createUser,createUser 里面又调用了 createPost,createPost 里面调用了 createComment。 243 | 244 | ```sh 245 | $ curl -XPOST localhost:3000/users 246 | ``` 247 | 248 | 打印如下: 249 | 250 | ```js 251 | { type: 'start', 252 | step: 1, 253 | take: 0 ... } 254 | { type: 'beforeAwait', 255 | step: 2, 256 | fn: 'createUser(name, age)', 257 | take: 1 ... } 258 | { type: 'beforeAwait', 259 | step: 3, 260 | fn: 'User.create(...)', 261 | take: 1 ... } 262 | { type: 'afterAwait', 263 | step: 4, 264 | fn: 'User.create(...)', 265 | take: 36 ... } 266 | { type: 'beforeAwait', 267 | step: 5, 268 | fn: 'createPost(user)', 269 | take: 1 ... } 270 | { type: 'beforeAwait', 271 | step: 6, 272 | fn: 'Post.create(...)', 273 | take: 0 ... } 274 | { type: 'afterAwait', 275 | step: 7, 276 | fn: 'Post.create(...)', 277 | take: 3 ... } 278 | { type: 'beforeAwait', 279 | step: 8, 280 | fn: 'createComment(user, post)', 281 | take: 1 ... } 282 | { type: 'beforeAwait', 283 | step: 9, 284 | fn: 'Comment.create(...)', 285 | take: 0 ... } 286 | { type: 'afterAwait', 287 | step: 10, 288 | fn: 'Comment.create(...)', 289 | take: 1 ... } 290 | { type: 'afterAwait', 291 | step: 11, 292 | fn: 'createComment(user, post)', 293 | take: 1 ... } 294 | { type: 'afterAwait', 295 | step: 12, 296 | fn: 'createPost(user)', 297 | take: 6 ... } 298 | { type: 'afterAwait', 299 | step: 13, 300 | fn: 'createUser(name, age)', 301 | take: 44 ... } 302 | { type: 'end', 303 | step: 14, 304 | take: 0 ... } 305 | ``` 306 | 307 | 至此,一个全链路、无侵入、强大的日志打点工具就完成了。 308 | 309 | ## 警告 310 | 311 | 使用 async_hooks 目前有较严重的性能损耗,见 [bmeurer/async-hooks-performance-impact](https://github.com/bmeurer/async-hooks-performance-impact),请慎重在生产环境中使用。 312 | 313 | ## 参考文献 314 | 315 | - https://nodejs.org/dist/latest-v8.x/docs/api/async_hooks.html 316 | - https://zhuanlan.zhihu.com/p/27394440 317 | - https://www.jianshu.com/p/4a568dac41ed 318 | 319 | 上一节:[6.1 koa-await-breakpoint](https://github.com/nswbmw/node-in-debugging/blob/master/6.1%20koa-await-breakpoint.md) 320 | 321 | 下一节:[6.3 ELK](https://github.com/nswbmw/node-in-debugging/blob/master/6.3%20ELK.md) 322 | -------------------------------------------------------------------------------- /3.4 Rust Addons.md: -------------------------------------------------------------------------------- 1 | 我们知道 Node.js 不适合 CPU 密集型计算的场景,通常解决方法是用 C/C++ 编写 Node.js 的扩展(Addons)。以前只能用 C/C++,现在我们有了新的选择——Rust。 2 | 3 | ## 环境 4 | 5 | - node@8.9.4 6 | - rust@1.26.0-nightly 7 | 8 | ## Rust 9 | 10 | Rust 是 Mozilla 开发的注重安全、性能和并发的现代编程语言。相比较于其他常见的编程语言,它有 3 个独特的概念: 11 | 12 | 1. 所有权 13 | 2. 借用 14 | 3. 生命周期 15 | 16 | 正是这 3 个特性保证了 Rust 是内存安全的,这里不会展开讲解,有兴趣的读者可以去了解下。 17 | 18 | 接下来,我们通过三种方式使用 Rust 编写 Node.js 的扩展。 19 | 20 | ## [FFI](https://github.com/node-ffi/node-ffi) 21 | 22 | FFI 全称是 Foreign Function Interface,即可以用 Node.js 调用动态链接库。 23 | 24 | 运行以下命令: 25 | 26 | ```sh 27 | $ cargo new ffi-demo && cd ffi-demo 28 | $ npm init -y 29 | $ npm i ffi --save 30 | $ touch index.js 31 | ``` 32 | 33 | 部分文件修改如下: 34 | 35 | **src/lib.rs** 36 | 37 | ```rust 38 | #[no_mangle] 39 | pub extern fn fib(n: i64) -> i64 { 40 | return match n { 41 | 1 | 2 => 1, 42 | n => fib(n - 1) + fib(n - 2) 43 | } 44 | } 45 | ``` 46 | 47 | **Cargo.toml** 48 | 49 | ```toml 50 | [package] 51 | name = "ffi-demo" 52 | version = "0.1.0" 53 | 54 | [lib] 55 | name = "ffi" 56 | crate-type = ["dylib"] 57 | ``` 58 | 59 | Cargo.toml 是 Rust 项目的配置文件,相当于 Node.js 中的 package.json。这里指定编译生成的类型是 dylib(动态链接库),名字在 *inux 下是 libffi,Windows 下是 ffi。 60 | 61 | 使用 cargo 编译代码: 62 | 63 | ```sh 64 | $ cargo build #开发环境用 65 | 或者 66 | $ cargo build --release #生产环境用,编译器做了更多优化,但编译慢 67 | ``` 68 | 69 | cargo 是 Rust 的构建工具和包管理工具,负责构建代码、下载依赖库并编译它们。此时会生成一个 target 的目录,该目录下会有 debug(不加 --release)或者 release(加 --release)目录,存放了生成的动态链接库。 70 | 71 | **index.js** 72 | 73 | ```js 74 | const ffi = require('ffi') 75 | const isWin = /^win/.test(process.platform) 76 | 77 | const rust = ffi.Library('target/debug/' + (!isWin ? 'lib' : '') + 'ffi', { 78 | fib: ['int', ['int']] 79 | }) 80 | 81 | function fib(n) { 82 | if (n === 1 || n === 2) { 83 | return 1 84 | } 85 | return fib(n - 1) + fib(n - 2) 86 | } 87 | 88 | // js 89 | console.time('node') 90 | console.log(fib(40)) 91 | console.timeEnd('node') 92 | 93 | // rust 94 | console.time('rust') 95 | console.log(rust.fib(40)) 96 | console.timeEnd('rust') 97 | ``` 98 | 99 | 运行 index.js: 100 | 101 | ```sh 102 | $ node index.js 103 | 102334155 104 | node: 1053.743ms 105 | 102334155 106 | rust: 1092.570ms 107 | ``` 108 | 109 | 将 index.js 中 debug 改为 release,运行: 110 | 111 | ```sh 112 | $ cargo build --release 113 | $ node index.js 114 | 102334155 115 | node: 1050.467ms 116 | 102334155 117 | rust: 273.508ms 118 | ``` 119 | 120 | 可以看出,添加 --release 编译后的代码执行效率提升十分明显。 121 | 122 | ## [Neon](https://github.com/neon-bindings/neon) 123 | 124 | 官方介绍: 125 | 126 | > Rust bindings for writing safe and fast native Node.js modules. 127 | 128 | 使用方法: 129 | 130 | ```sh 131 | $ npm i neon-cli -g 132 | $ neon new neon-demo 133 | $ cd neon-demo 134 | $ tree . 135 | . 136 | ├── README.md 137 | ├── lib 138 | │ └── index.js 139 | ├── native 140 | │ ├── Cargo.toml 141 | │ ├── build.rs 142 | │ └── src 143 | │ └── lib.rs 144 | └── package.json 145 | 146 | 3 directories, 6 files 147 | $ npm i #触发 neon build 148 | $ node lib/index.js 149 | hello node 150 | ``` 151 | 152 | 接下来我们看看关键的代码文件。 153 | 154 | **lib/index.js** 155 | 156 | ```js 157 | var addon = require('../native'); 158 | console.log(addon.hello()); 159 | ``` 160 | 161 | **native/src/lib.rs** 162 | 163 | ```rust 164 | #[macro_use] 165 | extern crate neon; 166 | 167 | use neon::vm::{Call, JsResult}; 168 | use neon::js::JsString; 169 | 170 | fn hello(call: Call) -> JsResult { 171 | let scope = call.scope; 172 | Ok(JsString::new(scope, "hello node").unwrap()) 173 | } 174 | 175 | register_module!(m, { 176 | m.export("hello", hello) 177 | }); 178 | ``` 179 | 180 | **native/build.rs** 181 | 182 | ```rust 183 | extern crate neon_build; 184 | 185 | fn main() { 186 | neon_build::setup(); // must be called in build.rs 187 | 188 | // add project-specific build logic here... 189 | } 190 | ``` 191 | 192 | **native/Cargo.toml** 193 | 194 | ```toml 195 | [package] 196 | name = "neon-demo" 197 | version = "0.1.0" 198 | authors = ["nswbmw "] 199 | license = "MIT" 200 | build = "build.rs" 201 | 202 | [lib] 203 | name = "neon_demo" 204 | crate-type = ["dylib"] 205 | 206 | [build-dependencies] 207 | neon-build = "0.1.22" 208 | 209 | [dependencies] 210 | neon = "0.1.22" 211 | ``` 212 | 213 | 运行 `neon build` 会根据 native/Cargo.toml 中 build 字段指定的文件(这里是 build.rs)编译,并且生成的类型是 dylib(动态链接库)。native/src/lib.rs 存放了扩展的代码逻辑,通过 register_module 注册了一个 hello 方法,返回 hello node 字符串。 214 | 215 | 接下来我们测试一下原生 Node.js 和 Neon 编写的扩展运行斐波那契数列的执行效率对比。 216 | 217 | 修改对应文件如下: 218 | 219 | **native/src/lib.rs** 220 | 221 | ```rust 222 | #[macro_use] 223 | extern crate neon; 224 | 225 | use neon::vm::{Call, JsResult}; 226 | use neon::mem::Handle; 227 | use neon::js::JsInteger; 228 | 229 | fn fib(call: Call) -> JsResult { 230 | let scope = call.scope; 231 | let index: Handle = try!(try!(call.arguments.require(scope, 0)).check::()); 232 | let index: i32 = index.value() as i32; 233 | let result: i32 = fibonacci(index); 234 | Ok(JsInteger::new(scope, result)) 235 | } 236 | 237 | fn fibonacci(n: i32) -> i32 { 238 | match n { 239 | 1 | 2 => 1, 240 | _ => fibonacci(n - 1) + fibonacci(n - 2) 241 | } 242 | } 243 | 244 | register_module!(m, { 245 | m.export("fib", fib) 246 | }); 247 | ``` 248 | 249 | **lib/index.js** 250 | 251 | ```js 252 | const rust = require('../native') 253 | 254 | function fib (n) { 255 | if (n === 1 || n === 2) { 256 | return 1 257 | } 258 | return fib(n - 1) + fib(n - 2) 259 | } 260 | 261 | // js 262 | console.time('node') 263 | console.log(fib(40)) 264 | console.timeEnd('node') 265 | 266 | // rust 267 | console.time('rust') 268 | console.log(rust.fib(40)) 269 | console.timeEnd('rust') 270 | ``` 271 | 272 | 运行: 273 | 274 | ```sh 275 | $ neon build 276 | $ node lib/index.js 277 | 102334155 278 | node: 1030.681ms 279 | 102334155 280 | rust: 270.417ms 281 | ``` 282 | 283 | 接下来看一个复杂点的例子,用 Neon 编写一个 User 类,可传入一个含有 first_name 和 last_name 对象,暴露出一个 get_full_name 方法。 284 | 285 | 修改对应文件如下: 286 | 287 | **native/src/lib.rs** 288 | 289 | ```rust 290 | #[macro_use] 291 | extern crate neon; 292 | 293 | use neon::js::{JsFunction, JsString, Object, JsObject}; 294 | use neon::js::class::{Class, JsClass}; 295 | use neon::mem::Handle; 296 | use neon::vm::Lock; 297 | 298 | pub struct User { 299 | first_name: String, 300 | last_name: String, 301 | } 302 | 303 | declare_types! { 304 | pub class JsUser for User { 305 | init(call) { 306 | let scope = call.scope; 307 | let user = try!(try!(call.arguments.require(scope, 0)).check::()); 308 | let first_name: Handle = try!(try!(user.get(scope, "first_name")).check::()); 309 | let last_name: Handle = try!(try!(user.get(scope, "last_name")).check::()); 310 | 311 | Ok(User { 312 | first_name: first_name.value(), 313 | last_name: last_name.value(), 314 | }) 315 | } 316 | 317 | method get_full_name(call) { 318 | let scope = call.scope; 319 | let first_name = call.arguments.this(scope).grab(|user| { user.first_name.clone() }); 320 | let last_name = call.arguments.this(scope).grab(|user| { user.last_name.clone() }); 321 | Ok(try!(JsString::new_or_throw(scope, &(first_name + &last_name))).upcast()) 322 | } 323 | } 324 | } 325 | 326 | register_module!(m, { 327 | let class: Handle> = try!(JsUser::class(m.scope)); 328 | let constructor: Handle> = try!(class.constructor(m.scope)); 329 | try!(m.exports.set("User", constructor)); 330 | Ok(()) 331 | }); 332 | ``` 333 | 334 | **lib/index.js** 335 | 336 | ```js 337 | const rust = require('../native') 338 | const User = rust.User 339 | 340 | const user = new User({ 341 | first_name: 'zhang', 342 | last_name: 'san' 343 | }) 344 | 345 | console.log(user.get_full_name()) 346 | ``` 347 | 348 | 运行: 349 | 350 | ```sh 351 | $ neon build 352 | $ node lib/index.js 353 | zhangsan 354 | ``` 355 | 356 | ## [NAPI](https://nodejs.org/api/n-api.html) 357 | 358 | NAPI 是 node@8 新添加的用于原生模块开发的接口,相比较于以前的开发方式,NAPI 提供了稳定的 ABI 接口,消除了 Node.js 版本差异、引擎差异等编译后不兼容问题。 359 | 360 | 目前 NAPI 还处于试验阶段,所以相关资料并不多,笔者写了一个 demo 放到了 GitHub 上,这里直接 clone 下来运行: 361 | 362 | ```sh 363 | $ git clone https://github.com/nswbmw/rust-napi-demo 364 | ``` 365 | 366 | 主要文件代码如下: 367 | 368 | **src/lib.rs** 369 | 370 | ```rust 371 | #[macro_use] 372 | extern crate napi; 373 | #[macro_use] 374 | extern crate napi_derive; 375 | 376 | use napi::{NapiEnv, NapiNumber, NapiResult}; 377 | 378 | #[derive(NapiArgs)] 379 | struct Args<'a> { 380 | n: NapiNumber<'a> 381 | } 382 | 383 | fn fibonacci<'a>(env: &'a NapiEnv, args: &Args<'a>) -> NapiResult> { 384 | let number = args.n.to_i32()?; 385 | NapiNumber::from_i32(env, _fibonacci(number)) 386 | } 387 | 388 | napi_callback!(export_fibonacci, fibonacci); 389 | 390 | fn _fibonacci(n: i32) -> i32 { 391 | match n { 392 | 1 | 2 => 1, 393 | _ => _fibonacci(n - 1) + _fibonacci(n - 2) 394 | } 395 | } 396 | ``` 397 | 398 | **index.js** 399 | 400 | ```js 401 | const rust = require('./build/Release/example.node') 402 | 403 | function fib (n) { 404 | if (n === 1 || n === 2) { 405 | return 1 406 | } 407 | return fib(n - 1) + fib(n - 2) 408 | } 409 | 410 | // js 411 | console.time('node') 412 | console.log(fib(40)) 413 | console.timeEnd('node') 414 | 415 | // rust 416 | console.time('rust') 417 | console.log(rust.fibonacci(40)) 418 | console.timeEnd('rust') 419 | ``` 420 | 421 | 运行结果: 422 | 423 | ```sh 424 | $ npm start 425 | 102334155 426 | node: 1087.650ms 427 | 102334155 428 | rust: 268.395ms 429 | (node:33302) Warning: N-API is an experimental feature and could change at any time. 430 | ``` 431 | 432 | ## 参考链接 433 | 434 | - [https://github.com/neon-bindings/neon](https://github.com/neon-bindings/neon) 435 | - https://github.com/napi-rs/napi 436 | - [https://zhuanlan.zhihu.com/p/27650526](https://zhuanlan.zhihu.com/p/27650526) 437 | 438 | 上一节:[3.3 Node@8](https://github.com/nswbmw/node-in-debugging/blob/master/3.3%20Node%408.md) 439 | 440 | 下一节:[4.1 Source Map](https://github.com/nswbmw/node-in-debugging/blob/master/4.1%20Source%20Map.md) 441 | -------------------------------------------------------------------------------- /6.1 koa-await-breakpoint.md: -------------------------------------------------------------------------------- 1 | 日志打点一直是个调试最头疼的问题。如果直接在代码中插入埋点代码不仅侵入性强而且工作量大也不够灵活,如果能做到智能打点就好了,koa-await-breakpoint 正是你需要的。 2 | 3 | ## [koa-await-breakpoint](https://github.com/shimohq/koa-await-breakpoint) 4 | 5 | koa-await-breakpoint 是一个 Koa 的中间件,是一个在 routes/controllers 里(作用域包含 ctx)的 await 表达式前后自动打点的工具,不用插入一行日志打点代码,只需要在引入的时候配置一下,可以记录每个请求到来时 await 表达式前后的现场,如: 6 | 7 | 1. await 表达式所在的文件及行列号(filename) 8 | 2. await 表达式是执行的第几步(step) 9 | 3. await 表达式字符串形式(fn) 10 | 4. 执行 await 表达式所花费的毫秒(take) 11 | 5. 执行 await 表达式的结果(result) 12 | 6. 当前请求的 ctx 13 | 14 | 使用方法: 15 | 16 | ```js 17 | // On top of the main file 18 | const koaAwaitBreakpoint = require('koa-await-breakpoint')({ 19 | name: 'api', 20 | files: ['./routes/*.js'] 21 | }) 22 | 23 | const Koa = require('koa') 24 | const app = new Koa() 25 | 26 | // Generally, above other middlewares 27 | app.use(koaAwaitBreakpoint) 28 | ... 29 | 30 | app.listen(3000) 31 | ``` 32 | 33 | ## 实现原理 34 | 35 | 1. 重载 Module.prototype._compile,相当于 hack 了 require,如果发现是 require 了配置里指定的文件,则进行下一步,否则返回原始代码内容,相关源代码如下: 36 | ```js 37 | shimmer.wrap(Module.prototype, '_compile', function (__compile) { 38 | return function koaBreakpointCompile(content, filename) { 39 | if (!_.includes(filenames, filename)) { 40 | return __compile.call(this, content, filename); 41 | } 42 | ... 43 | }; 44 | }); 45 | ``` 46 | 47 | 2. 用 esprima 解析代码,生成 AST。如: 48 | ```js 49 | const Mongolass = require('mongolass') 50 | const mongolass = new Mongolass('mongodb://localhost:27017/test') 51 | const User = mongolass.model('users') 52 | 53 | exports.getUsers = async function getUsers(ctx) { 54 | await User.create({ 55 | name: 'xx', 56 | age: 18 57 | }) 58 | const users = await User.find() 59 | return users 60 | } 61 | ``` 62 | 会生成如下 AST,只截取了 `await User.create(...)` 相关的 AST: 63 | 64 | ```js 65 | Script { 66 | ... 67 | AwaitExpression { 68 | type: 'AwaitExpression', 69 | argument: 70 | CallExpression { 71 | type: 'CallExpression', 72 | callee: 73 | StaticMemberExpression { 74 | type: 'MemberExpression', 75 | computed: false, 76 | object: 77 | Identifier { 78 | type: 'Identifier', 79 | name: 'User', 80 | loc: { start: { line: 6, column: 10 }, end: { line: 6, column: 14 } } }, 81 | property: 82 | Identifier { 83 | type: 'Identifier', 84 | name: 'create', 85 | loc: { start: { line: 6, column: 15 }, end: { line: 6, column: 21 } } }, 86 | loc: { start: { line: 6, column: 10 }, end: { line: 6, column: 21 } } }, 87 | arguments: 88 | [ ObjectExpression { 89 | type: 'ObjectExpression', 90 | properties: 91 | [ Property { 92 | type: 'Property', 93 | key: 94 | Identifier { 95 | type: 'Identifier', 96 | name: 'name', 97 | loc: { start: { line: 7, column: 6 }, end: { line: 7, column: 10 } } }, 98 | computed: false, 99 | value: 100 | Literal { 101 | type: 'Literal', 102 | value: 'xx', 103 | raw: '\'xx\'', 104 | loc: { start: { line: 7, column: 12 }, end: { line: 7, column: 16 } } }, 105 | kind: 'init', 106 | method: false, 107 | shorthand: false, 108 | loc: { start: { line: 7, column: 6 }, end: { line: 7, column: 16 } } }, 109 | Property { 110 | type: 'Property', 111 | key: 112 | Identifier { 113 | type: 'Identifier', 114 | name: 'age', 115 | loc: { start: { line: 8, column: 6 }, end: { line: 8, column: 9 } } }, 116 | computed: false, 117 | value: 118 | Literal { 119 | type: 'Literal', 120 | value: 18, 121 | raw: '18', 122 | loc: { start: { line: 8, column: 11 }, end: { line: 8, column: 13 } } }, 123 | kind: 'init', 124 | method: false, 125 | shorthand: false, 126 | loc: { start: { line: 8, column: 6 }, end: { line: 8, column: 13 } } } ], 127 | loc: { start: { line: 6, column: 22 }, end: { line: 9, column: 5 } } } ], 128 | loc: { start: { line: 6, column: 10 }, end: { line: 9, column: 6 } } }, 129 | loc: { start: { line: 6, column: 4 }, end: { line: 9, column: 6 } } }, 130 | ... 131 | ``` 132 | 133 | 3. 遍历找到 awaitExpression 节点,进行以下包装后生成 AST 替换掉原来的节点。 134 | ```js 135 | global.logger( 136 | (typeof ctx !== 'undefined' ? ctx : this), 137 | function(){ 138 | return awaitExpression 139 | }, 140 | awaitExpressionString, 141 | filename 142 | ) 143 | ``` 144 | 相关源代码如下: 145 | ```js 146 | findAwaitAndWrapLogger(parsedCodes) 147 | try { 148 | content = escodegen.generate(parsedCodes, { 149 | format: { indent: { style: ' ' } }, 150 | sourceMap: filename, 151 | sourceMapWithCode: true 152 | }) 153 | } catch (e) { 154 | console.error('cannot generate code for file: %s', filename) 155 | console.error(e.stack) 156 | process.exit(1) 157 | } 158 | debug('file %s regenerate codes:\n%s', filename, content.code) 159 | ``` 160 | findAwaitAndWrapLogger 作用就是遍历 AST 将 awaitExpression 替换成用日志函数包裹后新的 awaitExpression 的 AST。最后用 escodegen 将 AST 生成代码(支持 soucemap,所以错误栈对应的行数是正确的)。 161 | 162 | **核心**:每个请求到来时,生成一个 requestId(可自定义,默认 uuid)挂载到 ctx 上,这样就可以通过 requestId 将日志串起来了。 163 | 164 | **特点**:可以记录每个请求的每一步(await 表达式)的现场及返回值,方便查日志。 165 | 166 | ## 举个栗子 167 | 168 | **app.js** 169 | 170 | ```js 171 | const koaAwaitBreakpoint = require('koa-await-breakpoint')({ 172 | name: 'api', 173 | files: ['./routes/*.js'] 174 | }) 175 | 176 | const Paloma = require('paloma') 177 | const app = new Paloma() 178 | const userRouter = require('./routes/user') 179 | 180 | app.use(koaAwaitBreakpoint) 181 | app.route({ method: 'GET', path: '/users', controller: userRouter.getUsers }) 182 | 183 | app.listen(3000) 184 | ``` 185 | 186 | **routes/user.js** 187 | 188 | ```js 189 | const Mongolass = require('mongolass') 190 | const mongolass = new Mongolass('mongodb://localhost:27017/test') 191 | const User = mongolass.model('users') 192 | 193 | exports.getUsers = async function getUsers (ctx) { 194 | await User.create({ 195 | name: 'xx', 196 | age: 18 197 | }) 198 | 199 | const users = await User.find() 200 | ctx.body = users 201 | } 202 | ``` 203 | 204 | 运行: 205 | 206 | ```sh 207 | $ DEBUG=koa-await-breakpoint node app.js 208 | ``` 209 | 210 | 终端打印出转换后的代码,routes/users.js 被转换成了: 211 | 212 | ```js 213 | const Mongolass = require('mongolass'); 214 | const mongolass = new Mongolass('mongodb://localhost:27017/test'); 215 | const User = mongolass.model('users'); 216 | exports.getUsers = async function getUsers(ctx) { 217 | await global.logger(typeof ctx !== 'undefined' ? ctx : this, function () { 218 | return User.create({ 219 | name: 'xx', 220 | age: 18 221 | }); 222 | }, 'User.create({\n name: \'xx\',\n age: 18\n})', '/Users/nswbmw/Desktop/test/routes/user.js:6:2'); 223 | const users = await global.logger(typeof ctx !== 'undefined' ? ctx : this, function () { 224 | return User.find(); 225 | }, 'User.find()', '/Users/nswbmw/Desktop/test/routes/user.js:11:16'); 226 | ctx.body = users; 227 | }; 228 | ``` 229 | 230 | 访问 localhost:3000/users,终端打印出: 231 | 232 | ```js 233 | {"name":"api","requestId":"50dbda0c-9e13-4659-acce-b237bc5178b7","timestamp":"2018-02-26T06:31:31.100Z","this":...,"type":"start","step":1,"take":0} 234 | {"name":"api","requestId":"50dbda0c-9e13-4659-acce-b237bc5178b7","step":2,"filename":"/Users/nswbmw/Desktop/test/routes/user.js:6:2","timestamp":"2018-02-26T06:31:31.104Z","this":...,"type":"beforeAwait","fn":"User.create({\n name: 'xx',\n age: 18\n})","take":4} 235 | {"name":"api","requestId":"50dbda0c-9e13-4659-acce-b237bc5178b7","step":3,"filename":"/Users/nswbmw/Desktop/test/routes/user.js:6:2","timestamp":"2018-02-26T06:31:31.175Z","this":...,"type":"afterAwait","fn":"User.create({\n name: 'xx',\n age: 18\n})","result":{"result":{"ok":1,"n":1},"ops":[{"name":"xx","age":18,"_id":"5a93a9c3cf8c8797c9b47482"}],"insertedCount":1,"insertedIds":["5a93a9c3cf8c8797c9b47482"]},"take":71} 236 | {"name":"api","requestId":"50dbda0c-9e13-4659-acce-b237bc5178b7","step":4,"filename":"/Users/nswbmw/Desktop/test/routes/user.js:11:16","timestamp":"2018-02-26T06:31:31.175Z","this":...,"type":"beforeAwait","fn":"User.find()","take":0} 237 | {"name":"api","requestId":"50dbda0c-9e13-4659-acce-b237bc5178b7","step":5,"filename":"/Users/nswbmw/Desktop/test/routes/user.js:11:16","timestamp":"2018-02-26T06:31:31.180Z","this":...,"type":"afterAwait","fn":"User.find()","result":[{"_id":"5a93a9c3cf8c8797c9b47482","name":"xx","age":18}],"take":5} 238 | {"name":"api","requestId":"50dbda0c-9e13-4659-acce-b237bc5178b7","timestamp":"2018-02-26T06:31:31.181Z","this":...,"type":"end","step":6,"take":1} 239 | ``` 240 | 241 | **注意**:type 是以下其中一种,take 单位是 ms。 242 | 243 | 1. start:请求到来时第一次打点 244 | 2. beforeAwait:上一个 awaitExpression 之后到这一个 awaitExpression 之前 245 | 3. afterAwait:这个 awaitExpression 开始到结束 246 | 4. error:错误日志,包含了错误信息 247 | 5. end:请求结束时打点 248 | 249 | ## koa-await-breakpoint 自定义日志存储 250 | 251 | store 参数最好自己定义(默认打印日志到 stdout),该参数是一个对象并且有一个 save 方法即可。在 save 方法内可做一些逻辑修改或者日志策略,比如: 252 | 253 | 1. 添加日志标识(如:name)方便区分不同服务的日志 254 | 2. 错误日志时,添加一些额外字段方便追踪现场 255 | 3. 将日志发送到 Logstash 或其他日志服务 256 | 4. 限制日志频率,比如:只有响应时间大于 500ms 的请求日志才会记录 257 | 258 | **koa_await_breakpoint_store.js** 259 | 260 | ```js 261 | exports.save = function save(record, ctx) { 262 | record.name = 'app name' 263 | record.env = process.env.NODE_ENV 264 | 265 | if (record.error) { 266 | record.error = { 267 | message: record.error.message, 268 | stack: record.error.stack, 269 | status: record.error.status || record.error.statusCode || 500 270 | } 271 | } 272 | ... 273 | logstash.send(record) 274 | } 275 | ``` 276 | 277 | 上一节:[5.2 Elastic APM](https://github.com/nswbmw/node-in-debugging/blob/master/5.2%20Elastic%20APM.md) 278 | 279 | 下一节:[6.2 async_hooks](https://github.com/nswbmw/node-in-debugging/blob/master/6.2%20async_hooks.md) 280 | -------------------------------------------------------------------------------- /4.5 supervisor-hot-reload.md: -------------------------------------------------------------------------------- 1 | 我们在本地开发 Node.js 程序时通常会使用 [nodemon](https://github.com/remy/nodemon) 或者 [supervisor](https://github.com/petruisfan/node-supervisor) 这种进程管理工具,当有文件修改时自动重启应用。小项目还好,项目大了每次重启应用都用几秒到十几秒的时间,大部分时间花在了加载及编译代码上。 2 | 3 | 这让我联想到前端比较火的一个名词——Hot Reload(热加载),比如 React 静态资源的热加载通过 webpack-dev-server 和 react-hot-loader 实现,webpack-dev-server 负责重新编译代码,react-hot-loader 负责热加载。 4 | 5 | 那在 Node.js 应用中,如何实现 Hot Reload 呢?最好能实现不重启应用使新代码生效。幸好 ES6 引入了一个黑(xin)魔(te)法(xing)——Proxy,Proxy 用于修改对象的默认行为,等同于在语言层面做出修改,属于一种 “元编程”。Proxy 在要访问的对象之前架设一层拦截,要访问该对象成员必须先经过这层拦截。示例代码: 6 | 7 | ```js 8 | const obj = new Proxy({}, { 9 | get: function (target, key) { 10 | console.log(`getting ${key}!`) 11 | return 'haha' 12 | } 13 | }) 14 | 15 | console.log(obj.name) 16 | // getting name! 17 | // haha 18 | console.log(obj.age) 19 | // getting age! 20 | // haha 21 | ``` 22 | 23 | **可以看出**:我们并没有在 obj 上定义 name 和 age 属性,所有获取 obj 上属性都会执行 get 方法然后打印 getting xxx! 和返回 haha。 24 | 25 | 这里 Proxy 的第一个参数是一个空对象,也可以是一个其他的对象,比如函数(毕竟 js 中函数也是对象)。 26 | 27 | ```js 28 | function user () {} 29 | 30 | const obj = new Proxy(user, { 31 | get: function (target, key) { 32 | console.log(`getting ${key}!`) 33 | return 'haha' 34 | } 35 | }) 36 | 37 | console.log(user.name) 38 | // user 39 | console.log(user.age) 40 | // undefined 41 | console.log(obj.name) 42 | // getting name! 43 | // haha 44 | console.log(obj.age) 45 | // getting age! 46 | // haha 47 | new Proxy(1, {}) 48 | // TypeError: Cannot create proxy with a non-object as target or handler 49 | ``` 50 | 51 | ## Proxy 实现 Hot Reload 52 | 53 | **核心原理**:使用 Proxy 将模块导出的对象包装一层『代理』,即 module.exports 导出的是一个 Proxy 实例,定义一个 get 方法,使得获取实例上的属性其实是去获取最新的 require.cache 中的对象上的属性。同时,监听代码文件,如果有修改,则更新 require.cache。 54 | 55 | **简言之**:我们获取对象属性时,中间加了一层代理,通过代理间接获取原有属性的值,如果属性值有更新会更新 require.cache 的缓存,那么下次获取对象属性时,通过代理将获取该属性最新的值。可见,Proxy 可以实现属性访问拦截,也可实现断开 "强引用" 的作用。 56 | 57 | 笔者发布了一个 [proxy-hot-reload](https://www.npmjs.com/package/proxy-hot-reload) 模块,核心代码如下: 58 | 59 | ```js 60 | module.exports = function proxyHotReload(opts) { 61 | const includes = [ ... ] 62 | const excludes = [ ... ] 63 | const filenames = _.difference(includes, excludes) 64 | 65 | chokidar 66 | .watch(filenames, { 67 | usePolling: true 68 | }) 69 | .on('change', (path) => { 70 | try { 71 | if (require.cache[path]) { 72 | const _exports = require.cache[path].exports 73 | if (_.isPlainObject(_exports) && !_.isEmpty(_exports)) { 74 | delete require.cache[path] 75 | require(path) 76 | } 77 | } 78 | } catch (e) { ... } 79 | }) 80 | .on('error', (error) => console.error(error)) 81 | 82 | shimmer.wrap(Module.prototype, '_compile', function (__compile) { 83 | return function proxyHotReloadCompile(content, filename) { 84 | if (!_.includes(filenames, filename)) { 85 | try { 86 | return __compile.call(this, content, filename) 87 | } catch (e) { ... } 88 | } else { 89 | const result = __compile.call(this, content, filename) 90 | this._exports = this.exports 91 | // non-object return original compiled code 92 | if (!_.isPlainObject(this._exports)) { 93 | return result 94 | } 95 | try { 96 | this.exports = new Proxy(this._exports, { 97 | get: function (target, key, receiver) { 98 | try { 99 | if (require.cache[filename]) { 100 | return require.cache[filename]._exports[key] 101 | } else { 102 | return Reflect.get(target, key, receiver) 103 | } 104 | } catch (e) { ... } 105 | } 106 | }) 107 | } catch (e) { ... } 108 | } 109 | } 110 | }) 111 | } 112 | ``` 113 | 114 | 简单讲解一下: 115 | 116 | 1. 可传入 includes 和 excludes 参数,支持 glob 写法,用来设置监听哪些代码文件 117 | 2. 用 chokidar 模块监听文件,如有改动则重新加载该文件。这里只针对 module.exports 导出的是纯对象的模块有用,做这个限制的原因是:非对象比如函数,一般我们导出一个函数会直接调用执行而不是获取函数上的属性或方法,这种导出非纯对象模块即使重建缓存也不会生效,所以干脆忽略。幸运的是,module.exports 导出对象占了大多数场景。 118 | 3. 用 shimmer 模块重载 Module.prototype._compile 方法,如果是被监听的文件并且导出的是纯对象,则尝试将导出的对象包装成 Proxy 实例。这样,获取该对象上的属性时,将从 require.cache 中读取最新的值。 119 | 120 | 使用示例: 121 | 122 | **user.js** 123 | 124 | ```js 125 | module.exports = { 126 | id: 1, 127 | name: 'nswbmw' 128 | } 129 | ``` 130 | 131 | **app.js** 132 | 133 | ```js 134 | if (process.env.NODE_ENV !== 'production') { 135 | require('proxy-hot-reload')({ 136 | includes: '**/*.js' 137 | }) 138 | } 139 | 140 | const Paloma = require('paloma') 141 | const app = new Paloma() 142 | const user = require('./user') 143 | 144 | app.route({ method: 'GET', path: '/', controller (ctx) { 145 | ctx.body = user 146 | }}) 147 | 148 | app.listen(3000) 149 | ``` 150 | 151 | 浏览器访问 localhost:3000 查看结果,修改 user.js 中字段的值,然后刷新浏览器查看结果。 152 | 153 | proxy-hot-reload 有个非常明显的**缺点**:只支持对导出的是纯对象的文件做代理,而且程序入口文件不会生效,比如上面的 app.js,改个端口号只能重启才会生效。Proxy 再怎么黑魔法也只能做到这个地步了,退一步想,如果修改了 proxy-hot-reload 覆盖不到的文件(如 app.js)降级成自动重启就好了,如果 proxy-hot-reload 和 supervisor 结合会怎么样呢? 154 | 155 | ## [supervisor-hot-reload](https://github.com/nswbmw/supervisor-hot-reload) 156 | 157 | 如果要将 proxy-hot-reload 结合 supervisor,需要解决几个难点: 158 | 159 | 1. 非侵入式。即代码里不再写: 160 | 161 | ```js 162 | if (process.env.NODE_ENV !== 'production') { 163 | require('proxy-hot-reload')({ 164 | includes: '**/*.js' 165 | }) 166 | } 167 | ``` 168 | 169 | 2. 参数统一。supervisor 可接受 -w 参数表明监听哪些文件,-i 参数表明忽略哪些文件,这两个参数怎么跟 proxy-hot-reload 的 includes 和 excludes 参数整合 170 | 171 | 3. 职责分明。代码文件修改,优先尝试 proxy-hot-reload 的热更新,如果 proxy-hot-reload 热更新不了则使用 supervisor 重启 172 | 173 | 首先我们去看下 supervisor 的源码(lib/supervisor.js),源码中有这么一段: 174 | 175 | ```js 176 | var watchItems = watch.split(','); 177 | watchItems.forEach(function (watchItem) { 178 | watchItem = path.resolve(watchItem); 179 | 180 | if ( ! ignoredPaths[watchItem] ) { 181 | log("Watching directory '" + watchItem + "' for changes."); 182 | if(interactive) { 183 | log("Press rs for restarting the process."); 184 | } 185 | findAllWatchFiles(watchItem, function(f) { 186 | watchGivenFile( f, poll_interval ); 187 | }); 188 | } 189 | }); 190 | ``` 191 | 192 | 这段代码的作用是:遍历找到所有需要监听的文件,然后调用 watchGivenFile 监听文件。watchGivenFile 代码如下: 193 | 194 | ```js 195 | function watchGivenFile (watch, poll_interval) { 196 | if (isWindowsWithoutWatchFile || forceWatchFlag) { 197 | fs.watch(watch, { persistent: true, interval: poll_interval }, crashWin); 198 | } else { 199 | fs.watchFile(watch, { persistent: true, interval: poll_interval }, function(oldStat, newStat) { 200 | // we only care about modification time, not access time. 201 | if ( newStat.mtime.getTime() !== oldStat.mtime.getTime() ) { 202 | if (verbose) { 203 | log("file changed: " + watch); 204 | } 205 | } 206 | crash(); 207 | }); 208 | } 209 | if (verbose) { 210 | log("watching file '" + watch + "'"); 211 | } 212 | } 213 | ``` 214 | 215 | watchGivenFile 的作用是:用 fs.watch/fs.watchFile 监听文件,如果有改动则调用 crashWin/crash 程序退出。supervisor 用 child_process.spawn 将程序运行在子进程,子进程退出后会被 supervisor 重新启动。相关代码如下: 216 | 217 | ```js 218 | function startProgram (prog, exec) { 219 | var child = exports.child = spawn(exec, prog, {stdio: 'inherit'}); 220 | ... 221 | child.addListener("exit", function (code) { 222 | ... 223 | startProgram(prog, exec); 224 | }); 225 | } 226 | ``` 227 | 228 | 大体理清 supervisor 的关键源码后,我们就知道如何解决上面提到的几个难点了。 229 | 230 | 首先需要修改 proxy-hot-reload,添加几个功能: 231 | 232 | 1. 添加 includeFiles 和 excludeFiles 选项,值为数组,用来接受 supervisor 传来的文件列表 233 | 2. 添加 watchedFileChangedButNotReloadCache 参数。proxy-hot-reload 可以知道哪些代码文件可以热更新,哪些不可以。当监听到不能热更新的文件有修改时,调用这个 watchedFileChangedButNotReloadCache 函数,这个函数里有 process.exit() 让进程退出 234 | 235 | 难点及解决方案: 236 | 237 | 1. 非侵入式。因为真正的程序试运行在 supervisor 创建的子进程中,所以我们无法在 supervisor 进程中引入 proxy-hot-reload,只能通过子进程用 `node -r xxx` 提前引入并覆盖 Module.prototype._compile。解决方案:将 supervisor 需要监听的文件数组(watchFiles)和 proxy-hot-reload 配置写到一个文件(如:proxy-hot-reload.js)里,子进程通过 `node -r proxy-hot-reload.js app.js` 预加载此文件启动。 238 | 239 | supervisor 相关代码: 240 | 241 | ```js 242 | // 获取 watchFiles 243 | fs.writeFileSync(path.join(__dirname, 'proxy-hot-reload.js'), ` 244 | require('${path.join(__dirname, "..", "node_modules", "proxy-hot-reload")}')({ 245 | includeFiles: ${JSON.stringify(watchFiles)}, 246 | excludeFiles: [], 247 | watchedFileChangedButNotReloadCache: function (filename) { 248 | console.log(filename + ' changed, restarting...'); 249 | setTimeout(function () { 250 | process.exit(); 251 | }, ${poll_interval}); 252 | } 253 | });`); 254 | // startChildProcess() 255 | ``` 256 | 257 | 2. 参数统一。将上面 watchItems.forEach 内异步遍历需要监听的文件列表修改为同步,代码如下: 258 | 259 | ```js 260 | var watchFiles = [] 261 | var watchItems = watch.split(','); 262 | watchItems.forEach(function (watchItem) { 263 | watchItem = path.resolve(watchItem); 264 | if ( ! ignoredPaths[watchItem] ) { 265 | log("Watching directory '" + watchItem + "' for changes."); 266 | if(interactive) { 267 | log("Press rs for restarting the process."); 268 | } 269 | findAllWatchFiles(watchItem, function(f) { 270 | watchFiles.push(f) 271 | // watchGivenFile( f, poll_interval ); 272 | }); 273 | } 274 | }); 275 | ``` 276 | 277 | **注意:**这里 findAllWatchFiles 虽然有回调函数,但是同步的。将 findAllWatchFiles 内的 fs.lstat/fs.stat/fs.readdir 分别改为 fs.lstatSync/fs.statSync/fs.readdirSync,这里就不贴代码了。 278 | 279 | 3. 职责分明。子进程使用 `node -r proxy-hot-reload.js app.js` 启动后,能热更新的则热更新,不能热更新的执行 watchedFileChangedButNotReloadCache,子进程退出,supervisor 会启动一个新的子进程,实现了职责分明。 280 | 281 | 我将改进后的 supervisor 发布成一个新的包——[supervisor-hot-reload](https://github.com/nswbmw/supervisor-hot-reload) 。使用方法: 282 | 283 | **user.js** 284 | 285 | ```js 286 | module.exports = { 287 | id: 1, 288 | name: 'nswbmw' 289 | } 290 | ``` 291 | 292 | **app.js** 293 | 294 | ```js 295 | const Paloma = require('paloma') 296 | const app = new Paloma() 297 | const user = require('./user') 298 | 299 | app.route({ method: 'GET', path: '/', controller (ctx) { 300 | ctx.body = user 301 | }}) 302 | 303 | app.listen(3000) 304 | ``` 305 | 306 | 全局安装并使用 supervisor-hot-reload: 307 | 308 | ```sh 309 | $ npm i supervisor-hot-reload -g 310 | $ DEBUG=proxy-hot-reload supervisor-hot-reload app.js 311 | ``` 312 | 313 | 修改 user.js,程序不会重启,打印: 314 | 315 | ``` 316 | proxy-hot-reload Reload file: /Users/nswbmw/Desktop/test/user.js 317 | ``` 318 | 319 | 修改 app.js,程序会重启,打印: 320 | 321 | ``` 322 | /Users/nswbmw/Desktop/test/app.js changed, restarting... 323 | Program node app.js exited with code 0 324 | 325 | Starting child process with 'node app.js' 326 | ... 327 | ``` 328 | 329 | 上一节:[4.4 debug + repl2 + power-assert](https://github.com/nswbmw/node-in-debugging/blob/master/4.4%20debug%20%2B%20repl2%20%2B%20power-assert.md) 330 | 331 | 下一节:[5.1 NewRelic](https://github.com/nswbmw/node-in-debugging/blob/master/5.1%20NewRelic.md) 332 | -------------------------------------------------------------------------------- /3.2 Error Stack.md: -------------------------------------------------------------------------------- 1 | JavaScript 中的 Error 想必大家都很熟悉了,毕竟天天与它打交道。 2 | 3 | Node.js 内置的 Error 类型有: 4 | 5 | 1. [Error](https://nodejs.org/api/errors.html%23errors_class_error):通用的错误类型,如:`new Error('error!!!')` 6 | 2. [SyntaxError](https://nodejs.org/api/errors.html%23errors_class_syntaxerror):语法错误,如:`require('vm').runInThisContext('binary ! isNotOk')` 7 | 3. [ReferenceError](https://nodejs.org/api/errors.html%23errors_class_referenceerror):引用错误,如引用一个未定义的变量,如:`doesNotExist` 8 | 4. [TypeError](https://nodejs.org/api/errors.html%23errors_class_typeerror):类型错误,如:`require('url').parse(() => { })` 9 | 5. [URIError](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError):全局的 URI 处理函数抛出的错误,如:`encodeURI('\uD800')` 10 | 6. [AssertError](https://nodejs.org/api/errors.html%23errors_class_assertionerror):使用 assert 模块时抛出的错误,如:`assert(false)` 11 | 12 | 每个 Error 对象通常有 name、message、stack、constructor 等属性。当程序抛出异常,我们需要根据错误栈(error.stack)定位到出错代码,错误栈这块还是有许多学问在里面的,希望本文能够帮助读者理解并玩转错误栈,写出错误栈清晰的代码,方便调试。 13 | 14 | ## Stack Trace 15 | 16 | 错误栈本质上就是调用栈(或者叫:堆栈追踪)。所以我们先复习下 JavaScript 中调用栈的概念。 17 | 18 | **调用栈**:每当有一个函数调用,就会将其压入栈顶,在调用结束的时候再将其从栈顶移出。 19 | 20 | 来看一段代码: 21 | 22 | ```js 23 | function c () { 24 | console.log('c') 25 | console.trace() 26 | } 27 | 28 | function b () { 29 | console.log('b') 30 | c() 31 | } 32 | 33 | function a () { 34 | console.log('a') 35 | b() 36 | } 37 | 38 | a() 39 | ``` 40 | 41 | 执行后打印出: 42 | 43 | ```js 44 | a 45 | b 46 | c 47 | Trace 48 | at c (/Users/nswbmw/Desktop/test/app.js:3:11) 49 | at b (/Users/nswbmw/Desktop/test/app.js:8:3) 50 | at a (/Users/nswbmw/Desktop/test/app.js:13:3) 51 | at Object. (/Users/nswbmw/Desktop/test/app.js:16:1) 52 | at ... 53 | ``` 54 | 55 | **可以看出**:c 函数中 console.trace() 打印出的堆栈追踪依次为 c->b->a,即 a 调用了 b,b 调用了 c。 56 | 57 | 稍微修改下上面的例子: 58 | 59 | ```js 60 | function c () { 61 | console.log('c') 62 | } 63 | 64 | function b () { 65 | console.log('b') 66 | c() 67 | console.trace() 68 | } 69 | 70 | function a () { 71 | console.log('a') 72 | b() 73 | } 74 | 75 | a() 76 | ``` 77 | 78 | 执行后打印出: 79 | 80 | ``` 81 | a 82 | b 83 | c 84 | Trace 85 | at b (/Users/nswbmw/Desktop/test/app.js:8:11) 86 | at a (/Users/nswbmw/Desktop/test/app.js:13:3) 87 | at Object. (/Users/nswbmw/Desktop/test/app.js:16:1) 88 | at ... 89 | ``` 90 | 91 | **可以看出**:c() 在 console.trace() 之前执行完毕,从栈中移除,所以栈中从上往下为 b->a。 92 | 93 | 上面示例的代码过于简单,实际情况下错误栈并没有这么直观。就拿常用的 [mongoose](https://www.npmjs.com/package/mongoose) 举例,mongoose 的错误栈并不友好。 94 | 95 | ```js 96 | const mongoose = require('mongoose') 97 | const Schema = mongoose.Schema 98 | mongoose.connect('mongodb://localhost/test') 99 | 100 | const UserSchema = new Schema({ 101 | id: mongoose.Schema.Types.ObjectId 102 | }) 103 | const User = mongoose.model('User', UserSchema) 104 | User 105 | .create({ id: 'xxx' }) 106 | .then(console.log) 107 | .catch(console.error) 108 | ``` 109 | 110 | 运行后打印出: 111 | 112 | ```js 113 | { ValidationError: User validation failed: id: Cast to ObjectID failed for value "xxx" at path "id" 114 | at ValidationError.inspect (/Users/nswbmw/Desktop/test/node_modules/mongoose/lib/error/validation.js:56:24) 115 | at ... 116 | errors: 117 | { id: 118 | { CastError: Cast to ObjectID failed for value "xxx" at path "id" 119 | at new CastError (/Users/nswbmw/Desktop/test/node_modules/mongoose/lib/error/cast.js:27:11) 120 | at model.$set (/Users/nswbmw/Desktop/test/node_modules/mongoose/lib/document.js:792:7) 121 | at ... 122 | message: 'Cast to ObjectID failed for value "xxx" at path "id"', 123 | name: 'CastError', 124 | stringValue: '"xxx"', 125 | kind: 'ObjectID', 126 | value: 'xxx', 127 | path: 'id', 128 | reason: [Object] } }, 129 | _message: 'User validation failed', 130 | name: 'ValidationError' } 131 | ``` 132 | 133 | 从 mongoose 给出的 error.stack 中看不到任何有用的信息,error.message 告诉我们 "xxx" 不匹配 User 这个 Model 的 id(ObjectID)的类型,其他的字段基本也是这个结论的补充,却没有给出我们最关心的问题:**我写的代码中,哪一行出问题了?** 134 | 135 | 如何解决这个问题呢?我们先看看 Error.captureStackTrace 的用法。 136 | 137 | ## Error.captureStackTrace 138 | 139 | Error.captureStackTrace 是 Node.js 提供的一个 api,可以传入两个参数: 140 | 141 | ```js 142 | Error.captureStackTrace(targetObject[, constructorOpt]) 143 | ``` 144 | 145 | Error.captureStackTrace 会在 targetObject 中添加一个 stack 属性。对该属性进行访问时,将以字符串的形式返回 Error.captureStackTrace() 语句被调用时的代码位置信息(即:调用栈历史)。 146 | 147 | 举个简单的例子: 148 | 149 | ```js 150 | const myObject = {} 151 | Error.captureStackTrace(myObject) 152 | console.log(myObject.stack) 153 | // 输出 154 | Error 155 | at Object. (/Users/nswbmw/Desktop/test/app.js:2:7) 156 | at ... 157 | ``` 158 | 159 | 除了 targetObject,captureStackTrace 还接受一个类型为 function 的可选参数 constructorOpt,当传递该参数时,调用栈中所有 constructorOpt 函数之上的信息(包括 constructorOpt 函数自身),都会在访问 targetObject.stack 时被忽略。当需要对终端用户隐藏内部的实现细节时,constructorOpt 参数会很有用。传入第二个参数通常用于自定义错误,如: 160 | 161 | ```js 162 | function MyError() { 163 | Error.captureStackTrace(this, MyError) 164 | this.name = this.constructor.name 165 | this.message = 'you got MyError' 166 | } 167 | 168 | const myError = new MyError() 169 | console.log(myError) 170 | console.log(myError.stack) 171 | // 输出 172 | MyError { name: 'MyError', message: 'you got MyError' } 173 | Error 174 | at Object. (/Users/nswbmw/Desktop/test/app.js:7:17) 175 | at ... 176 | ``` 177 | 178 | 如果去掉 captureStackTrace 第二个参数: 179 | 180 | ```js 181 | function MyError() { 182 | Error.captureStackTrace(this) 183 | this.name = this.constructor.name 184 | this.message = 'you got MyError' 185 | } 186 | 187 | const myError = new MyError() 188 | console.log(myError) 189 | console.log(myError.stack) 190 | // 输出 191 | MyError { name: 'MyError', message: 'you got MyError' } 192 | Error 193 | at new MyError (/Users/nswbmw/Desktop/test/app.js:2:9) 194 | at Object. (/Users/nswbmw/Desktop/test/app.js:7:17) 195 | at ... 196 | ``` 197 | 198 | **可以看出**:出现了 MyError 相关的调用栈,但我们并不关心 MyError 及其内部是如何实现的。 199 | 200 | captureStackTrace 第二个参数可以传入其他函数,不一定是当前函数,如: 201 | 202 | ```js 203 | const myObj = {} 204 | 205 | function c () { 206 | Error.captureStackTrace(myObj, b) 207 | } 208 | 209 | function b () { 210 | c() 211 | } 212 | 213 | function a () { 214 | b() 215 | } 216 | 217 | a() 218 | console.log(myObj.stack) 219 | // 输出 220 | Error 221 | at a (/Users/nswbmw/Desktop/test/app.js:12:3) 222 | at Object. (/Users/nswbmw/Desktop/test/app.js:15:1) 223 | at ... 224 | ``` 225 | 226 | **可以看出**:captureStackTrace 第二个参数传入了函数 b,调用栈中隐藏了 b 函数及其以上所有的堆栈帧。 227 | 228 | 讲到这相信读者都明白了 captureStackTrace 的用法。但这具体有什么用呢?其实上面提到了:**隐藏内部实现细节,优化错误栈**。 229 | 230 | 下面我以自己写的一个模块——[Mongolass](https://github.com/mongolass/mongolass) 为例,讲讲如何应用 captureStackTrace。 231 | 232 | > [Mongolass](https://github.com/mongolass/mongolass) 是一个轻量且优雅的连接 MongoDB 的模块。 233 | 234 | ## captureStackTrace 在 Mongolass 中的应用 235 | 236 | 先大体讲下 Mongolass 的用法。Mongolass 跟 Mongoose 类似,有 Model 的概念,Model 上挂载的方法对应对 MongoDB 的 collections 的操作,如:`User.insert`。User 是一个 Model 实例,`User.insert` 方法返回的是一个 Query 实例。Query 代码如下: 237 | 238 | ```js 239 | class Query { 240 | constructor(op, args) { 241 | Error.captureStackTrace(this, this.constructor); 242 | ... 243 | } 244 | } 245 | ``` 246 | 247 | 这里用 Error.captureStackTrace 隐藏了 Query 内部的错误栈细节,但这样带来一个问题:丢失了原来的 error.stack,Mongolass 中可以自定义插件,而插件函数的执行是在 Query 内部,假如插件中抛错,则会丢失相关错误栈信息。 248 | 249 | 如何弥补呢?Mongolass 的做法是,当 Query 内部抛出错误(error)时,截取有用的 error.stack,然后拼接到 Query 实例通过 Error.captureStackTrace 生成的 stack 上。 250 | 251 | 来看一段 Mongolass 的代码: 252 | 253 | ```js 254 | const Mongolass = require('mongolass') 255 | const Schema = Mongolass.Schema 256 | const mongolass = new Mongolass('mongodb://localhost:27017/test') 257 | 258 | const UserSchema = new Schema('UserSchema', { 259 | name: { type: 'string' }, 260 | age: { type: 'number' } 261 | }) 262 | const User = mongolass.model('User', UserSchema) 263 | 264 | User 265 | .insertOne({ name: 'nswbmw', age: 'wrong age' }) 266 | .exec() 267 | .then(console.log) 268 | .catch(console.error) 269 | ``` 270 | 271 | 运行后打印的错误信息如下: 272 | 273 | ```js 274 | { TypeError: ($.age: "wrong age") ✖ (type: number) 275 | at Model.insertOne (/Users/nswbmw/Desktop/test/node_modules/mongolass/lib/query.js:104:16) 276 | at Object. (/Users/nswbmw/Desktop/test/app.js:12:4) 277 | at ... 278 | validator: 'type', 279 | actual: 'wrong age', 280 | expected: { type: 'number' }, 281 | path: '$.age', 282 | schema: 'UserSchema', 283 | model: 'User', 284 | op: 'insertOne', 285 | args: [ { name: 'nswbmw', age: 'wrong age' } ], 286 | pluginName: 'MongolassSchema', 287 | pluginOp: 'beforeInsertOne', 288 | pluginArgs: [] } 289 | ``` 290 | 291 | **可以看出**:app.js 第 12 行的 insertOne 报错,报错原因是 age 字段是字符串 "wrong age",而我们期望的是 number 类型的值。 292 | 293 | ## Error.prepareStackTrace 294 | 295 | V8 还暴露了另外一个接口——Error.prepareStackTrace。简单讲,这个函数的作用就是:**定制 stack**。 296 | 297 | 用法如下: 298 | 299 | ```js 300 | Error.prepareStackTrace(error, structuredStackTrace) 301 | ``` 302 | 303 | 第一个参数是个 Error 对象,第二个参数是一个数组,每一项是一个 CallSite 对象,包含错误的函数名、行数等信息。对比以下两种代码: 304 | 305 | 正常的 throw error: 306 | 307 | ```js 308 | function c () { 309 | throw new Error('error!!!') 310 | } 311 | 312 | function b () { 313 | c() 314 | } 315 | 316 | function a () { 317 | b() 318 | } 319 | 320 | try { 321 | a() 322 | } catch (e) { 323 | console.log(e.stack) 324 | } 325 | // 输出 326 | Error: error!!! 327 | at c (/Users/nswbmw/Desktop/test/app.js:2:9) 328 | at b (/Users/nswbmw/Desktop/test/app.js:6:3) 329 | at a (/Users/nswbmw/Desktop/test/app.js:10:3) 330 | at Object. (/Users/nswbmw/Desktop/test/app.js:14:3) 331 | at ... 332 | ``` 333 | 334 | 使用 Error.prepareStackTrace 格式化 stack: 335 | 336 | ```js 337 | Error.prepareStackTrace = function (error, callSites) { 338 | return error.toString() + '\n' + callSites.map(callSite => { 339 | return ' -> ' + callSite.getFunctionName() + ' (' 340 | + callSite.getFileName() + ':' 341 | + callSite.getLineNumber() + ':' 342 | + callSite.getColumnNumber() + ')' 343 | }).join('\n') 344 | } 345 | 346 | function c () { 347 | throw new Error('error!!!') 348 | } 349 | 350 | function b () { 351 | c() 352 | } 353 | 354 | function a () { 355 | b() 356 | } 357 | 358 | try { 359 | a() 360 | } catch (e) { 361 | console.log(e.stack) 362 | } 363 | // 输出 364 | Error: error!!! 365 | -> c (/Users/nswbmw/Desktop/test/app.js:11:9) 366 | -> b (/Users/nswbmw/Desktop/test/app.js:15:3) 367 | -> a (/Users/nswbmw/Desktop/test/app.js:19:3) 368 | -> null (/Users/nswbmw/Desktop/test/app.js:23:3) 369 | -> ... 370 | ``` 371 | 372 | **可以看出**:我们自定义了一个 Error.prepareStackTrace 格式化了 stack 并打印出来。 373 | 374 | CallSite 对象还有许多 api,如:getThis、getTypeName、getFunction、getFunctionName、getMethodName、getFileName、getLineNumber、getColumnNumber、getEvalOrigin、isToplevel、isEval、isNative、isConstructor,这里不一一介绍,有兴趣的读者可查看参考链接。 375 | 376 | Error.prepareStackTrace 使用时需要注意两点: 377 | 378 | 1. 这个方法是 V8 暴露出来的,所以只能在基于 V8 的 Node.js 或者 Chrome 里才能使用 379 | 2. 这个方法会修改全局 Error 的行为 380 | 381 | ## Error.prepareStackTrace 另类用法 382 | 383 | Error.prepareStackTrace 除了格式化错误栈外还有什么作用呢?[sindresorhus](https://github.com/sindresorhus) 大神还写了一个 [callsites](https://github.com/sindresorhus/callsites) 的模块,可以用来获取函数调用相关的信息。如获取执行该函数所在的文件名: 384 | 385 | ```js 386 | const callsites = require('callsites') 387 | 388 | function getFileName() { 389 | console.log(callsites()[0].getFileName()) 390 | //=> '/Users/nswbmw/Desktop/test/app.js' 391 | } 392 | 393 | getFileName() 394 | ``` 395 | 396 | 我们来看下源代码: 397 | 398 | ```js 399 | module.exports = () => { 400 | const _ = Error.prepareStackTrace 401 | Error.prepareStackTrace = (_, stack) => stack 402 | const stack = new Error().stack.slice(1) 403 | Error.prepareStackTrace = _ 404 | return stack 405 | } 406 | ``` 407 | 408 | 注意几点: 409 | 410 | 1. 因为修改 Error.prepareStackTrace 会全局生效,所以将原来的 Error.prepareStackTrace 存到一个变量,函数执行完后再重置回去,避免影响全局的 Error 411 | 2. Error.prepareStackTrace 函数直接返回 CallSite 对象数组,而不是格式化后的 stack 字符串 412 | 3. new 一个 Error,stack 是返回的 CallSite 对象数组,因为第一项是 callsites 总是这个模块的 CallSite,所以通过 slice(1) 去掉 413 | 414 | 假如我们想获取当前函数的父函数名,可以这样用: 415 | 416 | ```js 417 | const callsites = require('callsites') 418 | 419 | function b () { 420 | console.log(callsites()[1].getFunctionName()) 421 | // => 'a' 422 | } 423 | 424 | function a () { 425 | b() 426 | } 427 | a() 428 | ``` 429 | 430 | ## Error.stackTraceLimit 431 | 432 | Node.js 还暴露了一个 Error.stackTraceLimit 的设置,可以通过设置这个值来改变输出的 stack 的行数,默认值是 10。 433 | 434 | ## Long Stack Trace 435 | 436 | stack trace 也有短板,问题出在异步操作。正常的 stack trace 遇到异步回调就会丢失绑定回调前的调用栈信息,来看个例子: 437 | 438 | ```js 439 | const foo = function () { 440 | throw new Error('error!!!') 441 | } 442 | const bar = function () { 443 | setTimeout(foo) 444 | } 445 | bar() 446 | // 输出 447 | /Users/nswbmw/Desktop/test/app.js:2 448 | throw new Error('error!!!') 449 | ^ 450 | 451 | Error: error!!! 452 | at Timeout.foo [as _onTimeout] (/Users/nswbmw/Desktop/test/app.js:2:9) 453 | at ontimeout (timers.js:469:11) 454 | at tryOnTimeout (timers.js:304:5) 455 | at Timer.listOnTimeout (timers.js:264:5) 456 | ``` 457 | 458 | **可以看出**:丢失了 bar 的调用栈。 459 | 460 | 在实际开发过程中,异步回调的例子数不胜数,如果不能知道异步回调之前的触发位置,会给 debug 带来很大的难度。这时,出现了一个概念叫 long Stack Trace。 461 | 462 | long Stack Trace 并不是 JavaScript 原生就支持的东西,所以要拥有这样的功能,就需要我们做一些 hack,幸好在 V8 环境下,所有 hack 所需的 API,V8 都已经提供了。 463 | 464 | 对于异步回调,目前能做的就是在所有会产生异步操作的 API 做一些手脚,这些 API 包括: 465 | 466 | - setTimeout, setInterval, setImmediate 467 | - nextTick, nextDomainTick 468 | - EventEmitter.addEventListener 469 | - EventEmitter.on 470 | - Ajax XHR 471 | 472 | Long Stack Trace 相关的库可以参考: 473 | 474 | 1. [AndreasMadsen/trace](https://github.com/AndreasMadsen/trace) 475 | 2. [mattinsler/longjohn](https://github.com/mattinsler/longjohn) 476 | 3. [tlrobinson/long-stack-traces](https://github.com/tlrobinson/long-stack-traces) 477 | 478 | node@8+ 提供了强大的 async_hooks 模块,后面会介绍如何使用。 479 | 480 | ## 参考链接 481 | 482 | - https://zhuanlan.zhihu.com/p/25338849 483 | - https://segmentfault.com/a/1190000007076507 484 | - https://github.com/v8/v8/wiki/Stack-Trace-API 485 | - https://www.jianshu.com/p/1d5120ad62bb 486 | 487 | 上一节:[3.1 Async + Await](https://github.com/nswbmw/node-in-debugging/blob/master/3.1%20Async%20%2B%20Await.md) 488 | 489 | 下一节:[3.3 Node@8](https://github.com/nswbmw/node-in-debugging/blob/master/3.3%20Node%408.md) 490 | --------------------------------------------------------------------------------