Extend fastify logger with typesafe custom log level?

277 Views Asked by At

I add a custom log-level "silly".

Log with fastify.log.silly('...') produces a TypeScript error:

Property 'silly' does not exist on type 'FastifyBaseLogger'.ts(2339)

How can this be type-safe extended?

1

There are 1 best solutions below

0
On

If you are using fastify version >= 4.16.0, FastifyBaseLogger is exported as an interface instead of a type alias and you can use declaration merging pattern to extend it:

declare module 'fastify' {
  interface FastifyBaseLogger {
    silly: FastifyLogFn;
  }
}

Now the complier "knows" that silly is part of the logger interface and will not produce an error when calling fastify.log.silly('...')