Fastify logging works differently from console.log()
. It has a few gotchas.
- If you want to log an object, then put the object as the first argument, and (optionally) a message string as the second argument.
- If you want to log an error object, it must be the first argument, and not a property inside an object.
- But beware: If the "object" you are logging is actually a string, then do not put it as the first variable, concatenate it instead.
// Logging one string
fastify.log.info("message")
fastify.log.info("message: " + stringVariable)
fastify.log.info(`message: ${stringVariable}`)
// Puttting the error or context object first, and the log message second
fastify.log.info(error, "message")
fastify.log.info({ data, foo, bar, baz }, "message")
// You can also log two objects, although the second will be treated as the msg
fastify.log.debug({ foo: 'bar' }, { baz: 'qux' })
// Through pino, this will appear as: {baz: "qux"}, foo: "bar"
// Providing a string as the first argument? Only the first argument gets logged!
// Does not log the data
fastify.log.info("message", { data })
// Does not log the variable
fastify.log.info("message", stringVariable)
// Does not log the message
fastify.log.info(stringVariable, "message")
// An error deep inside an object does not get serialized.
// Only logs: msg: "test_log", error: {}
fastify.log.info({ error }, "message")