ts-rest / ts-rest

RPC-like client, contract, and server implementation for a pure REST API
https://ts-rest.com
MIT License
2.31k stars 108 forks source link

@ts-rest/fastify logInitialization does not use the fastify logger (it uses console.log) breaking structured logging #611

Closed firxworx closed 1 month ago

firxworx commented 3 months ago

Describe the bug

When registering ts-rest contract router in fastify (and possibly other integrations) and adding the logInitialization: true option to s.plugin() or s.registerRouter(), the @ts-rest/fastify implementation uses console.log().

This should use the fastify logger.

In many fastify projects pino is the top choice and pino produces a structured JSON log format that ts-rest does not respect when it uses console.log().

How to reproduce

enable logInitialization: true when using s.registerRouter(...) or s.plugin(...) then start the server and observe the log output in terminal.

Expected behavior

ts-rest could either integrate in a more "fastify" way where it can access the logger

OR

the returned object of initServer() could include a helper function that returns a string or string array of all routes, leaving it up to the caller to log with the fastify logger they have handy

per my example in the reproduction steps imagine something like: fastify.log.info(s.getRoutesSummary())

Code reproduction

Note in the following example that the fastify logger is available inside the function body via fastify.log.

const contract: FastifyPluginAsync = async function (fastify: FastifyInstance): Promise<void> {
  const s = initServer()

  const contractsRouter = s.router(apiContract, {
    posts: postsContractRouter.routes,
    example: exampleContractRouter.routes,
  })

  await fastify.register(s.plugin(contractsRouter), {
    logInitialization: true,
  })
}

ts-rest version

3.45.2