Skip to content

Instantly share code, notes, and snippets.

@RadGH
Last active July 6, 2017 21:37
Show Gist options
  • Save RadGH/408fe3c45dc8ce835bf1 to your computer and use it in GitHub Desktop.
Save RadGH/408fe3c45dc8ce835bf1 to your computer and use it in GitHub Desktop.
Cross-browser console.log, warnings, info, and errors supported
// EXAMPLE USAGE IN A COMMENT BELOW.
/*
Rad's Debug Console:
A safe-to-use JavaScript logging tool which can be disabled by setting window.error_log to false
@Thanks http://stackoverflow.com/questions/26554807
log( [mixed] )
log.__log( [mixed] )
Displays the value of one or more arguments in the developer's console.
For debugging. Use this place of console.log()
Only outputs if window.debug_mode is enabled
log.info( [mixed] )
log.warn( [mixed] )
log.error( [mixed] )
These methods will display the logged data as info/error/warn as appropriate.
log.trace( ln )
Logs a stack trace in the console. If "ln" is set to false, the line number will not be shown, Defualt: true.
*/
var log = (function() {
// Gets the filename and line number from an error object. We have to search "up two functions" to get the actual caller of the log() function.
function line( styled ) {
if ( !(Error instanceof Function) || typeof Error().stack != 'string' ) return;
var lineGetter = /(at line \(|\/?)([^\/]+):([0-9]+):([0-9]+)/ig;
var stackError = new Error().stack.toString();
var numbers = lineGetter.exec(stackError);
var occurrences = 1;
while ( numbers != null ) {
numbers = lineGetter.exec(stackError);
occurrences = occurrences + 1;
if ( occurrences > 2 ) break;
}
if ( occurrences < 2 || !numbers || numbers.length < 4 ) return [];
// Remove query argument and hash tags from url
var script_name = numbers[2].replace(/([\?\#\&].*$)/, '');
var line_number = numbers[3];
// Style our line number so it is distinguishable from normal logging messages. Not sure how well-supported this is yet.
if ( typeof styled == 'undefined' || styled == true ) {
var result = ["%c[%s:%s]%c", 'color: #172e73; font-family: "Courier New"; font-weight: bold;', script_name, line_number, ''];
}else{
var result = script_name + ":" + line_number;
}
return result;
}
// Default log() behavior.
function __log() {
if ( !log.debug ) return;
if ( console.group instanceof Function ) console.group( __log.line(false) );
else console.info.apply( console, __log.line() );
console.log.apply( console, arguments );
if ( console.group instanceof Function ) console.groupEnd();
};
// Displays information (blue info icon)
function info() {
if ( !log.debug ) return;
if ( console.group instanceof Function ) console.group( __log.line(false) );
else console.info.apply( console, __log.line() );
if ( console.info instanceof Function ) console.info.apply( console, arguments );
else console.log.apply( console, ["%c[(i) INFO]%c", 'color: #172e73', 'color: inherit'].concat(arguments) );
if ( console.group instanceof Function ) console.groupEnd();
};
// Displays a warning (yellow caution sign)
function warn() {
if ( !log.debug ) return;
if ( console.group instanceof Function ) console.group( __log.line(false) );
else console.info.apply( console, __log.line() );
if ( console.warn instanceof Function ) console.warn.apply( console, arguments );
else console.log.apply( console, ["%c[(!) WARN]%c", 'color: #735800', 'color: inherit'].concat(arguments) );
if ( console.group instanceof Function ) console.groupEnd();
};
// Displays an error message (red exclamation mark).
// A backtrace is included automatically for console.error, but we generate one if that is not supported.
function error() {
if ( !log.debug ) return;
if ( console.group instanceof Function ) console.group( __log.line(false) );
else console.info.apply( console, __log.line() );
if ( console.error instanceof Function ) {
console.error.apply( console, arguments );
}else{
console.log.apply( console, ["%c[(*!*) ERROR]%c", 'color: #b32b32', 'color: inherit'].concat(arguments) );
__log.trace(false);
}
if ( console.group instanceof Function ) console.groupEnd();
};
// Displays a backtrace, a few lines of previous function calls.
function trace( ln ) {
if ( !log.debug ) return;
if ( typeof ln == 'undefined' || ln ) console.info.apply( console, __log.line() );
console.trace();
};
// Ability to disable logging, just set log.debug = false
// Automatically disabled if the console is not supported by the browser.
__log.debug = (window.console && window.console.log instanceof Function);
// Attach our methods to the function
__log.__log = __log;
__log.line = line;
__log.info = info;
__log.warn = warn;
__log.error = error;
__log.trace = trace;
return __log;
}());
@RadGH
Copy link
Author

RadGH commented Oct 24, 2014

Example Usage

var my_selection = ['Apples', 'Bananas'];
log('You have selected:', my_selection);

You have selected: ["Apples", "Bananas"]


Advanced Usage

var my_selection = ['Apples', 'Bananas'];
log('%cYou selected: %s and %s', 'font-weight: bold', my_selection[0], my_selection[1]);

You selected: Apples and Bananas


All Features

function test() {
  log('Test A1');
  log.__log('Test A2');
  log.info('Test B');
  log.warn('Test C');
  log.error('Test D');

  log('Test E1: With filename/line number');
  log.trace();
  log('Test E2: No filename/line number');
  log.trace(false);

  log('Test F1: Disabling logging (You should not see Test F2, but you should see F3)');
  log.debug = false;
  log('Test F2: This shouldn\'t show up.');
  log.debug = true;
  log('Test F3: Logging is back on!');
}

test();

Preview: http://radleygh.com/uploads/logging.PNG

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment