Skip to content
Snippets Groups Projects
Logger.ts 1.73 KiB
Newer Older
Grant's avatar
Grant committed
import path from "node:path";
Grant's avatar
Grant committed

import winston, { format } from "winston";

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);
  }

Grant's avatar
Grant committed
  let moduleName = options.moduleName;
  if (typeof options.workerId !== "undefined") {
    moduleName += " #" + options.workerId;
  }

Grant's avatar
Grant committed
  const modulePadding = " ".repeat(
Grant's avatar
Grant committed
    Math.max(0, maxModuleWidth - `[${moduleName}]`.length)
Grant's avatar
Grant committed
  );

Grant's avatar
Grant committed
  const parts: string[] = [
Grant's avatar
Grant committed
    options.timestamp + `  [${moduleName || "---"}]` + modulePadding,
Grant's avatar
Grant committed
    options.level + ":",
    options.message + "",
Grant's avatar
Grant committed
  ];

  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
]);

Grant's avatar
Grant committed
export const getLogger = (
  module?: keyof typeof LoggerType,
  workerId?: number
) => Winston.child({ moduleName: module, workerId });