All files / src logging.ts

68.75% Statements 11/16
57.14% Branches 8/14
66.66% Functions 2/3
66.66% Lines 10/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66281x 1x 1x 1x   1x 1x                                                   1x                                                       1x 399x 1x      
import morgan from "morgan";
import winston from "winston";
import pc from "picocolors";
import config from "@cooper/backend/serverConfig.json";
 
const logFolder = config.logFolder ?? "./logs";
const logger = winston.createLogger({
  level: "info",
  format: winston.format.combine(winston.format.timestamp(), winston.format.json()),
  transports: [
    /**
     * Write all logs with importance level of error or higher to error.log
     * (i.e., error, fatal, but not other levels)
     */
    new winston.transports.File({
      filename: `${logFolder}/error.log`,
      level: "error",
    }),
    /**
     * Write all logs with importance level of info or higher to combined.log
     * (i.e., fatal, error, warn, and info, but not trace)
     */
    new winston.transports.File({
      filename: `${logFolder}/activity.log`,
      level: "info",
    }),
  ],
});
 
/**
 * Logger that prints to console with colour
 */
const consoleLogger = morgan(
  // Custom output format
  (tokens, req, res) => {
    const status = Number(tokens.status(req, res));
 
    // Check if status is an error code
    let statusCode: string;
    if (Number.isNaN(status) || status >= 400) {
      // Red if >= 400
      statusCode = pc.red(pc.bold(tokens.status(req, res)));
    } else {
      // Green for 200-300
      statusCode = pc.green(pc.bold(tokens.status(req, res)));
    }
 
    return [
      "[server]:",
      pc.yellow(tokens.method(req, res)),
      statusCode,
      pc.white(tokens.url(req, res)),
      pc.yellow(tokens["response-time"](req, res) + " ms"),
    ].join(" ");
  },
);
 
/**
 * Logger that logs to file activity.log on disk in timestamped json format
 */
const activityLogger = morgan("tiny", {
  stream: { write: (message) => logger.info(message) },
});
 
export { consoleLogger, activityLogger, logger };