All files logger.ts

100% Statements 45/45
100% Branches 18/18
100% Functions 9/9
100% Lines 35/35

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 781x 1x 1x 1x 1x     1x             1x 5x       5x 5x 5x 5x 5x             5x 5x 5x 5x     1x 11x 7x         7x   7x       8x 2x     8x 2x     17x 5x     8x 2x     1x 6x 6x         6x       1x  
export enum Level {
  ERROR = 1,
  WARN = 2,
  INFO = 3,
  DEBUG = 4,
}
 
export const levelMapper = {
  [`${Level.ERROR}`]: 'error',
  [`${Level.WARN}`]: 'warn',
  [`${Level.INFO}`]: 'info',
  [`${Level.DEBUG}`]: 'debug',
};
 
export class Logger {
  public level: Level = Level.INFO;
  private prefix: string | undefined;
  onLog: ((level: Level, args: Array<any>) => any) | undefined;
 
  constructor({
    prefix,
    level,
    titleTemplate,
    onLog,
  }: {
    prefix?: typeof Logger.prototype.prefix;
    level?: typeof Logger.prototype.level;
    titleTemplate?: typeof Logger.prototype.titleTemplate;
    onLog?: typeof Logger.prototype.onLog;
  } = {}) {
    if (prefix) this.prefix = prefix;
    if (level) this.level = level;
    if (titleTemplate) this.titleTemplate = titleTemplate;
    if (onLog) this.onLog = onLog;
  }
 
  log(runtimeLevel: Level, args) {
    if (runtimeLevel <= this.level) {
      const title = this.titleTemplate({
        prefix: this.prefix,
        level: runtimeLevel,
      });
 
      if (this.onLog) this.onLog(runtimeLevel, args);
 
      console[levelMapper[runtimeLevel]](title, ...args);
    }
  }
 
  error(...args) {
    this.log(Level.ERROR, args);
  }
 
  warn(...args) {
    this.log(Level.WARN, args);
  }
 
  info(...args) {
    this.log(Level.INFO, args);
  }
 
  debug(...args) {
    this.log(Level.DEBUG, args);
  }
 
  titleTemplate({
    prefix,
    level,
  }: {
    prefix: typeof Logger.prototype.prefix;
    level: typeof Logger.prototype.level;
  }) {
    return prefix
      ? `[${prefix}:${levelMapper[level]}]`
      : `[${levelMapper[level]}]`;
  }
}