Created
May 9, 2019 04:59
-
-
Save katowulf/08cd54013ad75f2c4d6cc9961ec77db1 to your computer and use it in GitHub Desktop.
A simple JavaScript/TypeScript logger for outputting messages to console and to DOM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
/////////////////////////////////// | |
// Rudimentary logger impl that outputs | |
// to the JS console and to <div> tag | |
// in demo app. | |
// | |
// ♡ Firebase | |
/////////////////////////////////// | |
let parentElement = null; | |
let queue = []; | |
const configParms = {element: '#log', type: 'div', insertPoint: 'beforeend'}; | |
if( document.readyState === 'loading' ) { | |
document.addEventListener("DOMContentLoaded", ready); | |
} | |
else { | |
ready(); | |
} | |
function ready() { | |
//log('logger ready'); | |
parentElement = document.querySelector(configParms.element); | |
queue.forEach(t => enqueue(t[0], t[1])); | |
queue.length = 0; | |
} | |
function enqueue(text, isError=false) { | |
if( parentElement ) { | |
const el = createEl(text, isError); | |
parentElement.insertAdjacentElement(configParms.insertPoint, el); | |
} | |
else { | |
queue.push([text, isError]); | |
} | |
} | |
function isObject(x) { | |
return typeof x === 'object' && x; | |
}; | |
function stringifyArgs(args) { | |
let s = ''; | |
args.forEach(v => s += stringify(v) + ' '); | |
return s; | |
} | |
function stringify(txt) { | |
if( isObject(txt) ) { | |
return JSON.stringify(txt); | |
} | |
else if( typeof txt !== 'string' ) { | |
return txt + ''; | |
} | |
return txt; | |
} | |
function createEl(text, isError) { | |
const el = document.createElement(configParms.type); | |
el.textContent = text; | |
el.classList.add('log'); | |
if( isError ) el.classList.add('error'); | |
return el; | |
} | |
export function config(props) { | |
Object.keys(props).forEach(k => configParms[k] = props[k]); | |
if( parentElement && props.hasOwnProperty('element') ) { | |
parentElement = document.querySelector(configParms.element); | |
} | |
} | |
export function debug(...args) { | |
console.log.apply(console, args); | |
} | |
export function log(...args) { | |
console.log.apply(console, args); | |
enqueue(stringifyArgs(args)); | |
} | |
export function error(...args) { | |
console.error.apply(console, args); | |
enqueue(stringifyArgs(args), true); | |
} | |
export default { | |
log: log, error: error, debug: debug, config: config | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment