alias to chrome console.log - javascript

I would like to know why the follow code doesn't work in the Google Chrome:
// creates a xss console log
var cl = ( typeof( console ) != 'undefined' ) ? console.log : alert;
cl('teste');
output: Uncaught TypeError: Illegal invocation
thanks.

When you write cl();, you're calling log in the global context.
Chrome's console.log doesn't want to be called on the window object.
Instead, you can write
cl = function() { return console.log.apply(console, arguments); };
This will call log in the context of console.

https://groups.google.com/a/chromium.org/d/msg/chromium-bugs/gGVPJ1T-qA0/F8uSupbO2R8J
Apparently you can also defined log:
log = console.log.bind(console);
and then the line numbers also work

Unfortunately #SLaks answer isnt applied to IE because it uses window-object as context in console.log-method.
I would be suggest another way that doesnt depend on browser:
!window.console && (console = {});
console.debug = console.debug || $.noop;
console.info = console.info || $.noop;
console.warn = console.warn || $.noop;
console.log = console.log || $.noop;
var src = console, desc = {};
desc.prototype = src;
console = desc;
desc.log = function(message, exception) {
var msg = message + (exception ? ' (exception: ' + exception + ')' : ''), callstack = exception && exception.stack;
src.log(msg);
callstack && (src.log(callstack));
//logErrorUrl && $.post(logErrorUrl, { message: msg + (callstack || '') }); // Send clientside error message to serverside.
};

Related

ServiceNow: JavaScript TypeError: Cannot read property of undefined

I am writing an onChange Client Script in ServiceNow and having issues with a Javascript error on the front end client. I keep getting a TypeError: Cannot read property 'u_emp_name' of undefined. the variable seems to vary as at one point i was getting the u_pos_office undefined as well, however the data is pulling correctly and there are no performance impacts on my code functionality.
What could be causing the type error?
Script is below:
function onChange(control, oldValue, newValue, isLoading) {
var billNum = g_form.getReference('u_billet',findBilletInfo);
console.log('Emp Name: ' + billNum.u_emp_name);
console.log('OFfice: ' + billNum.u_pos_office);
console.log('Career Field: ' + billNum.u_pos_career_field);
if (isLoading || newValue == '') {
return;
}
if (oldValue != newValue){
findBilletInfo(billNum);
}
function findBilletInfo(billNum){
console.log('Bill Num' + billNum);
console.log('encumbent' + billNum.u_emp_name);
var empName = billNum.u_emp_name;
var empNameStr = empName.toString();
console.log(empName);
console.log(empNameStr);
g_form.setValue('u_organization_office',billNum.u_pos_office);
g_form.setValue('u_encumbent',billNum.u_emp_name);
g_form.setValue('u_old_career_field',billNum.u_pos_career_field);
g_form.setValue('u_old_career_specialty',billNum.u_pos_career_specialty);
g_form.setValue('u_old_occupational_series',billNum.u_pos_series);
g_form.setValue('u_old_grade',billNum.u_pos_grade);
g_form.setValue('u_old_work_category',billNum.u_pos_category);
g_form.setValue('u_old_job_title',billNum.u_pos_title);
g_form.setValue('u_losing_rater',billNum.u_emp_rater_name);
g_form.setValue('u_losing_reviewer',billNum.u_emp_reviewer_name);
}
}
It appears to be an error here
var billNum = g_form.getReference('u_billet',findBilletInfo);
==> console.log('Emp Name: ' + billNum.u_emp_name);
In this case billNum is undefined since getReference is run asynchronously. See the documentation for the function.
This means that it won't guarantee a return value immediately or at all. This is probably why you get a record sometimes and not others.
You can move these debug logs within your findBilletInfo callback to check the values
if (isLoading || newValue == '') {
return;
}
var billNum = g_form.getReference('u_billet',findBilletInfo);
function findBilletInfo(billNum) {
console.log('Bill Num' + billNum);
console.log('encumbent' + billNum.u_emp_name);
console.log('OFfice: ' + billNum.u_pos_office);
console.log('Career Field: ' + billNum.u_pos_career_field);
...
}
If you debug in Firefox or Chrome, you should be able to just log the object to the console to explore the entire object at once.
function findBilletInfo(billNum) {
console.log(billNum);
...
}
The output will look like something like this in the console and you can see all fields at once.

I am trying to check for undefined but it's not working

I have the following code:
$scope.$watch("pid", _.debounce(function (pid) {
var a = pid;
$scope.$apply(function (pid) {
if (typeof pid == "undefined" || pid == null || pid === "") {
$scope.pidLower = null;
$scope.pidUpper = null;
}
else if (pid.indexOf("-") > 0) {
pid = pid.split("-");
$scope.pidLower = parseInt(pid[0]);
$scope.pidUpper = parseInt(pid[1]);
}
else {
$scope.pidLower = parseInt(pid);
$scope.pidUpper = null;
}
});
}, 1000));
The very first time the code runs (when the pid field is empty) I check pid with the google development tools and it shows as "undefined". However when the code runs it does not go into the first if condition. Rather it goes to the second and gives an error saying:
TypeError: Object # has no method 'indexOf'
Can anyone tell me why it ignores the first if statement ?
Here is what I get when I use the console to check pid on the first line with an if:
console.log(typeof pid)
object
undefined
Here is what I get when I use the console to check pid on the first line with an if:
console.log(typeof pid)
object
undefined
This says that the type of pid is an object. It then says that the return value of console.log() is undefined.
It isn't going into the first if because the variable is not, as you thought, undefined.
It then fails because, whatever kind of object pid is, it isn't one with an indexOf method.
Try this:
if (!pid) {
$scope.pidLower = null;
$scope.pidUpper = null;
}
else if (pid.indexOf("-") > 0) {
pid = pid.split("-");
$scope.pidLower = parseInt(pid[0]);
$scope.pidUpper = parseInt(pid[1]);
}
else {
$scope.pidLower = parseInt(pid);
$scope.pidUpper = null;
}

A proper wrapper for console.log with correct line number?

I'm now developing an application, and place a global isDebug switch. I would like to wrap console.log for more convenient usage.
//isDebug controls the entire site.
var isDebug = true;
//debug.js
function debug(msg, level){
var Global = this;
if(!(Global.isDebug && Global.console && Global.console.log)){
return;
}
level = level||'info';
Global.console.log(level + ': '+ msg);
}
//main.js
debug('Here is a msg.');
Then I get this result in Firefox console.
info: Here is a msg. debug.js (line 8)
What if I want to log with line number where debug() gets called, like info: Here is a msg. main.js (line 2)?
This is an old question and All the answers provided are overly hackey, have MAJOR cross browser issues, and don't provide anything super useful. This solution works in every browser and reports all console data exactly as it should. No hacks required and one line of code Check out the codepen.
var debug = console.log.bind(window.console)
Create the switch like this:
isDebug = true // toggle this to turn on / off for global controll
if (isDebug) var debug = console.log.bind(window.console)
else var debug = function(){}
Then simply call as follows:
debug('This is happening.')
You can even take over the console.log with a switch like this:
if (!isDebug) console.log = function(){}
If you want to do something useful with that.. You can add all the console methods and wrap it up in a reusable function that gives not only global control, but class level as well:
var Debugger = function(gState, klass) {
this.debug = {}
if (gState && klass.isDebug) {
for (var m in console)
if (typeof console[m] == 'function')
this.debug[m] = console[m].bind(window.console, klass.toString()+": ")
}else{
for (var m in console)
if (typeof console[m] == 'function')
this.debug[m] = function(){}
}
return this.debug
}
isDebug = true //global debug state
debug = Debugger(isDebug, this)
debug.log('Hello log!')
debug.trace('Hello trace!')
Now you can add it to your classes:
var MyClass = function() {
this.isDebug = true //local state
this.debug = Debugger(isDebug, this)
this.debug.warn('It works in classses')
}
You can maintain line numbers and output the log level with some clever use of Function.prototype.bind:
function setDebug(isDebug) {
if (window.isDebug) {
window.debug = window.console.log.bind(window.console, '%s: %s');
} else {
window.debug = function() {};
}
}
setDebug(true);
// ...
debug('level', 'This is my message.'); // --> level: This is my message. (line X)
Taking it a step further, you could make use of the console's error/warning/info distinctions and still have custom levels. Try it!
function setDebug(isDebug) {
if (isDebug) {
window.debug = {
log: window.console.log.bind(window.console, 'log: %s'),
error: window.console.error.bind(window.console, 'error: %s'),
info: window.console.info.bind(window.console, 'info: %s'),
warn: window.console.warn.bind(window.console, 'warn: %s')
};
} else {
var __no_op = function() {};
window.debug = {
log: __no_op,
error: __no_op,
warn: __no_op,
info: __no_op
}
}
}
setDebug(true);
// ...
debug.log('wat', 'Yay custom levels.'); // -> log: wat: Yay custom levels. (line X)
debug.info('This is info.'); // -> info: This is info. (line Y)
debug.error('Bad stuff happened.'); // -> error: Bad stuff happened. (line Z)
I liked #fredrik's answer, so I rolled it up with another answer which splits the Webkit stacktrace, and merged it with #PaulIrish's safe console.log wrapper. "Standardizes" the filename:line to a "special object" so it stands out and looks mostly the same in FF and Chrome.
Testing in fiddle: http://jsfiddle.net/drzaus/pWe6W/
_log = (function (undefined) {
var Log = Error; // does this do anything? proper inheritance...?
Log.prototype.write = function (args) {
/// <summary>
/// Paulirish-like console.log wrapper. Includes stack trace via #fredrik SO suggestion (see remarks for sources).
/// </summary>
/// <param name="args" type="Array">list of details to log, as provided by `arguments`</param>
/// <remarks>Includes line numbers by calling Error object -- see
/// * http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
/// * https://stackoverflow.com/questions/13815640/a-proper-wrapper-for-console-log-with-correct-line-number
/// * https://stackoverflow.com/a/3806596/1037948
/// </remarks>
// via #fredrik SO trace suggestion; wrapping in special construct so it stands out
var suffix = {
"#": (this.lineNumber
? this.fileName + ':' + this.lineNumber + ":1" // add arbitrary column value for chrome linking
: extractLineNumberFromStack(this.stack)
)
};
args = args.concat([suffix]);
// via #paulirish console wrapper
if (console && console.log) {
if (console.log.apply) { console.log.apply(console, args); } else { console.log(args); } // nicer display in some browsers
}
};
var extractLineNumberFromStack = function (stack) {
/// <summary>
/// Get the line/filename detail from a Webkit stack trace. See https://stackoverflow.com/a/3806596/1037948
/// </summary>
/// <param name="stack" type="String">the stack string</param>
if(!stack) return '?'; // fix undefined issue reported by #sigod
// correct line number according to how Log().write implemented
var line = stack.split('\n')[2];
// fix for various display text
line = (line.indexOf(' (') >= 0
? line.split(' (')[1].substring(0, line.length - 1)
: line.split('at ')[1]
);
return line;
};
return function (params) {
/// <summary>
/// Paulirish-like console.log wrapper
/// </summary>
/// <param name="params" type="[...]">list your logging parameters</param>
// only if explicitly true somewhere
if (typeof DEBUGMODE === typeof undefined || !DEBUGMODE) return;
// call handler extension which provides stack trace
Log().write(Array.prototype.slice.call(arguments, 0)); // turn into proper array
};//-- fn returned
})();//--- _log
This also works in node, and you can test it with:
// no debug mode
_log('this should not appear');
// turn it on
DEBUGMODE = true;
_log('you should', 'see this', {a:1, b:2, c:3});
console.log('--- regular log ---');
_log('you should', 'also see this', {a:4, b:8, c:16});
// turn it off
DEBUGMODE = false;
_log('disabled, should not appear');
console.log('--- regular log2 ---');
I found a simple solution to combine the accepted answer (binding to console.log/error/etc) with some outside logic to filter what is actually logged.
// or window.log = {...}
var log = {
ASSERT: 1, ERROR: 2, WARN: 3, INFO: 4, DEBUG: 5, VERBOSE: 6,
set level(level) {
if (level >= this.ASSERT) this.a = console.assert.bind(window.console);
else this.a = function() {};
if (level >= this.ERROR) this.e = console.error.bind(window.console);
else this.e = function() {};
if (level >= this.WARN) this.w = console.warn.bind(window.console);
else this.w = function() {};
if (level >= this.INFO) this.i = console.info.bind(window.console);
else this.i = function() {};
if (level >= this.DEBUG) this.d = console.debug.bind(window.console);
else this.d = function() {};
if (level >= this.VERBOSE) this.v = console.log.bind(window.console);
else this.v = function() {};
this.loggingLevel = level;
},
get level() { return this.loggingLevel; }
};
log.level = log.DEBUG;
Usage:
log.e('Error doing the thing!', e); // console.error
log.w('Bonus feature failed to load.'); // console.warn
log.i('Signed in.'); // console.info
log.d('Is this working as expected?'); // console.debug
log.v('Old debug messages, output dominating messages'); // console.log; ignored because `log.level` is set to `DEBUG`
log.a(someVar == 2) // console.assert
Note that console.assert uses conditional logging.
Make sure your browser's dev tools shows all message levels!
Listen McFly, this was the only thing that worked for me:
let debug = true;
Object.defineProperty(this, "log", {get: function () {
return debug ? console.log.bind(window.console, '['+Date.now()+']', '[DEBUG]')
: function(){};}
});
// usage:
log('Back to the future');
// outputs:
[1624398754679] [DEBUG] Back to the future
The beauty is to avoid another function call like log('xyz')()
or to create a wrapper object or even class. Its also ES5 safe.
If you don't want a prefix, just delete the param.
update included current timestamp to prefix every log output.
Chrome Devtools lets you achieve this with Blackboxing. You can create console.log wrapper that can have side effects, call other functions, etc, and still retain the line number that called the wrapper function.
Just put a small console.log wrapper into a separate file, e.g.
(function() {
var consolelog = console.log
console.log = function() {
// you may do something with side effects here.
// log to a remote server, whatever you want. here
// for example we append the log message to the DOM
var p = document.createElement('p')
var args = Array.prototype.slice.apply(arguments)
p.innerText = JSON.stringify(args)
document.body.appendChild(p)
// call the original console.log function
consolelog.apply(console,arguments)
}
})()
Name it something like log-blackbox.js
Then go to Chrome Devtools settings and find the section "Blackboxing", add a pattern for the filename you want to blackbox, in this case log-blackbox.js
From: How to get JavaScript caller function line number? How to get JavaScript caller source URL?
the Error object has a line number property(in FF). So something like this should work:
var err = new Error();
Global.console.log(level + ': '+ msg + 'file: ' + err.fileName + ' line:' + err.lineNumber);
In Webkit browser you have err.stack that is a string representing the current call stack. It will display the current line number and more information.
UPDATE
To get the correct linenumber you need to invoke the error on that line. Something like:
var Log = Error;
Log.prototype.write = function () {
var args = Array.prototype.slice.call(arguments, 0),
suffix = this.lineNumber ? 'line: ' + this.lineNumber : 'stack: ' + this.stack;
console.log.apply(console, args.concat([suffix]));
};
var a = Log().write('monkey' + 1, 'test: ' + 2);
var b = Log().write('hello' + 3, 'test: ' + 4);
A way to keep line number is here: https://gist.github.com/bgrins/5108712. It more or less boils down to this:
if (Function.prototype.bind) {
window.log = Function.prototype.bind.call(console.log, console);
}
else {
window.log = function() {
Function.prototype.apply.call(console.log, console, arguments);
};
}
You could wrap this with isDebug and set window.log to function() { } if you aren't debugging.
You can pass the line number to your debug method, like this :
//main.js
debug('Here is a msg.', (new Error).lineNumber);
Here, (new Error).lineNumber would give you the current line number in your javascript code.
If you simply want to control whether debug is used and have the correct line number, you can do this instead:
if(isDebug && window.console && console.log && console.warn && console.error){
window.debug = {
'log': window.console.log,
'warn': window.console.warn,
'error': window.console.error
};
}else{
window.debug = {
'log': function(){},
'warn': function(){},
'error': function(){}
};
}
When you need access to debug, you can do this:
debug.log("log");
debug.warn("warn");
debug.error("error");
If isDebug == true, The line numbers and filenames shown in the console will be correct, because debug.log etc is actually an alias of console.log etc.
If isDebug == false, no debug messages are shown, because debug.log etc simply does nothing (an empty function).
As you already know, a wrapper function will mess up the line numbers and filenames, so it's a good idea to prevent using wrapper functions.
Stack trace solutions display the line number but do not allow to click to go to source, which is a major problem. The only solution to keep this behaviour is to bind to the original function.
Binding prevents to include intermediate logic, because this logic would mess with line numbers. However, by redefining bound functions and playing with console string substitution, some additional behaviour is still possible.
This gist shows a minimalistic logging framework that offers modules, log levels, formatting, and proper clickable line numbers in 34 lines. Use it as a basis or inspiration for your own needs.
var log = Logger.get("module").level(Logger.WARN);
log.error("An error has occured", errorObject);
log("Always show this.");
EDIT: gist included below
/*
* Copyright 2016, Matthieu Dumas
* This work is licensed under the Creative Commons Attribution 4.0 International License.
* To view a copy of this license, visit http://creativecommons.org/licenses/by/4.0/
*/
/* Usage :
* var log = Logger.get("myModule") // .level(Logger.ALL) implicit
* log.info("always a string as first argument", then, other, stuff)
* log.level(Logger.WARN) // or ALL, DEBUG, INFO, WARN, ERROR, OFF
* log.debug("does not show")
* log("but this does because direct call on logger is not filtered by level")
*/
var Logger = (function() {
var levels = {
ALL:100,
DEBUG:100,
INFO:200,
WARN:300,
ERROR:400,
OFF:500
};
var loggerCache = {};
var cons = window.console;
var noop = function() {};
var level = function(level) {
this.error = level<=levels.ERROR ? cons.error.bind(cons, "["+this.id+"] - ERROR - %s") : noop;
this.warn = level<=levels.WARN ? cons.warn.bind(cons, "["+this.id+"] - WARN - %s") : noop;
this.info = level<=levels.INFO ? cons.info.bind(cons, "["+this.id+"] - INFO - %s") : noop;
this.debug = level<=levels.DEBUG ? cons.log.bind(cons, "["+this.id+"] - DEBUG - %s") : noop;
this.log = cons.log.bind(cons, "["+this.id+"] %s");
return this;
};
levels.get = function(id) {
var res = loggerCache[id];
if (!res) {
var ctx = {id:id,level:level}; // create a context
ctx.level(Logger.ALL); // apply level
res = ctx.log; // extract the log function, copy context to it and returns it
for (var prop in ctx)
res[prop] = ctx[prop];
loggerCache[id] = res;
}
return res;
};
return levels; // return levels augmented with "get"
})();
Here's a way to keep your existing console logging statements while adding a file name and line number or other stack trace info onto the output:
(function () {
'use strict';
var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
var isChrome = !!window.chrome && !!window.chrome.webstore;
var isIE = /*#cc_on!#*/false || !!document.documentMode;
var isEdge = !isIE && !!window.StyleMedia;
var isPhantom = (/PhantomJS/).test(navigator.userAgent);
Object.defineProperties(console, ['log', 'info', 'warn', 'error'].reduce(function (props, method) {
var _consoleMethod = console[method].bind(console);
props[method] = {
value: function MyError () {
var stackPos = isOpera || isChrome ? 2 : 1;
var err = new Error();
if (isIE || isEdge || isPhantom) { // Untested in Edge
try { // Stack not yet defined until thrown per https://learn.microsoft.com/en-us/scripting/javascript/reference/stack-property-error-javascript
throw err;
} catch (e) {
err = e;
}
stackPos = isPhantom ? 1 : 2;
}
var a = arguments;
if (err.stack) {
var st = err.stack.split('\n')[stackPos]; // We could utilize the whole stack after the 0th index
var argEnd = a.length - 1;
[].slice.call(a).reverse().some(function(arg, i) {
var pos = argEnd - i;
if (typeof a[pos] !== 'string') {
return false;
}
if (typeof a[0] === 'string' && a[0].indexOf('%') > -1) { pos = 0 } // If formatting
a[pos] += ' \u00a0 (' + st.slice(0, st.lastIndexOf(':')) // Strip out character count
.slice(st.lastIndexOf('/') + 1) + ')'; // Leave only path and line (which also avoids ":" changing Safari console formatting)
return true;
});
}
return _consoleMethod.apply(null, a);
}
};
return props;
}, {}));
}());
Then use it like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="console-log.js"></script>
</head>
<body>
<script>
function a () {
console.log('xyz'); // xyz (console-log.html:10)
}
console.info('abc'); // abc (console-log.html:12)
console.log('%cdef', "color:red;"); // (IN RED:) // def (console-log.html:13)
a();
console.warn('uuu'); // uuu (console-log.html:15)
console.error('yyy'); // yyy (console-log.html:16)
</script>
</body>
</html>
This works in Firefox, Opera, Safari, Chrome, and IE 10 (not yet tested on IE11 or Edge).
The idea with bind Function.prototype.bind is brilliant. You can also use npm library lines-logger. It shows origin source files:
Create logger anyone once in your project:
var LoggerFactory = require('lines-logger').LoggerFactory;
var loggerFactory = new LoggerFactory();
var logger = loggerFactory.getLoggerColor('global', '#753e01');
Print logs:
logger.log('Hello world!')();
With modern javascript and the use of getters, you could write something like this:
window.Logger = {
debugMode: true,
get info() {
if ( window.Logger.debugMode ) {
return window.console.info.bind( window.console );
} else {
return () => {};
}
}
}
The nice part about it is that you can have both static and computed values printed out, together with correct line numbers. You could even define multiple logger with different settings:
class LoggerClz {
name = null;
debugMode = true;
constructor( name ) { this.name = name; }
get info() {
if ( this.debugMode ) {
return window.console.info.bind( window.console, 'INFO', new Date().getTime(), this.name );
} else {
return () => {};
}
}
}
const Logger1 = new LoggerClz( 'foo' );
const Logger2 = new LoggerClz( 'bar' );
function test() {
Logger1.info( '123' ); // INFO 1644750929128 foo 123 [script.js:18]
Logger2.info( '456' ); // INFO 1644750929128 bar 456 [script.js:19]
}
test();
A little variation is to to have debug() return a function, which is then executed where you need it - debug(message)(); and so properly shows the correct line number and calling script in the console window, while allowing for variations like redirecting as an alert, or saving to file.
var debugmode='console';
var debugloglevel=3;
function debug(msg, type, level) {
if(level && level>=debugloglevel) {
return(function() {});
}
switch(debugmode) {
case 'alert':
return(alert.bind(window, type+": "+msg));
break;
case 'console':
return(console.log.bind(window.console, type+": "+msg));
break;
default:
return (function() {});
}
}
Since it returns a function, that function needs to be executed at the debug line with ();. Secondly, the message is sent to the debug function, rather than into the returned function allowing pre-processing or checking that you might need, such as checking log-level state, making the message more readable, skipping different types, or only reporting items meeting the log level criteria;
debug(message, "serious", 1)();
debug(message, "minor", 4)();
You can use optional chaining to really simplify this. You get full access to the console object with no hacks and concise syntax.
const debug = (true) ? console : null;
debug?.log('test');
debug?.warn('test');
debug?.error('test')
If debug == null, everything after the ? is ignored with no error thrown about inaccessible properties.
const debug = (false) ? console : null;
debug?.error('not this time');
This also lets you use the debug object directly as a conditional for other debug related processes besides logging.
const debug = (true) ? console : null;
let test = false;
function doSomething() {
test = true;
debug?.log('did something');
}
debug && doSomething();
if (debug && test == false) {
debug?.warn('uh-oh');
} else {
debug?.info('perfect');
}
if (!debug) {
// set up production
}
If you want, you can override the various methods with a no-op based on your desired log level.
const debug = (true) ? console : null;
const quiet = true; const noop = ()=>{};
if (debug && quiet) {
debug.info = noop;
debug.warn = noop;
}
debug?.log('test');
debug?.info('ignored in quiet mode');
debug?.warn('me too');
//isDebug controls the entire site.
var isDebug = true;
//debug.js
function debug(msg, level){
var Global = this;
if(!(Global.isDebug && Global.console && Global.console.log)){
return;
}
level = level||'info';
return 'console.log(\'' + level + ': '+ JSON.stringify(msg) + '\')';
}
//main.js
eval(debug('Here is a msg.'));
This will give me info: "Here is a msg." main.js(line:2).
But the extra eval is needed, pity.
I have been looking at this issue myself lately. Needed something very straight forward to control logging, but also to retain line numbers. My solution is not looking as elegant in code, but provides what is needed for me. If one is careful enough with closures and retaining.
I've added a small wrapper to the beginning of the application:
window.log = {
log_level: 5,
d: function (level, cb) {
if (level < this.log_level) {
cb();
}
}
};
So that later I can simply do:
log.d(3, function(){console.log("file loaded: utils.js");});
I've tested it of firefox and crome, and both browsers seem to show console log as intended. If you fill like that, you can always extend the 'd' method and pass other parameters to it, so that it can do some extra logging.
Haven't found any serious drawbacks for my approach yet, except the ugly line in code for logging.
This implementation is based on the selected answer and helps reduce the amount of noise in the error console: https://stackoverflow.com/a/32928812/516126
var Logging = Logging || {};
const LOG_LEVEL_ERROR = 0,
LOG_LEVEL_WARNING = 1,
LOG_LEVEL_INFO = 2,
LOG_LEVEL_DEBUG = 3;
Logging.setLogLevel = function (level) {
const NOOP = function () { }
Logging.logLevel = level;
Logging.debug = (Logging.logLevel >= LOG_LEVEL_DEBUG) ? console.log.bind(window.console) : NOOP;
Logging.info = (Logging.logLevel >= LOG_LEVEL_INFO) ? console.log.bind(window.console) : NOOP;
Logging.warning = (Logging.logLevel >= LOG_LEVEL_WARNING) ? console.log.bind(window.console) : NOOP;
Logging.error = (Logging.logLevel >= LOG_LEVEL_ERROR) ? console.log.bind(window.console) : NOOP;
}
Logging.setLogLevel(LOG_LEVEL_INFO);
Here's my logger function (based on some of the answers). Hope someone can make use of it:
const DEBUG = true;
let log = function ( lvl, msg, fun ) {};
if ( DEBUG === true ) {
log = function ( lvl, msg, fun ) {
const d = new Date();
const timestamp = '[' + d.getHours() + ':' + d.getMinutes() + ':' +
d.getSeconds() + '.' + d.getMilliseconds() + ']';
let stackEntry = new Error().stack.split( '\n' )[2];
if ( stackEntry === 'undefined' || stackEntry === null ) {
stackEntry = new Error().stack.split( '\n' )[1];
}
if ( typeof fun === 'undefined' || fun === null ) {
fun = stackEntry.substring( stackEntry.indexOf( 'at' ) + 3,
stackEntry.lastIndexOf( ' ' ) );
if ( fun === 'undefined' || fun === null || fun.length <= 1 ) {
fun = 'anonymous';
}
}
const idx = stackEntry.lastIndexOf( '/' );
let file;
if ( idx !== -1 ) {
file = stackEntry.substring( idx + 1, stackEntry.length - 1 );
} else {
file = stackEntry.substring( stackEntry.lastIndexOf( '\\' ) + 1,
stackEntry.length - 1 );
}
if ( file === 'undefined' || file === null ) {
file = '<>';
}
const m = timestamp + ' ' + file + '::' + fun + '(): ' + msg;
switch ( lvl ) {
case 'log': console.log( m ); break;
case 'debug': console.log( m ); break;
case 'info': console.info( m ); break;
case 'warn': console.warn( m ); break;
case 'err': console.error( m ); break;
default: console.log( m ); break;
}
};
}
Examples:
log( 'warn', 'log message', 'my_function' );
log( 'info', 'log message' );
For Angular / Typescript console logger with correct line number you can do the following:
example file: console-logger.ts
export class Log {
static green(title: string): (...args: any) => void {
return console.log.bind(console, `%c${title}`, `background: #222; color: #31A821`);
}
static red(title: string): (...args: any) => void {
return console.log.bind(console, `%c${title}`, `background: #222; color: #DA5555`);
}
static blue(title: string): (...args: any) => void {
return console.log.bind(console, `%c${title}`, `background: #222; color: #5560DA`);
}
static purple(title: string): (...args: any) => void {
return console.log.bind(console, `%c${title}`, `background: #222; color: #A955DA`);
}
static yellow(title: string): (...args: any) => void {
return console.log.bind(console, `%c${title}`, `background: #222; color: #EFEC47`);
}
}
Then call it from any other file:
example file: auth.service.ts
import { Log } from 'path to console-logger.ts';
const user = { user: '123' }; // mock data
Log.green('EXAMPLE')();
Log.red('EXAMPLE')(user);
Log.blue('EXAMPLE')(user);
Log.purple('EXAMPLE')(user);
Log.yellow('EXAMPLE')(user);
It will look like this in the console:
Stackblitz example
I found some of the answers to this problem a little too complex for my needs. Here is a simple solution, rendered in Coffeescript. It'a adapted from Brian Grinstead's version here
It assumes the global console object.
# exposes a global 'log' function that preserves line numbering and formatting.
(() ->
methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn']
noop = () ->
# stub undefined methods.
for m in methods when !console[m]
console[m] = noop
if Function.prototype.bind?
window.log = Function.prototype.bind.call(console.log, console);
else
window.log = () ->
Function.prototype.apply.call(console.log, console, arguments)
)()
Code from http://www.briangrinstead.com/blog/console-log-helper-function:
// Full version of `log` that:
// * Prevents errors on console methods when no console present.
// * Exposes a global 'log' function that preserves line numbering and formatting.
(function () {
var method;
var noop = function () { };
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
if (Function.prototype.bind) {
window.log = Function.prototype.bind.call(console.log, console);
}
else {
window.log = function() {
Function.prototype.apply.call(console.log, console, arguments);
};
}
})();
var a = {b:1};
var d = "test";
log(a, d);
window.line = function () {
var error = new Error(''),
brower = {
ie: !-[1,], // !!window.ActiveXObject || "ActiveXObject" in window
opera: ~window.navigator.userAgent.indexOf("Opera"),
firefox: ~window.navigator.userAgent.indexOf("Firefox"),
chrome: ~window.navigator.userAgent.indexOf("Chrome"),
safari: ~window.navigator.userAgent.indexOf("Safari"), // /^((?!chrome).)*safari/i.test(navigator.userAgent)?
},
todo = function () {
// TODO:
console.error('a new island was found, please told the line()\'s author(roastwind)');
},
line = (function(error, origin){
// line, column, sourceURL
if(error.stack){
var line,
baseStr = '',
stacks = error.stack.split('\n');
stackLength = stacks.length,
isSupport = false;
// mac版本chrome(55.0.2883.95 (64-bit))
if(stackLength == 11 || brower.chrome){
line = stacks[3];
isSupport = true;
// mac版本safari(10.0.1 (12602.2.14.0.7))
}else if(brower.safari){
line = stacks[2];
isSupport = true;
}else{
todo();
}
if(isSupport){
line = ~line.indexOf(origin) ? line.replace(origin, '') : line;
line = ~line.indexOf('/') ? line.substring(line.indexOf('/')+1, line.lastIndexOf(':')) : line;
}
return line;
}else{
todo();
}
return '😭';
})(error, window.location.origin);
return line;
}
window.log = function () {
var _line = window.line.apply(arguments.callee.caller),
args = Array.prototype.slice.call(arguments, 0).concat(['\t\t\t#'+_line]);
window.console.log.apply(window.console, args);
}
log('hello');
here was my solution about this question. when you call the method: log, it will print the line number where you print your log
The way I solved it was to create an object, then create a new property on the object using Object.defineProperty() and return the console property, which was then used as the normal function, but now with the extended abilty.
var c = {};
var debugMode = true;
var createConsoleFunction = function(property) {
Object.defineProperty(c, property, {
get: function() {
if(debugMode)
return console[property];
else
return function() {};
}
});
};
Then, to define a property you just do...
createConsoleFunction("warn");
createConsoleFunction("log");
createConsoleFunction("trace");
createConsoleFunction("clear");
createConsoleFunction("error");
createConsoleFunction("info");
And now you can use your function just like
c.error("Error!");
Based on other answers (mainly #arctelix one) I created this for Node ES6, but a quick test showed good results in the browser as well. I'm just passing the other function as a reference.
let debug = () => {};
if (process.argv.includes('-v')) {
debug = console.log;
// debug = console; // For full object access
}
Nothing here really had what I needed so I add my own approach: Overriding the console and reading the original error line from a synthetic Error. The example stores the console warns and errors to console.appTrace, having errors very detailed and verbose; in such way that simple (console.appTrace.join("") tells me all I need from the user session.
Note that this works as of now only on Chrome
(function () {
window.console.appTrace = [];
const defaultError = console.error;
const timestamp = () => {
let ts = new Date(), pad = "000", ms = ts.getMilliseconds().toString();
return ts.toLocaleTimeString("cs-CZ") + "." + pad.substring(0, pad.length - ms.length) + ms + " ";
};
window.console.error = function () {
window.console.appTrace.push("ERROR ",
(new Error().stack.split("at ")[1]).trim(), " ",
timestamp(), ...arguments, "\n");
defaultError.apply(window.console, arguments);
};
const defaultWarn = console.warn;
window.console.warn = function () {
window.console.appTrace.push("WARN ", ...arguments, "\n");
defaultWarn.apply(window.console, arguments);
};
})();
inspired by Get name and line of calling function in node.js and date formatting approach in this thread.
This is what worked for me. It creates a new object with all the functionality of the original console object and retains the console object.
let debugOn=true; // we can set this from the console or from a query parameter, for example (&debugOn=true)
const noop = () => { }; // dummy function.
const debug = Object.create(console); // creates a deep copy of the console object. This retains the console object so we can use it when we need to and our new debug object has all the properties and methods of the console object.
let quiet = false;
debug.log = (debugOn) ? debug.log : noop;
if (debugOn&&quiet) {
debug.info = noop;
debug.warn = noop;
debug.assert = noop;
debug.error = noop;
debug.debug = noop;
}
console.log(`we should see this with debug off or on`);
debug.log(`we should not see this with debugOn=false`);
All the solutions here dance around the real problem -- the debugger should be able to ignore part of the stack to give meaningful lines. VSCode's js debugger can now do this. At the time of this edit, the feature is available via the nightly build of the js-debug extension. See the link in the following paragraph.
I proposed a feature for VSCode's debugger here that ignores the top of the stack that resides in any of the skipFiles file paths of the launch configuration. The property is in the launch.json config of your vscode workspace. So you can create a file/module responsible for wrapping console.log, add it to the skipFiles and the debugger will show the line that called into your skipped file rather than console.log itself.
It is in the nightly build of the js-debug extension. It looks like it could be in the next minor release of visual studio code. I've verified it works using the nightly build. No more hacky workarounds, yay!
let debug = console.log.bind(console);
let error = console.error.bind(console);
debug('debug msg');
error('more important message');
Reading for noobs:
bind (function): https://www.w3schools.com/js/js_function_bind.asp
chrome console (object): https://developer.mozilla.org/en-US/docs/Web/API/console
function: https://www.w3schools.com/js/js_functions.asp
object: https://www.w3schools.com/js/js_objects.asp

error in javascript or no clue

I got the following javascript code.
And Basically, it works on FF, and IE with developer Tools.
$(function(){
console.log("it is ok");
var mybutton="";
alert("ready1");
$('button[name="delorder"]').click(function(){
console.log($(this).val()+"hay i got a click");
mybutton=$(this).val();
alert("a click1");
$.ajax({
type:'POST',
url:'deleteorderitem.php',
data:mybutton,
success:function(result){
if((result.indexOf("t") < 3) && (result.indexOf("t") >= 0)){
$('#orderresult').html(result);
console.log("i am 3 ");
console.log("index of t is "+result.indexOf("t"));
}else{
console.log("i am 4");
console.log("index of t is "+result.indexOf("t"));
$('#divOrderButton').hide();
$('#orderresult').html("");
$('#divNoinfo').html("There is no record to display at the moment.");
$('#divNoinfo').show();
$('#divOrder').hide();
}
}
});
});
});
</script>
But , it does NOT WORK on IE (without developer tools).
so, any advice will be appreciated.
Thanks
It is mostly because of
console.log()
Windows IE8 and below has no console object when the Developer tools is not open.
Either comment out the lines that says console. Or create the console object beforehand.
Try this ... Not sure if this is the correct way around..
var alertFallback = true;
if (typeof console === "undefined" || typeof console.log === "undefined") {
console = {};
if (alertFallback) {
console.log = function(msg) {
alert(msg);
};
} else {
console.log = function() {};
}
}
This will create the console object if it is not present.
If you're saying it doesn't work without developer tools open, (unless I'm mistaken) it is because you have all those console.log's and that must be what's blowing it up.
Try something like this at the very top of a master JS file to prevent that in IE.
if (typeof (console) === 'undefined' || !console) {
window.console = {};
window.console.log = function () { return; };
}
I use this function to write logs for cross browser console log :
/**
*Log into the console if defined
*/
function log(msg)
{
if (typeof console != "undefined") {
console.log(msg);
}
}

How do I print debug messages in the Google Chrome JavaScript Console?

How do I print debug messages in the Google Chrome JavaScript Console?
Please note that the JavaScript Console is not the same as the JavaScript Debugger; they have different syntaxes AFAIK, so the print command in JavaScript Debugger will not work here. In the JavaScript Console, print() will send the parameter to the printer.
Executing following code from the browser address bar:
javascript: console.log(2);
successfully prints message to the "JavaScript Console" in Google Chrome.
Improving on Andru's idea, you can write a script which creates console functions if they don't exist:
if (!window.console) console = {};
console.log = console.log || function(){};
console.warn = console.warn || function(){};
console.error = console.error || function(){};
console.info = console.info || function(){};
Then, use any of the following:
console.log(...);
console.error(...);
console.info(...);
console.warn(...);
These functions will log different types of items (which can be filtered based on log, info, error or warn) and will not cause errors when console is not available. These functions will work in Firebug and Chrome consoles.
Just add a cool feature which a lot of developers miss:
console.log("this is %o, event is %o, host is %s", this, e, location.host);
This is the magical %o dump clickable and deep-browsable content of a JavaScript object. %s was shown just for a record.
Also this is cool too:
console.log("%s", new Error().stack);
Which gives a Java-like stack trace to the point of the new Error() invocation (including path to file and line number!).
Both %o and new Error().stack are available in Chrome and Firefox!
Also for stack traces in Firefox use:
console.trace();
As https://developer.mozilla.org/en-US/docs/Web/API/console says.
Happy hacking!
UPDATE: Some libraries are written by bad people which redefine the console object for their own purposes. To restore the original browser console after loading library, use:
delete console.log;
delete console.warn;
....
See Stack Overflow question Restoring console.log().
Just a quick warning - if you want to test in Internet Explorer without removing all console.log()'s, you'll need to use Firebug Lite or you'll get some not particularly friendly errors.
(Or create your own console.log() which just returns false.)
Here is a short script which checks if the console is available. If it is not, it tries to load Firebug and if Firebug is not available it loads Firebug Lite. Now you can use console.log in any browser. Enjoy!
if (!window['console']) {
// Enable console
if (window['loadFirebugConsole']) {
window.loadFirebugConsole();
}
else {
// No console, use Firebug Lite
var firebugLite = function(F, i, r, e, b, u, g, L, I, T, E) {
if (F.getElementById(b))
return;
E = F[i+'NS']&&F.documentElement.namespaceURI;
E = E ? F[i + 'NS'](E, 'script') : F[i]('script');
E[r]('id', b);
E[r]('src', I + g + T);
E[r](b, u);
(F[e]('head')[0] || F[e]('body')[0]).appendChild(E);
E = new Image;
E[r]('src', I + L);
};
firebugLite(
document, 'createElement', 'setAttribute', 'getElementsByTagName',
'FirebugLite', '4', 'firebug-lite.js',
'releases/lite/latest/skin/xp/sprite.png',
'https://getfirebug.com/', '#startOpened');
}
}
else {
// Console is already available, no action needed.
}
In addition to Delan Azabani's answer, I like to share my console.js, and I use for the same purpose. I create a noop console using an array of function names, what is in my opinion a very convenient way to do this, and I took care of Internet Explorer, which has a console.log function, but no console.debug:
// Create a noop console object if the browser doesn't provide one...
if (!window.console){
window.console = {};
}
// Internet Explorer has a console that has a 'log' function, but no 'debug'. To make console.debug work in Internet Explorer,
// We just map the function (extend for info, etc. if needed)
else {
if (!window.console.debug && typeof window.console.log !== 'undefined') {
window.console.debug = window.console.log;
}
}
// ... and create all functions we expect the console to have (taken from Firebug).
var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
"group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
for (var i = 0; i < names.length; ++i){
if(!window.console[names[i]]){
window.console[names[i]] = function() {};
}
}
Or use this function:
function log(message){
if (typeof console == "object") {
console.log(message);
}
}
Here's my console wrapper class. It gives me scope output as well to make life easier. Note the use of localConsole.debug.call() so that localConsole.debug runs in the scope of the calling class, providing access to its toString method.
localConsole = {
info: function(caller, msg, args) {
if ( window.console && window.console.info ) {
var params = [(this.className) ? this.className : this.toString() + '.' + caller + '(), ' + msg];
if (args) {
params = params.concat(args);
}
console.info.apply(console, params);
}
},
debug: function(caller, msg, args) {
if ( window.console && window.console.debug ) {
var params = [(this.className) ? this.className : this.toString() + '.' + caller + '(), ' + msg];
if (args) {
params = params.concat(args);
}
console.debug.apply(console, params);
}
}
};
someClass = {
toString: function(){
return 'In scope of someClass';
},
someFunc: function() {
myObj = {
dr: 'zeus',
cat: 'hat'
};
localConsole.debug.call(this, 'someFunc', 'myObj: ', myObj);
}
};
someClass.someFunc();
This gives output like so in Firebug:
In scope of someClass.someFunc(), myObj: Object { dr="zeus", more...}
Or Chrome:
In scope of someClass.someFunc(), obj:
Object
cat: "hat"
dr: "zeus"
__proto__: Object
Personally I use this, which is similar to tarek11011's:
// Use a less-common namespace than just 'log'
function myLog(msg)
{
// Attempt to send a message to the console
try
{
console.log(msg);
}
// Fail gracefully if it does not exist
catch(e){}
}
The main point is that it's a good idea to at least have some practice of logging other than just sticking console.log() right into your JavaScript code, because if you forget about it, and it's on a production site, it can potentially break all of the JavaScript code for that page.
You could use console.log() if you have a debugged code in what programming software editor you have and you will see the output mostly likely the best editor for me (Google Chrome). Just press F12 and press the Console tab. You will see the result. Happy coding. :)
I've had a lot of issues with developers checking in their console.() statements. And, I really don't like debugging Internet Explorer, despite the fantastic improvements of Internet Explorer 10 and Visual Studio 2012, etc.
So, I've overridden the console object itself... I've added a __localhost flag that only allows console statements when on localhost. I also added console.() functions to Internet Explorer (that displays an alert() instead).
// Console extensions...
(function() {
var __localhost = (document.location.host === "localhost"),
__allow_examine = true;
if (!console) {
console = {};
}
console.__log = console.log;
console.log = function() {
if (__localhost) {
if (typeof console !== "undefined" && typeof console.__log === "function") {
console.__log(arguments);
} else {
var i, msg = "";
for (i = 0; i < arguments.length; ++i) {
msg += arguments[i] + "\r\n";
}
alert(msg);
}
}
};
console.__info = console.info;
console.info = function() {
if (__localhost) {
if (typeof console !== "undefined" && typeof console.__info === "function") {
console.__info(arguments);
} else {
var i, msg = "";
for (i = 0; i < arguments.length; ++i) {
msg += arguments[i] + "\r\n";
}
alert(msg);
}
}
};
console.__warn = console.warn;
console.warn = function() {
if (__localhost) {
if (typeof console !== "undefined" && typeof console.__warn === "function") {
console.__warn(arguments);
} else {
var i, msg = "";
for (i = 0; i < arguments.length; ++i) {
msg += arguments[i] + "\r\n";
}
alert(msg);
}
}
};
console.__error = console.error;
console.error = function() {
if (__localhost) {
if (typeof console !== "undefined" && typeof console.__error === "function") {
console.__error(arguments);
} else {
var i, msg = "";
for (i = 0; i < arguments.length; ++i) {
msg += arguments[i] + "\r\n";
}
alert(msg);
}
}
};
console.__group = console.group;
console.group = function() {
if (__localhost) {
if (typeof console !== "undefined" && typeof console.__group === "function") {
console.__group(arguments);
} else {
var i, msg = "";
for (i = 0; i < arguments.length; ++i) {
msg += arguments[i] + "\r\n";
}
alert("group:\r\n" + msg + "{");
}
}
};
console.__groupEnd = console.groupEnd;
console.groupEnd = function() {
if (__localhost) {
if (typeof console !== "undefined" && typeof console.__groupEnd === "function") {
console.__groupEnd(arguments);
} else {
var i, msg = "";
for (i = 0; i < arguments.length; ++i) {
msg += arguments[i] + "\r\n";
}
alert(msg + "\r\n}");
}
}
};
/// <summary>
/// Clever way to leave hundreds of debug output messages in the code,
/// but not see _everything_ when you only want to see _some_ of the
/// debugging messages.
/// </summary>
/// <remarks>
/// To enable __examine_() statements for sections/groups of code, type the
/// following in your browser's console:
/// top.__examine_ABC = true;
/// This will enable only the console.examine("ABC", ... ) statements
/// in the code.
/// </remarks>
console.examine = function() {
if (!__allow_examine) {
return;
}
if (arguments.length > 0) {
var obj = top["__examine_" + arguments[0]];
if (obj && obj === true) {
console.log(arguments.splice(0, 1));
}
}
};
})();
Example use:
console.log("hello");
Chrome/Firefox:
prints hello in the console window.
Internet Explorer:
displays an alert with 'hello'.
For those who look closely at the code, you'll discover the console.examine() function. I created this years ago so that I can leave debug code in certain areas around the product to help troubleshoot QA/customer issues. For instance, I would leave the following line in some released code:
function doSomething(arg1) {
// ...
console.examine("someLabel", arg1);
// ...
}
And then from the released product, type the following into the console (or address bar prefixed with 'javascript:'):
top.__examine_someLabel = true;
Then, I will see all of the logged console.examine() statements. It's been a fantastic help many times over.
Simple Internet Explorer 7 and below shim that preserves line numbering for other browsers:
/* Console shim */
(function () {
var f = function () {};
if (!window.console) {
window.console = {
log:f, info:f, warn:f, debug:f, error:f
};
}
}());
console.debug("");
Using this method prints out the text in a bright blue color in the console.
Improving further on ideas of Delan and Andru (which is why this answer is an edited version); console.log is likely to exist whilst the other functions may not, so have the default map to the same function as console.log....
You can write a script which creates console functions if they don't exist:
if (!window.console) console = {};
console.log = console.log || function(){};
console.warn = console.warn || console.log; // defaults to log
console.error = console.error || console.log; // defaults to log
console.info = console.info || console.log; // defaults to log
Then, use any of the following:
console.log(...);
console.error(...);
console.info(...);
console.warn(...);
These functions will log different types of items (which can be filtered based on log, info, error or warn) and will not cause errors when console is not available. These functions will work in Firebug and Chrome consoles.
Even though this question is old, and has good answers, I want to provide an update on other logging capabilities.
You can also print with groups:
console.group("Main");
console.group("Feature 1");
console.log("Enabled:", true);
console.log("Public:", true);
console.groupEnd();
console.group("Feature 2");
console.log("Enabled:", false);
console.warn("Error: Requires auth");
console.groupEnd();
Which prints:
This is supported by all major browsers according to this page:

Categories

Resources