LoggerService.ts 2.14 KB
Newer Older
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
1 2 3 4 5 6 7 8
import * as bunyan from 'bunyan';
import { LogLevel } from 'bunyan';
import * as process from 'process';
import { staticStatistics } from '../statistics';

class LoggerService {

  private static instance: LoggerService;
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
9
  public useLog = true;
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
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

  private _logger: bunyan;

  get logger(): bunyan {
    return this._logger;
  }

  private _logQueue: Array<{ level: LogLevel, msg: string }>;

  constructor() {
    this._logQueue = [];
    this.init();
  }

  public static getInstance(): LoggerService {
    if (!this.instance) {
      this.instance = new LoggerService();
    }

    return this.instance;
  }

  public info(...messages: Array<string | number>): void {
    const parsedMessages = messages.join(' ');

    if (!this._logger) {
      this._logQueue.push({
        level: 'info',
        msg: parsedMessages,
      });
      return;
    }

    this._logger.info(parsedMessages);
  }

  public error(...messages: Array<string | number>): void {
    const parsedMessages = messages.join(' ');

    if (!this._logger) {
      this._logQueue.push({
        level: 'error',
        msg: parsedMessages,
      });
      return;
    }

    this._logger.error(parsedMessages);
  }

  public debug(...messages: Array<string | number>): void {
    const parsedMessages = messages.join(' ');

    if (!this._logger) {
      this._logQueue.push({
        level: 'debug',
        msg: parsedMessages,
      });
      return;
    }

    this._logger.debug(parsedMessages);
  }

  private async init(): Promise<void> {
    const level: LogLevel = <LogLevel>process.env.LOG_LEVEL || 'info';

    const streams = [];

    if (process.env.NODE_ENV !== 'test') {
      streams.push({
        stream: process.stdout,
      });
    }

    this.createLogging(level, streams);
  }

  private createLogging(level: LogLevel, streams: Array<bunyan.Stream>): void {
    this._logger = bunyan.createLogger({
      name: staticStatistics.appName,
      level,
      streams,
    });

    this._logQueue.forEach((logLevelQueue) => {
      this[logLevelQueue.level].call(this, logLevelQueue.msg);
    });
    this._logQueue.splice(0, this._logQueue.length);
  }
}

export default LoggerService.getInstance();