Since Fastify is really focused on performances, 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 the logger option to Fastify. You can find all the 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 the 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 behavior can be customized by specifying custom serializers.

    1. const fastify = require('fastify')({
    2. logger: {
    3. req: function (req) {
    4. return { url: req.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 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.

    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. })

    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

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

    See https://getpino.io/#/docs/redaction for more details.