Since Fastify is focused on performance, it uses pino as its logger, with the default log level, when enabled, set to 'info'
.
Enabling the logger is extremely easy:
If you want to pass some options to the logger, just pass them to Fastify. You can find all available options in the . If you want to specify a file destination, use:
const fastify = require('fastify')({
logger: {
level: 'info',
file: '/path/to/file' // Will use pino.destination()
}
})
fastify.get('/', options, function (request, reply) {
request.log.info('Some info about the current request')
reply.send({ hello: 'world' })
})
If you want to pass a custom stream to the Pino instance, just add a stream field to the logger object.
By default, fastify adds an id to every request for easier tracking. If the "request-id" header is present its value is used, otherwise a new incremental id is generated. See Fastify Factory requestIdHeader
and Fastify Factory for customization options.
The default logger is configured with a set of standard serializers that serialize objects with req
, res
, and err
properties. This behaviour can be customized by specifying custom serializers.
const fastify = require('fastify')({
logger: {
req: function (req) {
return { url: req.url }
}
}
}
})
For example, the response payload and headers could be logged using the approach below (even if it is not recommended):
Note: The body not can serialize inside req
method, because the request is serialized when we create the child logger. At that time, the body is not parsed yet.
app.addHook('preHandler', function (req, reply, done) {
if (req.body) {
req.log.info({ body: req.body }, 'parsed body')
}
done()
})
This option will be ignored by any logger other than Pino.
You can also supply your own logger instance. Instead of passing configuration options, simply pass the instance. The logger you supply must conform to the Pino interface; that is, it must have the following methods: info
, error
, debug
, fatal
, warn
, trace
, .
Example:
The logger instance for the current request is available in every part of the lifecycle.
Log Redaction
const fastify = Fastify({
logger: {
redact: ['req.headers.authorization'],
level: 'info',
serializers: {
req (req) {
return {
method: req.method,
url: req.url,
headers: req.headers,
hostname: req.hostname,
remoteAddress: req.ip,
remotePort: req.connection.remotePort
}
}
}
})
See https://getpino.io/#/docs/redaction for more details.