Logging

Introduction

Monitoring the events of your application is important, especially to catch the flow of bugs in your application. I'm going to introduce a 3rd-party logging service here called Axiom: https://axiom.co/. It officially supports NextJS applications using this library: https://github.com/axiomhq/next-axiom

One of the reasons why I picked this is because I've been using it on our startup for nearly 2 years now, and up to this date, we haven't even paid a dime for it, and we have 5,000 active users on our app every single day. You will only need to pay if you have multiple users that needs to view the logs, but for us, the workaround is just to use a single account and share it among the team members. Sorry Axiom 😔.

In order to use Axiom, first of all create an account https://app.axiom.co/register and create a dataset and a token, paste that variables (AXIOM_TOKEN and AXIOM_DATASET) on your env file.

Determining the source of your log event

Each app (web and admin) has its own logger instance to determine the source of your log event. If you just want to check all the logs for the web app here's an example:

X-Correlation-Id

A correlation id is a unique identifier that can be used to track all related events aka "event chain". This unique identifier will help you group certain events to establish a context on what happened on a certain feature of your app. The middleware function of NextJS helps us set this unique identifier on every http request.

/admin-web/src/middleware.ts
import { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
import { createId } from '@paralleldrive/cuid2';

export default async function middleware(request: NextRequest) {
  const correlationId = createId();
  request.headers.set('x-correlation-id', correlationId);
  const response = NextResponse.next();
  response.headers.set('x-correlation-id', correlationId);
  return response;
}

export const config = {};

Here's an example of using the correlationId to group log events for a customer sign up flow.

Last updated