Skip to content

Instantly share code, notes, and snippets.

@dabroder
Last active January 21, 2021 17:58
Show Gist options
  • Save dabroder/fe8fa6ee53c9eebee306fec2ec0b970c to your computer and use it in GitHub Desktop.
Save dabroder/fe8fa6ee53c9eebee306fec2ec0b970c to your computer and use it in GitHub Desktop.
Simple Logger Module
const { inspect } = require('util')
const os = require('os')
const isProd = process.env.NODE_ENV === 'production'
const isDev = process.env.NODE_ENV === 'development'
const eff = f => x => ((f(x), x))
const noop = () => {}
const now = () => new Date().toISOString()
const inspDevOps = { colors: true, breakLength: 60 }
const inspProdOps = { colors: false, breakLength: Infinity }
Object.assign(inspect.defaultOptions, isProd ? inspProdOps : inspDevOps, { depth: 5 })
const pid = process.pid
const hostname = os.hostname()
const jsonErr = e => {
if (!(e instanceof Error)) return e
const r = Object.assign({}, e)
if (e.name) r.name = e.name
if (e.message) r.message = e.message
if (e.stack) r.stack = e.stack
return r
}
const ins = x => x !== undefined ? `\n${inspect(x)}` : ''
const infoDev = (msg, meta) => console.log(`\x1b[34m${now()} ${msg}\x1b[0m${ins(meta)}`)
const infoProd = (msg, meta) => console.log(JSON.stringify({ msg, pid, hostname, time: now(), meta }))
const info = isProd ? infoProd : infoDev
const infoC = msg => x => info(msg, x)
const errorDev = (msg, meta) => console.error(`\x1b[31m${now()} ${msg}\x1b[0m${ins(jsonErr(meta))}`)
const errorProd = (msg, meta) => console.error(JSON.stringify({ msg, pid, hostname, time: now(), meta: jsonErr(meta) }))
const error = isProd ? errorProd : errorDev
const errorC = msg => e => error(msg, e)
const trace = tag => eff(isDev ? infoC(tag) : noop)
module.exports = { error, errorC, info, infoC, trace }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment