πŸͺ΅Structured logger

Structured logging should be an early thing you introduce into your stack.

Another best practice is to treat logs as a source of enriched data rather than as plain, individual strings. To do so, we need to have a structured approach to outputting them.

In my implementation project, I'll demonstrate a handcrafted logging utility to help us do this in an easy way that nobody can fail to use correctly.

Good folks like Yan Cui have written and presented on this matter many times and you can certainly also opt-in to turnkey solutions like dazn-lambda-powertools.

I've provided a basic one that also uses getUserMetadata() to get metadata (correlation ID and user ID) that has been set in the environment at an early stage in the controller.

🎯 Example: See src/FakeUser/frameworks/Logger.ts. Implementation is as simple as importing it and then:

src/FakeUser/frameworks/Logger.ts
const logger = new Logger();
logger.log("My message!");
logger.warn("My warning!");
logger.error("My error!");

Or for that matter something more like this:

const logger = new Logger();
logger.log({
  accountId: "192k-d124",
  setting: "baseline",
  customization: {
    cinemaMode: false,
    highDef: true,
  },
  timePlayed: "412",
});

As opposed to some solutions, in our case, the Logger will not replace the vanilla console.log() (etc) so you will need to import it everywhere you want to use it.

Using it, your logs will then all follow the format:

src/FakeUser/frameworks/Logger.ts
{
  message: "My message!",
  level: "INFO" | "WARN" | "ERROR" <based on the call, i.e. logger.warn() etc.>,
  timestamp: <timestamp>,
  userId: <userId from metadata>,
  correlationId: <correlationId from metadata>
};

Last updated