Skip to content

Instantly share code, notes, and snippets.

@joeytwiddle
Last active March 22, 2025 09:41
Show Gist options
  • Save joeytwiddle/e7cccc1e3adc83512220078ec62d61e7 to your computer and use it in GitHub Desktop.
Save joeytwiddle/e7cccc1e3adc83512220078ec62d61e7 to your computer and use it in GitHub Desktop.
Logging in Fastify

Logging in Fastify

Fastify logging works differently from console.log(). It has a few gotchas.

TLDR

  • 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.

Patterns which WORK

// 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"

Patterns which unexpectedly DO NOT WORK

// 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")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment