fliplog

fluent logging with verbose insight, colors, tables, emoji, filtering, spinners, progress bars, timestamps, capturing, stack traces, clearing, & presets

Downloads in past

Stats

StarsIssuesVersionUpdatedCreatedSize
fliplog
44111.0.46 years ago6 years agoMinified + gzip package size for fliplog in KB

Readme

ā›“šŸ”ˆ fliplog
!NPM versionfliplog-npm-imagefliplog-npm-url !MIT Licenselicense-imagelicense-url !fliphubgitter-badgegitter-url !flipfamflipfam-imageflipfam-url
all-in-one logging tool

Screenshot

usage

yarn add fliplog
npm i fliplog --save

const log = require('fliplog')

šŸ”  description

fluent logging with verbose insight, colors, tables, emoji, deep cleaning, filtering, spinners, progress bars, timestamps, capturing, stack traces, clearing, boxen, stringifying, code highlighting, notifications, beeping, sparkles, slow-mode, formatting, bar charts, & presets

šŸ—ļø legend:

- json - stringify - capture all - return formatted values - return values - chalk - shorthands - xterm - šŸ”¢ level - šŸŽÆ matcher - šŸš© flags - filter - tags - multi - ora - verbose vs tosource - verbose - tosource - add your own - use built ins - šŸŒ² tree - šŸ“Š bar chart - šŸ“¦ box - šŸ“Æ beep - šŸŽ‡ sparkly - šŸ”£ formatting
- [šŸ›° space](#-space)
- [šŸ’± formatter](#-formatter)
- šŸŒ slow - ā² timer - āš” performance (lightweight configurable dependencies)

šŸ‘‹ basics

log
  .data({anyKindOfData: true}) // .json, .stringify, .tosource, .verbose
  .text('text to use, this is what gets colored')
  .color('bold') // any cli-color, chalk, available as shorthands
  .echo() // outputs the log, .return to return the formatted values
šŸ†• NEW!
šŸ“šŸ“š all of these new ones need more docs

šŸ“– read the wip docs for new stuff on the wiki

+ == .echo

log.italic('so short!')+

// ^ same as `log.italic('so short!').echo()`

šŸŽ€ stringifying

json

prettyjson
// optional second arg for options passed into pretty json
log.json({eh: 'prettified'})

stringify

javascript-stringify
// args are the same as javascript-stringify
log.stringify({data: 'can stringify deep things'})

šŸ™Š silencing

  • to disable outputting a log, .silence() (optional true/false arg)
  • to disable all logs, .shush()
  • to enable all logs, .unshush()

capture all

capture output of all console logs everywhere

log.startCapturing()

console.log('this will be captured')
log.stopCapturing()

// captured data is available here
const saved = log.savedLog

return

return only echos from fliplogs, useful for getting formatted data.
// formatted data
const {text, data} = log
  .data({catchMeIfYouCan: true})
  .text('gingerbread man')
  .returnVals()

// this returns everything inside, it will call .filter first
const everything = log
  .color('blue.underline')
  .data({canYouHandleIt: true})
  .text('M')
  .return()

šŸŽØ color

chalk

chalks
all chalk colors available with .color
log
.text('\n========================================\n')
.color('bold')
.echo()

shorthands

log
  .bold('same as calling .color(bold).text(all this text)')
  .echo()

xterm

cli-colors
all cli-color are available by calling .xterm
log
  .time(true)
  .xterm(202, 236).text(' orange!!! ')
  .echo()

function

because it's javascript, the log is an object... but it can be called as a function for convenience
log({data: true}, 'text', 'color')

stack

šŸ˜Š emoji

names using emoji-commits are available with .emoji (currently šŸš§ not all have been ported yet)
log
  .emoji('phone')
  .text('et')
  .data('phone home')
  .echo()

ā˜• filtering

comma separated strings, or arrays a function can also be passed in, the argument will be an object containing the entries see flipchain/ChainedMap.entries

šŸ”¢ level

filter by log level as a number with simple comparison operators
log.filter('>= 1')
log.level(1).bold('above 1... success').echo()
log.level(0).bold('not above 1...').echo()

šŸŽÆ matcher

filter using an Array made up of Functions, Strings, and RegExps!
log.filter(['canada*'])
log.tag('canada-eh').white('canadian, pass.').echo()

more advanced
log.filter(['eh*', '!warm', tag => (/ez/).test(tag)])
log.tag('eh').underline('eh').echo()
log.tag('warm').red('warm').echo()
log.tag('ez').yellow('ez').echo()

ā— important to note, if only a function is passed in, it will have the entire log instance passed to the argument, rather than the array of tags (for compatibility & simplicity.)

filter & tags

  • verbose enables everything
  • silent silences everything
  • ! means disabled

log
  .filter('!nope, yes')

log
  .tag('unrelated,nope')
  .cyan('you will never see me :-(')
  .echo()

log
  .tag('yes')
  .underline('yay!')
  .echo()

šŸš© flags

this can also be done using cli flags compat with debug flags
yourprogram --DEBUG="!nope,yes"
yourprogram --DEBUG=verbose

šŸ›‘ quick

quickly log data and exit if you want to stop execution at a certain point for debugging
log.quick({give: 'me'}, 'everything', 'and quit')

// or
log.data({now: 'die'}).exit(1)

ā¬› tables

Screenshot
extending cli-table2
log
  .table(['header1', 'header2'], ['row1', 'row2'])
  .echo()

log
  .table(['header1', 'header2'])
  .row({'key1': 'val1'})
  .row({'key2': 'val2'})
  .echo()

āš–ļø diff

ava-diff (uses a fork of ava-formatava-format which is a fork of jest-diffjest-diff which is a fork of google's diff-match-patchdiff-match-patch)
Compare two pieces of data. Data will be cloned so it can be mutated if needed, and then compared.
let oneOneTwoTwo = 'one-one  was a race horse šŸŽ '
log.diff(oneOneTwoTwo)
log.diff(oneOneTwoTwo + '... two-two was one, two.')
log.echo()

(
previously deep-diffdeep-diff & cli-table was used.)
const royalty = {posh: true}
const lowlyPeasant = {pauper: true}
log.diff(royalty)
const abomination = Object.assign(royalty, lowlyPeasant)
log.diff(abomination)
log.echo()

šŸ› cleaner

extremely powerful tool built with chain-able
chain-able using a fork of js-traversejs-traverse
can take next-to-unusable output such as this garbage
and clean it usable cleaned
...or you could clean out certain phrases from every log
var obj = {property: {}}
obj.circularReference = obj
obj[Symbol('foo')] = 'foo'
obj.map = new Map()
obj.map.set('prop', 'value')
obj.array = [1, NaN, Infinity]

log.prettyformat(obj).echo()

const cleaner = log
  .cleaner(true)
  .keys([/array|circularReference|map|property/])
  .data(obj)
  .clean()
  .echo()

šŸŒ€ spinner

spinners

easy

// easy to color spinners
log.bold().startSpinner('loading...')
setTimeout(() => log.stopSpinner(), 2000)

advanced

// instance available on log.Spinner
log.startSpinner('spinner message', {
  // optional spinner args
  onTick: () => {},

  // where to output the logs, default process.stdout
  stream: () => {}

  // default 60
  delay: 80,
})

console.log('log this, then spinner shows up again - it is sticky.')

log.stopSpinner()

šŸŒ€šŸŒ€ multiple

multi-spinner

// instance available on log.spinners
log
  .addSpinner('key1', 'spinner 1 msg')
  .addSpinner('key2', 'spinner 2 msg')
  .addSpinner('key3', 'spinner 3 msg')

  // arg is optionally a string for frames
  // or an object for multi-spinner options
  .startSpinners()

// string arg removes by name
setTimeout(() => log.removeSpinner('key1'), 1000)

// empty args removes all
setTimeout(() => log.removeSpinner(), 20000)

ora

  • .ora is available as a method with the same options
  • adds .fliplog to the ora instance to allow chaining back to fliplog
  • returns ora instance

// call .ora
log.ora('loading...').start()

// or
log.spinner('loading...', {ora: true})

šŸ“ˆ progress

progress bar

default

log.progress()

interval callback

total, cb(bar, interval), interval time
log.progress(20, (bar, interval) => {
  bar.tick()
  if (bar.complete) clearInterval(interval)
}, 1000)

advanced

progress bar download
let contentLength = 128 * 1024
const bar = log.progress('  downloading [:bar] :percent :etas', {
  complete: '=',
  incomplete: ' ',
  width: 20,
  total: contentLength,
}).progressBar

function next() {
  if (!contentLength) return
  bar.tick(Math.random() * 10 * 1024)
  if (!bar.complete) setTimeout(next, Math.random() * 1000)
}
next()

šŸ›Ž notify

node-notifier

string title and description

or a string for title
log
  .notify('woot!', 'super long and not as important description')
  .echo()

shorthand (echo immediate)

log.notify('woot!', true)

šŸ—ŗ stack traces

āš¾ catch errors

will output the stack trace formatted and inspected deeply with the error preset
const ForeverAndEver = new Promise(resolve => Promise.resolve())
  .then(() => Promise.reject('šŸ’'))
  .catch(log.catch)

šŸ”Ž find logs

in your entry point, calling log.track() will output the location all of the next logs output from.
log.track()

// later on...

log.bold('I cannot be found... oh wait, I was tracked.').echo()

you can also track every console.log anywhere
log.trackConsole()

// becomes `eh 'at your-file#the-line-number'`
console.log('me!')

trace

calling .trace will output a shortened stack trace to the current location.
log.data({bigData: 'oh'}).trace().echo()

Ā®ļø register

registerConsole

defines properties on the console global and automatically calls echo where applicable, for easier access:
log.registerConsole()

console.time('so easy')
console.bold('hullabaloo')
console.error(new Error('eh-rar'))
console.timeEnd('so easy')
console.quick('toodaloo')

// also available
// verbose, info, error, track, trace, note, warning, spinner, time, timeEnd, timeLap timeLapEcho, box, beep, timer, table, diff, diffs, stringify, stack, json, filter, tags, quick, exit, reset, sleep, slow, red, yellow, cyan, underline, magenta, bold

registerCatch

catches uncaught promises and errors, displays them verbosely.
log.registerCatch()

throw new Error('eh')
Promise.reject('eh')

šŸ†‘ clear

this will clear the terminal (at least, move it down so it is clear)

log.clear()

šŸ•³ deep

vs

| goal | winner | ------------- |:-------------:| | code source | tosource | | deep inside objects | verbose | | colors | verbose |

verbose

using inspector-gadget, objects are inspected and colorized as deep as configured
log
  .bold('verbose:')
  .data({
    numbers: 1000,
    booleans: true,
    functions: () => {},
    strings: 'wacky wavy fun',
  })
  .verbose(/* optional number for how deep to go */)
  .echo()

tosource

see the code source
using tosource for nodejs you can look at the source of a variable
log
  .bold('tosource:')
  .data({
    numbers: 1000,
    booleans: true,
    functions: () => {},
    strings: 'wacky wavy fun',
  })
  .tosource()
  .echo()

šŸ’ˆ highlight

cli-highlight
  • cli-highlight (but will not output wrapping html tags around the code, other options are disabled, default themes are used)

function highlitedWithColors() { return 'notice me' }
log
  .data(highlitedWithColors)
  .tosource()
  .highlight()
  .echo()

šŸ° presets

add your own

log.addPreset('warning', (chain) => {
  return chain.text('āš   warning:').color('bgYellow.black').verbose(10)
})

use built-ins

log
  .preset('warning')
  .data('nananenano!')
  .echo()

log
  .preset('error')
  .data(new Error('prettyfull!'))
  .echo()

āŒ› timestamps

log
  .time(true)
  .color('cyan')
  .text('šŸ•³  so deep, so colorful, so meta  šŸŽØ  ')
  .data(log)
  .verbose()
  .echo()

from

to use logging from a pure js object, .from is available
log.from({
  data: 'data',
  text: 'eh',
  color: 'bold',
  echo: true,
})

^ is the same as
log
  .text('eh')
  .data('data')
  .color('bold')
  .echo()

šŸŽ¢ fun

these will all be silent by default, so you can easily disable them by filtering your logs or setting silent output which can be exceedingly helpful.

šŸŒ² tree

screen shot 2017-06-13 at 11 24 29 pm
log
  .color('green')
  .text('šŸŒ²  treeify')
  .tree({
    oranges: {
      mandarin: {
        clementine: null,
        tangerine: 'so cheap and juicy!',
      },
    },
    apples: {
      'gala': null,
      'pink lady': null,
    },
  })
  .echo()

šŸŽ‡ sparkly

sparkly
  • options from sparkly can be passed in
  • will output a random sparkle if it is not set

log.sparkly().echo()

šŸ“Š bar

babar
  • will output a random bar chart if not set
  • options from babar can be passed in

random

log.bar().echo()

bar

const points = []
for (var i = 0; i < Math.PI * 2; i += Math.PI / 1000) {
  points.push([i, Math.cos(i)]);
}
log.bar(points).echo()

styles and bar

log
  .bar([[0, 1], [1, 5], [2, 5], [3, 1], [4, 6]])
  .barStyles({
    width: 80,
    height: 10,
    color: 'yellow',
    maxY: 100
  })
  .echo()

šŸ“Æ beep

beeper
all options from beeper
log.beep(1).echo()

šŸ“¦ box

boxen-fliplog

colors

boxen-fliplog
// with bold colors
log.bold().box('fliplog').echo()

// echos right away
log.box('fliplog', true)

// use boxen box styles
log
  .boxStyles({borderColor: 'blue'})
  .box('fliplog')
  .echo()

šŸ”£ formatting

log.data({}).bold('text')

// returns the currently formatted text and data
const {text, data} = log.returnVals()

// returns every single setting as an object, resets
const everything = log.return()

šŸ›° space

will output number of spaces after your log
log.text('followed by 2 empty lines').space(2).echo()

šŸŒ slow

slow mode allows debugging each log step-by-step, and will force a sleep usable across all environments using sleepfor
log.slow(1000)
log.emoji('snail').yellow('slow...').echo()
const start = Date.now()
log.emoji('snail').yellow('...slow').echo()
const end = Date.now() - start

ā² timer

start, stop, lap, and timer instance using fliptime
log
  .startTimer('named')
  .sleep(1000)
  .stopTimer('named')
  .echoTimer('named')

or for more customized usage
log.startTimer('named')

sleepfor(1000)

log.stopTimer('named').echoTimer('named')

const fliptime = log.fliptime()

šŸ’± formatter

allows final formatting of the data before echoing
āœ interesting to note, this is how most plugins do their formatting

function cb(data) {
  if (!data || typeof data !== 'object') return data

  Object
    .keys(data)
    .forEach(key => {
      if (typeof data[key] === 'string')
        data[key] = data[key].replace(/\s{2}/gmi, ' ')
      else if (Array.isArray(data[key]))
        data[key] = data[key].map(a => cb(a.name))
    })

  return data
}

const fixture = {
  str: 'I  have  too  many  spaces',
  arr: [{name: 'eh'}, {noname: 'just undefined'}],
}

log
.formatter(cb)
.data(fixture)
.echo()

āš” performance

āš™ config

to keep the module lightweight, almost all functionality is added through plugins.

requiring

all non-core dependencies are required when functions are called & the filtering passes. this way, only the used-functionality is loaded.
additionally, almost all of the functions are not formatted until .echo(), so they will not have dependencies loaded when echoing is false which means code does not have to be changed for production.
if echo(false) or filtering disables the output, they are never called.

šŸ”— resources

šŸ“ TODO

  • to file šŸ“’
  • to stream
  • middleware alongside .return
  • configure which keys are persistent across instances