推荐答案
在 Fastify 中,日志记录可以通过内置的 fastify.log 对象来实现。Fastify 默认使用 Pino 作为日志记录器,Pino 是一个高性能的 JSON 日志记录库。
以下是一个简单的示例,展示如何在 Fastify 中进行日志记录:
// www.javascriptcn.com code example
const fastify = require('fastify')({
logger: true
});
fastify.get('/', async (request, reply) => {
request.log.info('This is an info log');
return { hello: 'world' };
});
fastify.listen(3000, (err) => {
if (err) {
fastify.log.error(err);
process.exit(1);
}
});在这个示例中,fastify.log 提供了不同级别的日志记录方法,如 info、error、warn 等。你可以根据需要在不同的场景中使用这些方法。
本题详细解读
1. Fastify 的日志配置
Fastify 的日志记录器是通过 fastify 实例的 logger 选项来配置的。默认情况下,logger 选项为 false,即不启用日志记录。你可以通过将其设置为 true 来启用默认的 Pino 日志记录器。
const fastify = require('fastify')({
logger: true
});你也可以传递一个自定义的 Pino 配置对象来进一步定制日志记录器的行为:
const fastify = require('fastify')({
logger: {
level: 'info',
prettyPrint: true
}
});2. 日志级别
Fastify 的日志记录器支持多种日志级别,包括:
tracedebuginfowarnerrorfatal
你可以根据不同的场景选择合适的日志级别。例如,在调试时可以使用 debug 级别,而在生产环境中可能只记录 info 及以上级别的日志。
fastify.get('/', async (request, reply) => {
request.log.debug('This is a debug log');
request.log.info('This is an info log');
request.log.error('This is an error log');
return { hello: 'world' };
});3. 请求日志
Fastify 会自动记录每个请求的日志。你可以通过 request.log 对象在请求处理过程中添加自定义日志。
fastify.get('/', async (request, reply) => {
request.log.info('Request received');
return { hello: 'world' };
});4. 自定义日志记录器
如果你不想使用 Pino,或者需要集成其他日志记录库,你可以通过 logger 选项传递一个自定义的日志记录器。这个日志记录器需要实现与 Pino 兼容的 API。
// www.javascriptcn.com code example
const customLogger = {
info: function (msg) {
console.log(`INFO: ${msg}`);
},
error: function (msg) {
console.error(`ERROR: ${msg}`);
}
};
const fastify = require('fastify')({
logger: customLogger
});5. 日志格式
Fastify 默认使用 JSON 格式记录日志,这使得日志易于解析和处理。如果你需要更易读的日志格式,可以使用 prettyPrint 选项来启用漂亮的日志输出。
const fastify = require('fastify')({
logger: {
level: 'info',
prettyPrint: true
}
});6. 日志上下文
Fastify 的日志记录器支持在日志中添加上下文信息。你可以通过传递一个对象作为日志方法的第二个参数来添加上下文。
fastify.get('/', async (request, reply) => {
request.log.info({ user: 'JohnDoe' }, 'User logged in');
return { hello: 'world' };
});7. 日志性能
由于 Fastify 使用 Pino 作为默认的日志记录器,Pino 的高性能特性使得 Fastify 的日志记录对应用程序的性能影响非常小。Pino 通过异步写入日志和最小化日志格式化的开销来实现高性能。
8. 日志输出
Fastify 的日志默认输出到标准输出(stdout)。你可以通过配置 Pino 的 destination 选项将日志输出到文件或其他流。
// www.javascriptcn.com code example
const fs = require('fs');
const pino = require('pino');
const logStream = fs.createWriteStream('./app.log');
const logger = pino({ level: 'info' }, logStream);
const fastify = require('fastify')({
logger: logger
});通过以上方式,你可以灵活地在 Fastify 中进行日志记录,并根据需求进行定制。