javascriptfastifypinojs

pino logger as fastify plugin


I have been created my own options and stream for fastify logger:

const logger = pino(
{
  level: 'info',
  ...ecsFormat,
},
pinoMultiStream.multistream([
  { stream: streamToElastic },
  {
    stream: pretty({
      colorize: true,
      sync: true,
      ignore: 'pid',
    }),
  },
]),)

const fastify = Fastify({logger})

now I want to extract this options as fastify plugin, how can I do this functionality? If that’s impossible what can I do to extract this code?


Solution

  • You can't encapsulate your code into a Fastify plugin because Fastify's logger has been already created at that time.

    In this case, you need to define your own logic to build the fastify server's configuration such as a decorator pattern.

    The user experience you will get would be something like:

    const decorateLogger = require('my-logger-module')
    
    const applicationConfig = loadAppConfig()
    
    decorateLogger(applicationConfig, options)
    
    const app = Fastify(applicationConfig)