在 Web 开发中,请求日志记录是非常重要的一项功能,它可以帮助我们了解用户的行为、排查问题、优化性能等。而在 Node.js 中,使用 Hapi 框架可以很方便地实现请求日志记录。本文将详细介绍 Hapi 框架中的请求日志记录功能,包括使用方法、配置参数、示例代码等。
使用方法
Hapi 框架中的请求日志记录功能是通过插件 hapi-pino 实现的。在使用前,需要先安装 hapi-pino 插件以及 pino 日志库。可以使用以下命令进行安装:
npm install hapi-pino pino --save
安装完成后,在 Hapi 应用中引入 hapi-pino 插件,并将其注册到服务器实例中:
// www.javascriptcn.com code example
const Hapi = require('@hapi/hapi');
const HapiPino = require('hapi-pino');
const server = Hapi.server({ port: 3000 });
async function start() {
await server.register({
plugin: HapiPino,
options: {
prettyPrint: true
}
});
await server.start();
console.log(`Server running at ${server.info.uri}`);
}
start();上述代码中,options 参数是可选的,用于指定日志记录的格式。例如,prettyPrint 参数可以将日志输出为易读的格式。
配置参数
hapi-pino 插件支持多种配置参数,可以通过 options 参数进行设置。下面是一些常用的配置参数:
level:指定日志记录的级别,默认为info。prettyPrint:将日志输出为易读的格式。serializers:指定序列化函数,用于将对象转换为字符串。redact:指定要过滤的属性,用于保护敏感信息。
例如,以下代码将日志记录级别设置为 debug,并使用 pino-pretty 库将日志输出为易读的格式:
await server.register({
plugin: HapiPino,
options: {
level: 'debug',
prettyPrint: true
}
});示例代码
在了解了使用方法和配置参数后,我们来看一下如何在 Hapi 应用中记录请求日志。下面是一个示例代码:
// www.javascriptcn.com code example
const Hapi = require('@hapi/hapi');
const HapiPino = require('hapi-pino');
const server = Hapi.server({ port: 3000 });
async function start() {
await server.register({
plugin: HapiPino,
options: {
prettyPrint: true
}
});
server.route({
method: 'GET',
path: '/',
handler: (request, h) => {
request.logger.info('Hello, world!');
return 'Hello, world!';
}
});
await server.start();
console.log(`Server running at ${server.info.uri}`);
}
start();在上述代码中,我们定义了一个路由 /,并在其中记录了一条日志。request.logger 是 Hapi 框架提供的请求级别的日志记录器,它可以在请求处理过程中记录日志。在上述代码中,我们使用 info 级别记录了一条字符串 'Hello, world!'。
启动应用后,我们可以在控制台中看到类似以下的日志输出:
{"level":30,"time":1628211027108,"pid":1,"hostname":"localhost","reqId":1,"res":{"statusCode":200},"responseTime":11,"msg":"request completed"}
{"level":30,"time":1628211027109,"pid":1,"hostname":"localhost","reqId":1,"method":"get","url":"/","remoteAddress":"::1","remotePort":54689,"userAgent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36","referer":"","responseTime":11,"msg":"request"}
{"level":30,"time":1628211027111,"pid":1,"hostname":"localhost","reqId":1,"msg":"Hello, world!"}可以看到,日志记录了请求的方法、路径、响应状态码、响应时间等信息,以及我们记录的一条日志信息。
指导意义
请求日志记录是 Web 开发中非常重要的一项功能,它可以帮助我们了解用户的行为、排查问题、优化性能等。使用 Hapi 框架中的请求日志记录功能,可以轻松地实现请求日志记录,并方便地进行配置和扩展。
在实际开发中,我们可以根据需求自定义日志格式、级别、过滤等参数,以满足不同的需求。同时,我们也需要注意保护敏感信息,避免在日志中泄漏用户的隐私。
总之,请求日志记录是 Web 开发中必不可少的一项功能,掌握 Hapi 框架中的请求日志记录功能,可以帮助我们更好地进行 Web 开发。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d38ed2a941bf71346c7ade