All files / utils/common logger.ts

88.32% Statements 121/137
79.31% Branches 23/29
100% Functions 11/11
88.32% Lines 121/137

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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 1781x 1x 1x 1x 1x 1x 1x 1x       1x 1x   1x 1x         1x     1x   1x 1x 1x 1x     1x 1x     1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x       1x   1x 1x   1x 2x 2x   1x 42x 42x   1x   1x   42x 7x 7x     42x 21x 21x     21x 21x   42x 42x 42x 42x 42x     42x 42x               42x 21x 21x 21x     21x     21x 21x 21x 21x 21x   42x 1x 1x     21x 42x   1x 7x 7x   1x 7x 7x   1x 7x 7x   1x 7x 7x   1x 7x 7x   1x 7x 7x 1x   1x   1x 47x 2x 2x 1x 1x 2x   47x 47x  
export enum LogLevel {
  Trace,
  Debug,
  Info,
  Log,
  Warn,
  Error,
  Silent
}
export type ConsoleMethods = 'trace' | 'debug' | 'info' | 'log' | 'warn' | 'error';
 
let globalLogLevel: LogLevel = LogLevel.Log;
let isNodeEnv: boolean = false;
declare const window: undefined | Window;
if (typeof window !== 'undefined' && typeof window.location !== 'undefined') {
  if (window.location.search.indexOf('debug=') !== -1) {
    const level = parseInt(window.location.search.split('debug=')[1].split('&')[0], 10);
    if (typeof LogLevel[level] !== 'undefined') {
      globalLogLevel = level;
    }
  } else if (window.location.search.indexOf('debug') !== -1) {
    globalLogLevel = LogLevel.Debug;
  }
}
declare const process: undefined | NodeJS.Process;
if (typeof process !== 'undefined' && typeof process.env !== 'undefined') {
  isNodeEnv = true;
  globalLogLevel = LogLevel.Log;
  if (typeof process.env.DEBUG !== 'undefined') {
    globalLogLevel = LogLevel.Trace;
  }
}
const stylePlaceholder = isNodeEnv ? '' : '%c';
 
// Set to silent for testing
if (
  typeof process !== 'undefined' &&
  typeof process.env !== 'undefined' &&
  process.env.NODE_ENV === 'test'
) {
  globalLogLevel = LogLevel.Silent;
}
 
const levelStrings: string[] = [
  'Trace',
  'Debug',
  'Info',
  'Log',
  'Warn',
  'Error',
];
const maxLevelStringLen: number = levelStrings.reduce(
  (len, str) => str.length > len ? str.length : len,
  0
);
const resetStyleString = '\x1B[m';
const baseLevelStyleString = 'color:{color};font-weight:bold;';
const nameStyleString = 'color:white;';
const levelStyles: string[] = [
  'grey',
  'white',
  'lightblue',
  'lightgreen',
  'orange',
  'red',
].map(color => baseLevelStyleString.replace(/\{color\}/g, color));
 
let maxLoggerNameLen: number = 0;
 
type logArguments = [ string, ...unknown[] ];
 
class Logger {
  name: string;
  level: LogLevel = LogLevel.Error;
  maxLevelStringLen = 5;
 
  constructor(name: string) {
    this.name = name;
  }
 
  setLevel(level: LogLevel) {
    globalLogLevel = level;
  }
 
  buildAlert(msg: string) {} // eslint-disable-line @typescript-eslint/no-unused-vars
 
  printLog(level: LogLevel, method: ConsoleMethods, ...args: logArguments) {
    // Build an alert if this is an error
    if (level === LogLevel.Error) {
      this.buildAlert(args[0]);
    }
 
    // Exit early if we shouldn't print this log
    if (globalLogLevel > level) {
      return;
    }
 
    // Build the logger name portion
    const loggerNameStr = isNodeEnv
      ? this.name
      : this.name.padEnd(maxLoggerNameLen, ' ');
    const loggerName = `[ ${stylePlaceholder}${loggerNameStr}${stylePlaceholder} ]`;
    let styles: string[] = [
      levelStyles[level],
      resetStyleString,
    ];
 
    // Build the first portion of the log
    let logPrefix = '';
    if (!isNodeEnv) {
      logPrefix = `${level < LogLevel.Error ? '  ' : ''}[ ${stylePlaceholder}${levelStrings[level].padEnd(maxLevelStringLen, ' ')}${stylePlaceholder} ]`;
      if (level !== LogLevel.Trace) {
        styles.push(
          nameStyleString,
          resetStyleString
        );
      }
    } else {
      styles = [];
    }
    logPrefix += loggerName;
 
    // Build the argument array
    const consoleArgs: [
      string,
      ...unknown[]
    ] = [
      logPrefix,
      ...styles,
      ...args,
    ];
    // Remove the title for trace
    if (level === LogLevel.Trace) {
      consoleArgs.splice(0, 1, loggerName);
    }
 
    // Pass it to the console
    console[method](...consoleArgs);
  }
 
  trace(...args: logArguments) {
    this.printLog(LogLevel.Trace, 'trace', ...args);
  }
 
  debug(...args: logArguments) {
    this.printLog(LogLevel.Debug, 'debug', ...args);
  }
 
  info(...args: logArguments) {
    this.printLog(LogLevel.Info, 'info', ...args);
  }
 
  log(...args: logArguments) {
    this.printLog(LogLevel.Log, 'log', ...args);
  }
 
  warn(...args: logArguments) {
    this.printLog(LogLevel.Warn, 'warn', ...args);
  }
 
  error(...args: logArguments) {
    this.printLog(LogLevel.Error, 'error', ...args);
  }
}
 
const loggers: { [key: string]: Logger } = {};
 
export function getLogger(name: string): Logger {
  if (typeof loggers[name] === 'undefined') {
    loggers[name] = new Logger(name);
    if (name.length > maxLoggerNameLen) {
      maxLoggerNameLen = name.length;
    }
  }
 
  return loggers[name];
}