All files / wdio-logger/src node.js

100% Statements 76/76
100% Branches 31/31
100% Functions 25/25
100% Lines 71/71

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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176              1x   1x 1x               1x           1x       17x 1x         16x 1x         15x 1x         14x 1x     1x 1x 1x     1x 1x 321x 321x       13x 1x             39x 13x 3x 3x     13x 17x 62x 4x     13x     13x 13x       10x 1x 1x     10x     3x 3x       1x   13x 13x 13x             19x 1x     18x 18x 18x 3x     18x 18x 18x           13x 13x 9x 9x 9x     4x   6x 1x       7x 5x     7x         7x 4x 4x           7x 48x         48x   48x     70x  
import fs from 'fs'
import log from 'loglevel'
import util from 'util'
import chalk from 'chalk'
import prefix from 'loglevel-plugin-prefix'
import ansiStrip from 'strip-ansi'
 
prefix.reg(log)
 
const DEFAULT_LEVEL = 'trace'
const COLORS = {
    error: 'red',
    warn: 'yellow',
    info: 'cyanBright',
    debug: 'green',
    trace: 'cyan'
}
 
const matches = {
    COMMAND: 'COMMAND',
    DATA: 'DATA',
    RESULT: 'RESULT'
}
 
const SERIALIZERS = [{
    /**
     * display error stack
     */
    matches: (err) => err instanceof Error,
    serialize: (err) => err.stack
}, {
    /**
     * color commands blue
     */
    matches: (log) => log === matches.COMMAND,
    serialize: (log) => chalk.magenta(log)
}, {
    /**
     * color data yellow
     */
    matches: (log) => log === matches.DATA,
    serialize: (log) => chalk.yellow(log)
}, {
    /**
     * color result cyan
     */
    matches: (log) => log === matches.RESULT,
    serialize: (log) => chalk.cyan(log)
}]
 
const loggers = {}
let logLevelsConfig = {}
const logCache = new Set()
let logFile
 
const originalFactory = log.methodFactory
log.methodFactory = function (methodName, logLevel, loggerName) {
    const rawMethod = originalFactory(methodName, logLevel, loggerName)
    return (...args) => {
        /**
         * create logFile lazily
         */
        if (!logFile && process.env.WDIO_LOG_PATH) {
            logFile = fs.createWriteStream(process.env.WDIO_LOG_PATH)
        }
 
        /**
         * split `prefixer: value` sting to `prefixer: ` and `value`
         * so that SERIALIZERS can match certain string
         */
        const match = Object.values(matches).filter(x => args[0].endsWith(`: ${x}`))[0]
        if (match) {
            const prefixStr = args.shift().slice(0, -match.length - 1)
            args.unshift(prefixStr, match)
        }
 
        args = args.map((arg) => {
            for (const s of SERIALIZERS) {
                if (s.matches(arg)) {
                    return s.serialize(arg)
                }
            }
            return arg
        })
 
        const logText = ansiStrip(`${util.format.apply(this, args)}\n`)
        if (logFile && logFile.writable) {
            /**
             * empty logging cache if stuff got logged before
             */
            if (logCache.size) {
                logCache.forEach((log) => logFile.write(log))
                logCache.clear()
            }
 
            return logFile.write(logText)
        }
 
        logCache.add(logText)
        rawMethod(...args)
    }
}
 
prefix.apply(log, {
    template: '%t %l %n:',
    timestampFormatter: (date) => chalk.gray(date.toISOString()),
    levelFormatter: (level) => chalk[COLORS[level]](level.toUpperCase()),
    nameFormatter: (name) => chalk.whiteBright(name)
})
 
export default function getLogger (name) {
    /**
     * check if logger was already initiated
     */
    if (loggers[name]) {
        return loggers[name]
    }
 
    let logLevel = process.env.WDIO_LOG_LEVEL || DEFAULT_LEVEL
    const logLevelName = getLogLevelName(name)
    if (logLevelsConfig[logLevelName]) {
        logLevel = logLevelsConfig[logLevelName]
    }
 
    loggers[name] = log.getLogger(name)
    loggers[name].setLevel(logLevel)
    return loggers[name]
}
/**
 * Wait for writable stream to be flushed.
 * Calling this prevents part of the logs in the very env to be lost.
 */
getLogger.waitForBuffer = async () => new Promise(resolve => {
    if (logFile && Array.isArray(logFile.writableBuffer) && logFile.writableBuffer.length !== 0) {
        return setTimeout(async () => {
            await getLogger.waitForBuffer(resolve)
            resolve()
        }, 20)
    }
    resolve(true)
})
getLogger.setLevel = (name, level) => loggers[name].setLevel(level)
getLogger.setLogLevelsConfig = (logLevels = {}, wdioLogLevel = DEFAULT_LEVEL) => {
    /**
     * set log level
     */
    if (process.env.WDIO_LOG_LEVEL === undefined) {
        process.env.WDIO_LOG_LEVEL = wdioLogLevel
    }
 
    logLevelsConfig = {}
 
    /**
     * build logLevelsConfig object
     */
    Object.entries(logLevels).forEach(([logName, logLevel]) => {
        const logLevelName = getLogLevelName(logName)
        logLevelsConfig[logLevelName] = logLevel
    })
 
    /**
     * set log level for each logger
     */
    Object.keys(loggers).forEach(logName => {
        const logLevelName = getLogLevelName(logName)
 
        /**
         * either apply log level from logLevels object or use global logLevel
         */
        const logLevel = typeof logLevelsConfig[logLevelName] !== 'undefined' ? logLevelsConfig[logLevelName] : process.env.WDIO_LOG_LEVEL
 
        loggers[logName].setLevel(logLevel)
    })
}
const getLogLevelName = logName => logName.split(':').shift()