Skip to content

Instantly share code, notes, and snippets.

@dfparker2002
Forked from getify/1.js
Created August 24, 2018 23:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfparker2002/e9341141cae35ec69bc2272eaa0cd98b to your computer and use it in GitHub Desktop.
Save dfparker2002/e9341141cae35ec69bc2272eaa0cd98b to your computer and use it in GitHub Desktop.
tag function for formatting console.log(..) statements
function logger(strings,...values) {
var str = "";
for (let i = 0; i < strings.length; i++) {
if (i > 0) {
if (values[i-1] && typeof values[i-1] == "object") {
if (values[i-1] instanceof Error) {
if (values[i-1].stack) {
str += values[i-1].stack;
}
else {
str += values[i-1];
}
continue;
}
else {
try {
str += JSON.stringify(values[i-1]);
continue;
}
catch (err) {}
}
}
str += values[i-1];
}
str += strings[i];
}
console.log(str);
return str;
}
var v = 42;
var o = { a: 1, b: [2,3,4] };

logger`This is my value: ${v} and another: ${o}`;
// This is my value: 42 and another: {"a":1,"b":[2,3,4]}
try {
  nothing();
}
catch (err) {
  logger`Caught: ${err}`;
}
// Caught: ReferenceError: nothing is not defined
//    at <anonymous>:2:3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment