All files / src/classes CoreLogger.ts

100% Statements 28/28
100% Branches 11/11
100% Functions 6/6
100% Lines 28/28

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 821x 1x 1x 1x 1x 1x 1x                                 12x 12x 12x 12x 12x 12x 12x                                   13x   5x   2x   1x   1x   2x   1x   1x         5x 2x 2x   3x       4x       1108x      
export enum LogLevel {
  VERBOSE,
  DEBUG,
  WARN,
  INFO,
  ERROR,
  SILENT,
}
 
/**
 * Abstract base class for logging implementations.
 *
 * The class manages a log level and provides a set of abstract methods that
 * concrete logger subclasses must implement. The log level can be set using a
 * string or a {@link LogLevel} value. Subclasses should respect the current
 * log level when emitting messages.
 * set StoreGlobal.GLOBAL_LOG_LEVEL {VERBOSE, DEBUG, WARN, INFO, ERROR, SILENT}
 * @abstract
 */
export default abstract class CoreLogger {
  private logLevel: LogLevel;
 
  constructor(logLevel?: string) {
    this.log = this.log.bind(this);
    this.error = this.error.bind(this);
    this.debug = this.debug.bind(this);
    this.info = this.info.bind(this);
    this.warn = this.warn.bind(this);
    this.verbose = this.verbose.bind(this);
    this.logLevel = logLevel
      ? CoreLogger.getLogLevelFromString(logLevel)
      : LogLevel.WARN;
  }
 
  abstract log(channel: string, ...ags: unknown[]): void;
 
  abstract debug(channel: string, ...ags: unknown[]): void;
 
  abstract info(channel: string, ...ags: unknown[]): void;
 
  abstract error(channel: string, ...ags: unknown[]): void;
 
  abstract warn(channel: string, ...ags: unknown[]): void;
 
  abstract verbose(channel: string, ...ags: unknown[]): void;
 
  static getLogLevelFromString(value: string): LogLevel {
    switch (value.toLowerCase()) {
      case 'verbose':
        return LogLevel.VERBOSE;
      case 'debug':
        return LogLevel.DEBUG;
      case 'warn':
        return LogLevel.WARN;
      case 'info':
        return LogLevel.INFO;
      case 'error':
        return LogLevel.ERROR;
      case 'silent':
        return LogLevel.SILENT;
      default:
        throw new Error(`Unknown log level: ${value}`);
    }
  }
 
  setLogLevel(value: string | LogLevel) {
    if (typeof value === 'string') {
      this.logLevel = CoreLogger.getLogLevelFromString(value);
      return;
    }
    this.logLevel = value;
  }
 
  getLogLevel() {
    return this.logLevel;
  }
 
  isOnLevel(value: LogLevel): boolean {
    return value >= this.logLevel;
  }
}