all files / src/ logger.js

100% Statements 30/30
100% Branches 28/28
100% Functions 5/5
100% Lines 29/29
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     15× 13× 11×             11×                                        
module.exports = function () {
 
    const logLevels = ['debug', 'info', 'warn', 'error', 'fatal']
 
    function initLoggerInstance (options, logLevels) {
        const logger = {}
        logLevels.forEach(logLevel => {
            if (logLevels.indexOf(logLevel) >= logLevels.indexOf(options.logLevel)) {
                logger[logLevel] = (...args) => {
                    const prefix = options.showLogLevel ? logLevel + ' | ' : ''
                    const formattedArguments = options.stringifyArguments ? args.map(a => JSON.stringify(a)) : args
                    print(logLevel, prefix, formattedArguments)
                }
            } else {
                logger[logLevel] = () => {}
            }
        })
        return logger
    }
 
    function print (logLevel, prefix, formattedArguments) {
        if (logLevel === 'warn' || logLevel === 'error' || logLevel === 'fatal') {
            console[logLevel === 'fatal' ? 'error' : logLevel](prefix, ...formattedArguments)
        } else {
            console.log(prefix, ...formattedArguments)
        }
    }
 
    function validateOptions (options, logLevels) {
        if (!(options.logLevel && typeof options.logLevel === 'string' && logLevels.indexOf(options.logLevel) > -1)) {
            return false
        }
        if (options.stringifyArguments && typeof options.stringifyArguments !== 'boolean') {
            return false
        }
        if (options.showLogLevel && typeof options.showLogLevel !== 'boolean') {
            return false
        }
        return true
    }
 
    function install (Vue, options) {
        if (validateOptions(options, logLevels)) {
            Vue.prototype.$log = initLoggerInstance(options, logLevels)
        } else {
            throw new Error('Provided options for vuejs-logger are not valid.')
        }
    }
 
    return {
        install,
        validateOptions,
        print,
        initLoggerInstance,
        logLevels
    }
}