Easy Log Facilities for JavaScript

François-Emmanuel CORTES - Oct 8 '22 - - Dev Community

Here are some log debugging facilities exposed for JS.

1. console.log (arg1, arg2, ..., argn)

console.log can take more than one argument. If it is the case, it would make logs as much as separate arguments count.

 2. console.log ({ ...props })

You can either pass an object or a property bag object and it will be logged as well. Remember that if an object does not have an explicit toString() method it will output something like "[object Object]" when concatenated in a message string, and could be useless.

// example
const a = 1
const b = 2
const c = 3

// shorthand object notation
const item = { a, b, c }

// instead of:
console.log ('The item is ' + item)

// prefer: 
console.log ('the item is:', item)

// or: 
console.log ({ item })
Enter fullscreen mode Exit fullscreen mode

debug flag for factory functions

You can pass to a factory function a debug flag, and log if it is true, just with logical AND!

let debug = true

const factoryFun = ({ x, y, debug }) => {
    const point = { x, y }

    point.distance = (other) => {
        const dx = Math.abs (this.x - other.x)
        const dy = Math.abs (this.y - other.y)

        debug && console.log ('computing distance between another point')

        return Math.sqrt (dx*dx + dy*dy)
    }

    debug && console.log ('factory')

    return point
}

const point = factoryFun ({ x:4, y:2, debug })
Enter fullscreen mode Exit fullscreen mode

4. Adjustable verbosity level filtering

let level = 0 // no log !


const bigImplFun = ({ level }) => {
    const filter = (x) => x > 0 && x >= level

    filter (1) && console.log ('log level 1')
    filter (2) && console.log ('log level 2')
    filter (3) && console.log ('log level 3')
}

bigImplFun ({ level: 3 })
Enter fullscreen mode Exit fullscreen mode

5. Indentable logging messages

Wrap it up ! If you're tired writing ampersands "&&" sequences, isolate inside a function body

const debugx = ( level, message ) => {
    const test = x > 0 && x >= level
    const indent = '\t'.repeat (level - 1)

    test && console.log (indent + message)
}

const BigImplModule = ({ level }) => {
    const nested = () => {
        debug (2, 'log level2')
    }

    const f1 = () => {
        debug (1, 'log level1')
    }
    const f2 = () => {
        debug (1, 'log level1')
        nested ()
    }

    const mod = { f1, f2 }
   return mod
}

let level = 0 // no debug !!!
let instance = bigImplModule ({ level })

instance.f1 ()
instance.f2 ()
Enter fullscreen mode Exit fullscreen mode

Et voilà ! Happy coding.

. . . . . . .
Terabox Video Player