Skip to content
Logger.ts 1.57 KiB
Newer Older
import winston, { format } from "winston";
Grant's avatar
Grant committed
import path from "node:path";
Grant's avatar
Grant committed
import { createEnum } from "./utils";
Grant's avatar
Grant committed
// if PIXEL_LOG_PATH is defined, use that, otherwise default to packages/server root
const PIXEL_LOG_PATH =
  process.env.PIXEL_LOG_PATH || path.join(__dirname, "..", "..", "pixels.log");

Grant's avatar
Grant committed
const formatter = format.printf((options) => {
  let maxModuleWidth = 0;
  for (const module of Object.values(LoggerType)) {
    maxModuleWidth = Math.max(maxModuleWidth, `[${module}]`.length);
  }

  let modulePadding = " ".repeat(
    Math.max(0, maxModuleWidth - `[${options.moduleName}]`.length)
  );

  let parts: string[] = [
    options.timestamp + `  [${options.moduleName || "---"}]` + modulePadding,
    options.level + ":",
    options.message,
  ];

  return parts.join("\t");
});

const Winston = winston.createLogger({
  level: process.env.LOG_LEVEL || "info",
Grant's avatar
Grant committed
  format: format.combine(format.timestamp(), formatter),
  transports: [new winston.transports.Console()],
});
Grant's avatar
Grant committed

Grant's avatar
Grant committed
// Used by LogMan for writing to pixels.log
export const PixelLogger = winston.createLogger({
  format: format.printf((options) => {
    return [new Date().toISOString(), options.message].join("\t");
  }),
  transports: [
    new winston.transports.File({
      filename: PIXEL_LOG_PATH,
    }),
  ],
});

Grant's avatar
Grant committed
export const LoggerType = createEnum([
  "MAIN",
  "SETTINGS",
  "CANVAS",
  "HTTP",
  "HTTP/ADMIN",
  "HTTP/CLIENT",
  "REDIS",
  "SOCKET",
  "JOB_WORKER",
  "CANVAS_WORK",
  "WORKER_ROOT",
Grant's avatar
Grant committed
  "RECAPTCHA",
Grant's avatar
Grant committed
]);

export const getLogger = (module?: keyof typeof LoggerType) =>
  Winston.child({ moduleName: module });