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:

    1. const fastify = require('fastify')({
    2. logger: {
    3. level: 'info',
    4. file: '/path/to/file' // Will use pino.destination()
    5. }
    6. })
    7. fastify.get('/', options, function (request, reply) {
    8. request.log.info('Some info about the current request')
    9. reply.send({ hello: 'world' })
    10. })

    If you want to pass a custom stream to the Pino instance, just add a stream field to the logger object.

    The default logger is configured with a set of standard serializers that serialize objects with req, res, and err properties. The object received by req is the Fastify Request object, while the object received by res is the Fastify object.
    This behaviour can be customized by specifying custom serializers.

    1. const fastify = require('fastify')({
    2. logger: {
    3. req (request) {
    4. return { url: request.url }
    5. }
    6. }
    7. }
    8. })

    For example, the response payload and headers could be logged using the approach below (even if it is not recommended):

    Note: The body cannot be serialized inside req method because the request is serialized when we create the child logger. At that time, the body is not yet parsed.

    See an approach to log req.body

    1. app.addHook('preHandler', function (req, reply, done) {
    2. if (req.body) {
    3. req.log.info({ body: req.body }, 'parsed body')
    4. }
    5. done()
    6. })

    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, , trace, child.

    Example:

    The logger instance for the current request is available in every part of the lifecycle.

    Log Redaction

    Pino supports low-overhead log redaction for obscuring values of specific properties in recorded logs. As an example, we might want to log all the HTTP headers minus the Authorization header for security concerns:

    1. const fastify = Fastify({
    2. logger: {
    3. redact: ['req.headers.authorization'],
    4. level: 'info',
    5. serializers: {
    6. req (request) {
    7. return {
    8. method: request.method,
    9. url: request.url,
    10. headers: request.headers,
    11. hostname: request.hostname,
    12. remoteAddress: request.ip,
    13. remotePort: request.socket.remotePort
    14. }
    15. }
    16. }