FormidableLabs / pino-lambda

Send pino logs to cloudwatch with aws-lambda
MIT License
125 stars 13 forks source link

Formatter is very fragile #44

Open ramblingenzyme opened 11 months ago

ramblingenzyme commented 11 months ago

https://github.com/pinojs/pino/blob/master/docs/api.md#messagekey-string

Configuring messageKey will cause the formatter to fail.

Additionally we configure a formatter for level which returns status, to meet Datadog's expectations https://docs.datadoghq.com/logs/log_configuration/attributes_naming_convention/#reserved-attributes.

    level: (label: string) => ({
      status: label,
    }),
  },
carbonrobot commented 11 months ago

pino runs the custom destination as the last function in the call chain, so the level and messagekey are not known to pino-lambda by the time pino calls our formatter. The fix is pretty simple, however, by supplying your own custom formatter.

import { LogData, ILogFormatter } from 'pino-lambda';

class CustomLogFormatter implements ILogFormatter {
  format(data: LogData): string {
    const { 
      awsRequestId,
      // your custom message key
      customMessageKey,
      // your custom level label key
      status
    } = data;

    // extract parts for message format
    const time = new Date().toISOString();

    return `${time}${
      awsRequestId ? `\t${awsRequestId}` : ''
    }\t${status.toUpperCase()}\t${msg}\t${JSON.stringify(data)}`;
  }
}

const destination = pinoLambdaDestination({
  formatter: new CustomLogFormatter(),
});
const logger = pino(destination);