Skip to content

node-custom-server morgan logging not working #66

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
mbrowne opened this issue Jan 21, 2025 · 2 comments
Open

node-custom-server morgan logging not working #66

mbrowne opened this issue Jan 21, 2025 · 2 comments

Comments

@mbrowne
Copy link

mbrowne commented Jan 21, 2025

In the node-custom-server template, this line is too late:

app.use(morgan("tiny"));

This means that morgan won't run at all.

Personally I like just logging in production, since logging every request in development can be noisy. So I would move the morgan() call right below this line:

It could alternatively be moved above the "/assets" handler if you wanted to log requests to static assets as well.

@lasseklovstad
Copy link

I had the same issue for node-postgres template

@jdnichollsc
Copy link

morgan is too old, maybe replacing that with Pino is a better approach here for a production ready logger, e.g:

import pino, { LoggerOptions as PinoLoggerOptions } from "pino";
import { Request } from "express";
import crypto from "crypto";

type LoggerOptions = {
  level: string;
  serviceName: string;
};

export function createLoggerOptions({ level, serviceName }: LoggerOptions) {
  const isProduction = process.env.APP_ENV === "production";

  return <PinoLoggerOptions>{
    level,
    name: serviceName,
    formatters: {
      level(label) {
        return { level: label };
      },
    },
    base: { service: serviceName },
    transport: !isProduction
      ? {
          target: "pino-pretty",
          options: {
            colorize: true,
            translateTime: "SYS:standard",
            ignore: "pid,hostname",
          },
        }
      : undefined,
    // Generate a correlation ID for each request
    genReqId: (request: Request) => {
      const correlationId = request.headers["x-correlation-id"];
      return correlationId ?? crypto.randomUUID();
    },
  };
}

const logger = pino(
  createLoggerOptions({
    level: process.env.LOG_LEVEL ?? "info",
    serviceName: "web-app",
  }),
);

export default logger;

Dependencies:

    "pino": "9.6.0",
    "pino-http": "10.4.0",
    "pino-pretty": "13.0.0",

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants