Source

services/SparkLogger.ts

/**
 * This logger class provides a set of utility logging functions to SPARK developers.
 *
 * The intent is to provide a single system to use for logging, which can be modified/updated to meet future logging
 * needs without requiring developers to modify existing applications use of the service.
 *
 * Currently the logger only provides some basic wrapper functions to allow developers to log messages to the console
 * while the react build is not production (e.g. during local development).
 *
 * In future, the logger should:
 *  - Support multiple logging destinations (including remote destinations)
 *  - Contain additional debugging features
 *  - Contain performance logging capacity
 *
 *  A singleton instance of the `SparkLogger` is exported as `logger`, and can be imported with
 *  `import {logger} from '@jcu/spark'`
 *
 *  @category Services
 */
export class SparkLogger {

    console: Console = window.console

    _devMode: boolean = false

    /**
     * A wrapper function for `console.warn` that only logs if `devMode` is true, i.e. not a production build.
     *
     * Has the same parameters and return values as `console.warn`
     */
    devWarn(message?: any, ...optionalParams: any[]): void {
        if (this._devMode) {
            return this.console.warn(message, ...optionalParams)
        } else {
            return undefined
        }
    }

    /**
     * A wrapper function for `console.error` that only logs if `devMode` is true, i.e. not a production build.
     *
     * Has the same parameters and return values as `console.error`
     */
    devError(message?: any, ...optionalParams: any[]): void {
        if (this._devMode) {
            return this.console.error(message, ...optionalParams)
        } else {
            return undefined
        }
    }

    /**
     * A wrapper function for `console.log` that only logs if `devMode` is true, i.e. not a production build.
     *
     * Has the same parameters and return values as `console.log`
     */
    devLog(message?: any, ...optionalParams: any[]): void {
        if (this._devMode) {
            return this.console.log(message, ...optionalParams)
        } else {
            return undefined
        }
    }

    set devMode(devMode: boolean) {
        this._devMode = devMode
    }

    get devMode() {
        return this._devMode
    }

    /**
     * Constructor currently sets `devMode` during instantiation
     */
    constructor() {
        //TODO: Convert this to use the useEnvironmentCheck hook (may need a bigger refactor)
        this._devMode = process.env.NODE_ENV !== 'production'
    }
}

// Instantiates a singleton instance of SparkLogger.
export let logger = new SparkLogger()