Skip to content

Instantly share code, notes, and snippets.

@boeserwolf
Last active September 11, 2017 08:51
Show Gist options
  • Save boeserwolf/0c0ae06bd02a5b06a13398e95a02c3d6 to your computer and use it in GitHub Desktop.
Save boeserwolf/0c0ae06bd02a5b06a13398e95a02c3d6 to your computer and use it in GitHub Desktop.
ES6 Proxy Demo - Prepending a timestamp to console output
let pad = val => String(val).padStart(2, '0');
let getTimestamp = () => {
let opts = ['day', 'month', 'year', 'hour', 'minute', 'second']
.reduce((res, key) => (res[key] = '2-digit') && res, { hour12: false });
return new Date().toLocaleString(undefined, opts);
};
let prependTimestamp = (fn) => ({
apply(target, arg, args) {
let tag = fn !== 'log' ? ` [${fn.toUpperCase()}]` : '';
args = [`${getTimestamp()}${tag}`, ...args];
return Reflect.apply(target, arg, args);
}
});
['log', 'info', 'error', 'warn'].forEach(fn =>
console[fn] = new Proxy(console[fn], prependTimestamp(fn)));
if (typeof require !== 'undefined' && require.main === module) {
// Called directly (not via require).
console.debug('Debug message (without proxy).')
console.log('Log message.');
console.info('Info message.');
console.warn('Warn message.');
console.error('Error message.');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment