All files logger.ts

100% Statements 26/26
78.57% Branches 11/14
92.86% Functions 13/14
100% Lines 26/26

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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 862x                               2x 2x 2x 2x     2x 2x   2x       2x 4x       6x   2x     4x 2x         2x         4x   2x           2x         4x 1x     2x         4x 1x     2x 4x 4x              
import { Console } from "console";
import { Options } from "./options";
import { Chalk } from "chalk";
 
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type InternalLoggerFunc = (whereToLog: any, message: string) => void;
 
export type LoggerFunc = (message: string) => void;
 
export interface Logger {
  log: LoggerFunc;
  logInfo: LoggerFunc;
  logWarning: LoggerFunc;
  logError: LoggerFunc;
}
 
enum LogLevel {
  INFO = 1,
  WARN = 2,
  ERROR = 3,
}
 
const stderrConsole = new Console(process.stderr);
const stdoutConsole = new Console(process.stdout);
 
const doNothingLogger = (_message: string): void => {
  /* Do nothing */
};
 
const makeLoggerFunc = (options: Options): InternalLoggerFunc =>
  options.silent
    ? (_whereToLog: Console, _message: string) => {
        /* Do nothing */
      }
    : (whereToLog: Console, message: string) => whereToLog.log(message);
 
const makeExternalLogger = (
  loaderOptions: Options,
  logger: InternalLoggerFunc
): LoggerFunc => (message: string) =>
  logger(
    loaderOptions.logInfoToStdOut ? stdoutConsole : stderrConsole,
    message
  );
 
const makeLogInfo = (
  options: Options,
  logger: InternalLoggerFunc,
  green: Chalk
): LoggerFunc =>
  LogLevel[options.logLevel] <= LogLevel.INFO
    ? (message: string) =>
        logger(
          options.logInfoToStdOut ? stdoutConsole : stderrConsole,
          green(message)
        )
    : doNothingLogger;
 
const makeLogError = (
  options: Options,
  logger: InternalLoggerFunc,
  red: Chalk
): LoggerFunc =>
  LogLevel[options.logLevel] <= LogLevel.ERROR
    ? (message: string) => logger(stderrConsole, red(message))
    : doNothingLogger;
 
const makeLogWarning = (
  options: Options,
  logger: InternalLoggerFunc,
  yellow: Chalk
): LoggerFunc =>
  LogLevel[options.logLevel] <= LogLevel.WARN
    ? (message: string) => logger(stderrConsole, yellow(message))
    : doNothingLogger;
 
export function makeLogger(options: Options, colors: Chalk): Logger {
  const logger = makeLoggerFunc(options);
  return {
    log: makeExternalLogger(options, logger),
    logInfo: makeLogInfo(options, logger, colors.green),
    logWarning: makeLogWarning(options, logger, colors.yellow),
    logError: makeLogError(options, logger, colors.red),
  };
}