Last active
April 3, 2018 08:49
-
-
Save abdel-ships-it/44ea86ae5b9c90601fe069675a3943bd to your computer and use it in GitHub Desktop.
console.context polyfill
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
var createLogger = function(name) { | |
if ( 'context' in console ) { | |
// If console context is supported just return it | |
// | |
return console.context(name); | |
} else { | |
// If its not, we will return a fallback version which just prefixes all the logs | |
// | |
return loggerFallBack(name); | |
} | |
} | |
var loggerFallBack = function(name) { | |
var supportedMethods = Object.keys(console); | |
var customConsole = {}; | |
supportedMethods.forEach( function( method ) { | |
customConsole[method] = function() { | |
var args = Array.prototype.slice.call(arguments); | |
args.unshift(name); | |
console[method].apply(null, args); | |
} | |
}); | |
return customConsole; | |
} | |
// Usage. | |
// Step 1- Create a logger | |
logger = createLogger('my-component'); | |
// 2- Use all console methods like you normally would | |
logger.log('created'); | |
logger.error('error at creation'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment