npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@askeladden/logger-node

v2.5.2

Published

A logger using `express-http-context` to provide JSON logging with request ids and meta data to application logs.

Downloads

91

Readme

Logger

A logger using express-http-context to provide JSON logging with request ids and meta data to application logs.

Usage

After setting up the logger (see below), logging can be done with our without context data:

import Logger from '../Logger.ts';

// Simple logging
Logger.info('Fetching available from Waitwhile');

// With related data
enum DOMAINS {
  ONBOARDING = 'ONBOARDING',
  BOOKING = 'BOOKING',
  AUTH = 'AUTH',
}

Logger.info('User signed up', {
  customerId: '1234',
  domain: DOMAINS.ONBOARDING,
  action: 'USER_SIGNUP',
  value: '30DAY_TRIAL',
});

// With custom data
Logger.info('Something special happened', {
  myownkey: 18,
  anotherCustomKey: {
    custom: 1,
  },
});

Setup

Setting up logging is done in two steps:

  1. Adding a logger.
  2. Add middleware to capture http context
  3. Extracting logs from our hosting provider (Heroku, AWS, Vercel), to a log provider like Logtail, Logz.io or LogDNA.

Adding logging to our app

yarn add @askeladden/logger-node

1. Add Logger.ts

/*
 * Logger.ts
 * Usage:
 *   import Logger from '../Logger.ts';
 *
 *   Logger.info('User signed up', {
 *     action: 'USER_SIGNUP',
 *   })
 */

import LoggerNode from '@askeladden/logger-node';
import config from './config';

const Logger = new LoggerNode({
  logLevel: process.env.LOG_LEVEL || 'debug',
  env: process.env.ENVIRONMENT || 'development',
  serviceName: 'candystore-api',
});

export default Logger;

2. Add logging middleware

The middleware adds metadata to requests with express-http-context. The following context fields are included in the output log.

reqId;
method;
url;
path;
query;
userId;
extra;

By adding this middleware, we:

  • set url, path, query, method automatically
  • extract reqId from header X-Request-Id, or generate a new one if header not present.
  • extract userId from req.user?.id || req.user?.sub or a JWT token in the Authorization header.

2.1 Node express

import { middlewares } from '@askeladden/logger-node';

const addMiddlewares = (app: Express) => {
  app.use(middlewares.node);
};

2.2. NextJS

Adding the logging middleware to NextJS requires us to add support for express-middlewares.

yarn add next-connect

import type { NextApiRequest, NextApiResponse } from "next";
import baseHandler from "../../middlewares/handler";
import Logger from "../../logger";

const handler = baseHandler().get((req, res) => {
  Logger.info("User signed up", {
    action: "USER_SIGNUP",
    customerId: '123',
  });
  res.status(200).json({ id: '123' });
}

export default handler;
// middlewares/handler.ts
import nc from 'next-connect';
import logMiddleware from '../logger/middleware';
import { NextApiRequest, NextApiResponse } from 'next';
import { RequestContext } from '../logger/types';
import { getHttpContext } from '../logger/request.utils';
import Logger from '../logger';

export default function requestHandler<T>() {
  // Context of express-http-context is not set inside onError handler
  //   and instead set manually here from a middleware
  let context: RequestContext | undefined;

  return nc<NextApiRequest, NextApiResponse<T>>({
    onError: (err, req: NextApiRequest, res: NextApiResponse, next) => {
      // (Suitable spot for adding Sentry event)
      Logger.error(String(err), { ...context, stack: err.stack });
      res.status(500).send({ message: 'An error occured' });
    },
  })
    .use(logMiddleware)
    .use((req, res, next) => {
      context = getHttpContext();
      next();
    });
}

Adding extra context data (optional)

If you need to set additional http context data, you can do this by populating extra like this:

import httpContext from 'express-http-context';
import { middlewares } from '@askeladden/logger-node';

app.use(middlewares.node);
app.use((req, res, next) => {
  httpContext.set('extra', {
    myfield: 'customvalue',
  });
  next();
});

You can also override fields that way.

3. Adding 3rd party log management (optional)

Adding log management is done by consuming the log drains of the infrastructure that the app runs on.

E.g. for Logtail on Heroku, see this guide.