consola icon indicating copy to clipboard operation
consola copied to clipboard

support a `context` prop on the logger

Open smeijer opened this issue 10 months ago • 1 comments

Describe the feature

It would be great to have a context prop on the instance, which accepts a Record<string, unknown>, which is then appended to the args argument (or the logObject) of any message logged.

This way it would be trivial to bind a logger to an http request, and add a trace-id to every logged message, or details about the authenticated user.

So basically;

const consola = createConsola({
  defaults: {
    context: { userId: 1 },
  }
});

consola.info('http request', { path: '/dashboard' })
  //    logObject: { args: ['http request', { path: '/dashboard' }, { userId: 1 }] }
  // or logObject: { args: ['http request', { path: '/dashboard' }], context: { userId: 1 } }

Additional information

  • [ ] Would you be willing to help implement this feature?

smeijer avatar Feb 03 '25 15:02 smeijer

Currenly you can use the second parameter of log to retrieve all the options. Does this work for you?

import { createConsola } from 'consola'

const consola = createConsola({
  defaults: {
    args: [{ userId: 1 }]
  },
  reporters: [
    {
      log: (logObj, options) => {
        const context = options.options.defaults.args?.[0]

        // => { userId: 1 }
        console.log('context', context)
      }
    }
  ]
})

kricsleo avatar Mar 21 '25 07:03 kricsleo