介绍
在前端开发中,日志是非常重要的,可以帮助我们快速定位问题,提高开发效率。而 @aptoma/hapi-log 提供了一种很方便的日志记录方式,本文将详细介绍如何使用它。
安装
使用 npm 安装:
npm install @aptoma/hapi-log -S
使用
在 Hapi 服务启动时,通过 Hapi 服务器实例(server)的方法 register()
,将插件(plugin)注册到服务中:
-- -------------------- ---- ------- ----- ----------------- ------- ---------------------------- -------- - ---------- - -------- - - ------- --------------------- ----- ---------- ----- -- ---- ---- --------- --- -- -- - ------- -------------------- -- -------- - - - --展开代码
以上代码定义了一个 插件(plugin)到 Hapi 服务中,该插件的作用是记录所有的请求日志以及响应日志,并输出到控制台。
其中,@hapi/good-squeeze
和 @hapi/good-console
都是插件依赖。Squeeze
是一个 good 所提供的插件,它可以根据我们设置的参数,筛选出我们需要记录的日志,这里我们是需要筛选所有的日志,所以设置了 { log: '*', response: '*' }
;@hapi/good-console
是一个将日志输出到控制台的插件。
如果我们需要将日志记录到文件中,可以这样写:
-- -------------------- ---- ------- - ------- ---------------------------- -------- - ---------- - ----- - - ------- --------------------- ----- ----------- ----- -- ---------- --- -- -- - ------- ----------------------- ----- --------------------- - ----- ------ --------- ---- -- - - - - -展开代码
以上代码使用 rotating-file-stream
模块将日志记录到文件中,每天自动滚动日志文件。
示例代码
为了更好地理解,这里提供一个完整的示例,可以直接运行并查看效果:
-- -------------------- ---- ------- ----- ---- - --------------------- ----- ---- - ----- -- -- - ----- ------ - ------------- ----- ----- ----- ----------- -- ----- ----------------- ------- ---------------------------- -------- - ---------- - -------- - - ------- --------------------- ----- ---------- ----- -- ---- ---- --------- --- -- -- - ------- -------------------- -- -------- -- ----- - - ------- --------------------- ----- ----------- ----- -- ---------- --- -- -- - ------- ----------------------- ----- --------------------- - ----- ------ --------- ---- -- - - - - -- -------------- ------- ------ ----- ---- -------- --------- -- -- - ------------------- ------ ---- ---------- ------ ------ ------- - -- ----- -------------- ------------------- ------- -- ---- ---------------- - -------------------------------- ----- -- - ---------------- --------------- -- ------展开代码
启动项目:
node index.js
浏览器打开 http://localhost:3000/
,可以在控制台看到如下输出:
index.js:39 Server running on http://localhost:3000 {"name":"localhost-53926","hostname":"localhost","pid":9623,"level":30,"msg":"request received","time":"2021-07-23T03:04:47.247Z","v":0} {"name":"localhost-53926","hostname":"localhost","pid":9623,"level":30,"msg":"index page accessed","time":"2021-07-23T03:04:47.256Z","v":0} {"name":"localhost-53926","hostname":"localhost","pid":9623,"level":30,"msg":"response sent","time":"2021-07-23T03:04:47.257Z","v":0}
并且在项目根目录下的 logs/access.log
文件中会记录请求和响应的日志。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/151876