Next.js Discord

Discord Forum

Parsing Raw Console Context From Middleware

Unanswered
Black carp posted this in #help-forum
Open in Discord
Black carpOP
I'm currently doing a console.info on my middleware functions and give them a context in form of object:

    console.info(
      { err: new Error('foo'), foo: 'bar' },
      'THIS IS A TEST MESSAGE \' \" FROM MIDDLEWARE',
    );


context in comment

3 Replies

Black carpOP
This will then get patched in instrumentation.ts which pipes to pino

const logger = pino({
          messageKey: 'message',
          timestamp: () =>
            `,"timestamp":"${new Date(Date.now()).toISOString()}"`,
          formatters: {
            level(label, _) {
              return { level: label.toUpperCase() };
            },
          },
          transport,
          hooks: {
            async logMethod(inputArgs, method) {
              const firstArg = inputArgs[0] as unknown;
              let meta: Record<string, unknown> | undefined;

              if (firstArg instanceof Error) {
                meta = { err: firstArg };
              } else if (typeof firstArg === 'object' && firstArg !== null) {
                meta = { ...firstArg };
              }

              let msg =
                inputArgs.find((input) => typeof input === 'string') ?? '';

              const logContext: Record<string, unknown> = {
                ...meta,
              };

              const isWarning = errorToWarningMessagePatterns.some((pattern) =>
                pattern(msg),
              );

              if (isWarning) {
                return this.warn(logContext, msg);
              }

              const isInfo = errorToInfoMessagePatterns.some((pattern) =>
                pattern(msg),
              );
              if (isInfo) {
                return this.info(logContext, msg);
              }

              // just ignore logContext type
              return method.call(this, logContext as any, msg);
            },
          },
        });

        console.log = (...args: unknown[]) => {
          // just ignore logContext type
          (logger.info as any)(...args);
        };


This function works fine in server context. However, if I logged in middleware, I got a weirdly-stringified object
{
  requestId: '<REQUEST_ID>',
  userId: '<USER_EMAIL>',
  originIp: '<IP_ADDRESS>',
  referer: undefined,
  err: {
    name: 'Error',
    message: 'foo',
    stack: 'Error: foo
    at fn_a1b2c3d4 (<PATH>:<LINE>:<COL>)
    at fn_b2c3d4e5 (<PATH>:<LINE>:<COL>)
    at fn_c3d4e5f6 (<PATH>:<LINE>:<COL>)
    at async <PATH>:<LINE>:<COL>
    at async <PATH>:<LINE>:<COL>
    at async <PATH>:<LINE>:<COL>
    at async fn_d4e5f6a7 (<PATH>:<LINE>:<COL>)
    at async <PATH>:<LINE>:<COL>
    at async fn_e5f6a7b8 (<PATH>:<LINE>:<COL>)
    at async fn_f6a7b8c9 (<PATH>:<LINE>:<COL>)'
  },
  foo: 'bar'
}` 'THIS IS A TEST MESSAGE \' \" FROM MIDDLEWARE'


I suspect that Next called util.inspect on the object on consoles. How do I stop this behavior?
Black carpOP
I see... There's no helping it then. Thanks!