Here is my go-to snippet for a consistent, production-ready logger in NodeJS or Typescript :

logger.js

import pino from "pino";
import ecsFormat from "@elastic/ecs-pino-format"; // Optional
export const logger = pino({
...ecsFormat(), // Optional
level: process.env.LOG_LEVEL || "info",
prettyPrint:
process.env.NODE_ENV !== "production" ||
process.env.LOG_PRETTY_PRINT === "true",
});

What's inside ?

That's it! It just works :)

Usage

Add its dependencies to your project :

npm i pino
npm i -D pino-pretty
# Optional : Use the Elastic Common Format
npm i @elastic/ecs-pino-format

And use it like this :

import { logger } from "logger";
// Simplest example
logger.info("Yay");
// Add more context
const ctx = { user: "foo", action: "delete", reason: "whatever" };
logger.debug(ctx, "User deleted");

Links

© Julien Tanay
·RSS