2
\$\begingroup\$

Looking for a critique of this simple logger class I'm working on in my transition to TypeScript.

The purpose of the logging class is to just print to a console either info, warn or error messages.

The main things I'm after feedback on are my usage of the TypeScript type system. I.e interfaces/types/whatever else could be done different or better.

interface LoggerConfig {
  prefix?: string;
  prefixColor?: TextColor.White;
  displayConsole?: boolean;
  outputExternal?: boolean;
}

type LogFn = (msg: string) => void;

interface Log {
  config: LoggerConfig;
  log: (msg: string, logColor: TextColor, override?: LoggerConfig) => void;
  info: LogFn;
  warn: LogFn;
  error: LogFn;
}

class Logger implements Log {
  config: LoggerConfig = {
    prefix: 'console :: ',
    prefixColor: TextColor.Green,
    displayConsole: false,
    outputExternal: false,
  };

  constructor(userConfig: LoggerConfig = {}) {
    this.config = {...this.config, ...userConfig};
  }

  log(msg: string, logColor: TextColor, override?: LoggerConfig) {
    const config = override ? {...this.config, ...override} : this.config;
    const {displayConsole, outputExternal, prefix, prefixColor} = config;

    if (displayConsole) {
      showConsole();
    }

    if (outputExternal) {
      external.printToConsole(`${prefix} ${msg}`);
    }

    print(prefixColor + prefix + logColor + ' ' + msg);
  }

  info(msg: string) {
    this.log(msg, TextColor.White);
  }

  warn(msg: string) {
    this.log(msg, TextColor.Yellow, {displayConsole: true});
  }

  error(msg: string) {
    this.log(msg, TextColor.Red, {displayConsole: true, outputExternal: true});
  }
}

const logger = new Logger({prefix: 'testLogger :: '})
\$\endgroup\$
  • \$\begingroup\$ It would help to see the definitions of showConsole, external.printToConsole and print. Right now it's difficult to say what the behavior of the logger will be. \$\endgroup\$ – Gerrit0 Dec 31 '18 at 4:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.