console.log formatting for dates and objects - javascript

How can we format a value into a string to be consistent with how console.log(value) does it?
I need to append extra details to each value I am printing, without breaking the default formatting provided by console.log. It is easy for simple values, but for such types as Date and Object it is more complicated.
Is there a way I can make it consistent with console.log? In other words, how to format a value to be the same string as we get from console.log(value)?
I'm trying to implement a simple library manakin. Here's its complete source code:
'use strict';
(function () {
var error = console.error, warn = console.warn;
console.error = function () {
var a = arguments;
error.apply(this, Object.keys(a).map(function (key) {
return "\u001b[31m" + a[key] + "\u001b[0m";
}));
};
console.warn = function () {
var a = arguments;
warn.apply(this, Object.keys(a).map(function (key) {
return "\u001b[33m" + a[key] + "\u001b[0m";
}));
};
})();
The problem I am having is that for types Date and Object the output is different:
// without manakin:
console.warn({value: 1});
//=> { value: 1 }
// with manakin:
console.warn({value: 1});
//=> [object Object]
And I want to make it consistent.
SOLVED
In the end I figured out how to make it all work in both both Node.js and in all browsers, see manakin source code (it is small).
It required different implementation for Node.js and for the browsers. Specifically under Node.js it uses util.inspect.

I believe if you modify the code in warn to be:
console.warn = function () {
var a = arguments;
warn.apply(this, Object.keys(a).map(function (key) {
if (a[key] instanceof Date) {
return "\u001b[33m" + a[key].toString() + "\u001b[0m";
}
return "\u001b[33m" + JSON.stringify(a[key]) + "\u001b[0m";
}));
};
you have what you're looking for. I tested it out by just pasting the new code in the console and logging the examples you have, hope that works for you!

Related

Get line number with abstract syntax tree in node js

Im making a program that takes some code via parameter, and transform the code adding some console.logs to the code. This is the program:
const escodegen = require('escodegen');
const espree = require('espree');
const estraverse = require('estraverse');
function addLogging(code) {
const ast = espree.parse(code);
estraverse.traverse(ast, {
enter: function(node, parent) {
if (node.type === 'FunctionDeclaration' ||
node.type === 'FunctionExpression') {
addBeforeCode(node);
}
}
});
return escodegen.generate(ast);
}
function addBeforeCode(node) {
const name = node.id ? node.id.name : '<anonymous function>';
const beforeCode = "console.log('Entering " + name + "()');";
const beforeNodes = espree.parse(beforeCode).body;
node.body.body = beforeNodes.concat(node.body.body);
}
So if we pass this code to the function:
console.log(addLogging(`
function foo(a, b) {
var x = 'blah';
var y = (function () {
return 3;
})();
}
foo(1, 'wut', 3);
`));
This is the output of this program:
function foo(a, b) {
console.log('Entering foo()');
var x = 'blah';
var y = function () {
console.log('Entering <anonymous function>()');
return 3;
}();
}
foo(1, 'wut', 3);
And this is the AST (Abstract Syntax Tree) for that last function passed to addLoggin:
https://astexplorer.net/#/gist/b5826862c47dfb7dbb54cec15079b430/latest
So i wanted to add more information to the console logs like for example the line number we are on. As far as i know, in the ast, the node has a value caled 'start' and 'end' which indicates in which character that node starts and where it ends. How can i use this to get the line number we are on? Seems pretty confusing to me to be honest. I was thinking about doing a split of the file by "\n", so that way i have the total line numbers, but then how can i know i which one im on?
Thank you in advance.
Your idea is fine. First find the offsets in the original code where each line starts. Then compare the start index of the node with those collected indexes to determine the line number.
I will assume here that you want the reported line number to refer to the original code, not the code as it is returned by your function.
So from bottom up, make the following changes. First expect the line number as argument to addBeforeCode:
function addBeforeCode(node, lineNum) {
const name = node.id ? node.id.name : '<anonymous function>';
const beforeCode = `console.log("${lineNum}: Entering ${name}()");`;
const beforeNodes = espree.parse(beforeCode).body;
node.body.body = beforeNodes.concat(node.body.body);
}
Define a function to collect the offsets in the original code that correspond to the starts of the lines:
function getLineOffsets(str) {
const regex = /\r?\n/g;
const offsets = [0];
while (regex.exec(str)) offsets.push(regex.lastIndex);
offsets.push(str.length);
return offsets;
}
NB: If you have support for matchAll, then the above can be written a bit more concise.
Then use the above in your main function:
function addLogging(code) {
const lineStarts = getLineOffsets(code); // <---
let lineNum = 0; // <---
const ast = espree.parse(code);
estraverse.traverse(ast, {
enter: function(node, parent) {
if (node.type === 'FunctionDeclaration' ||
node.type === 'FunctionExpression') {
// Look for the corresponding line number in the source code:
while (lineStarts[lineNum] < node.body.body[0].start) lineNum++;
// Actually we now went one line too far, so pass one less:
addBeforeCode(node, lineNum-1);
}
}
});
return escodegen.generate(ast);
}
Unrelated to your question, but be aware that functions can be arrow functions, which have an expression syntax. So they would not have a block, and you would not be able to inject a console.log in the same way. You might want to make your code capable to deal with that, or alternatively, to skip over those.

How to build a namespace-like string using chained variables

This is a strange one, but I'm exploring it to see if it's possible.
Let's say that I have a .NET application where I am using PubSub. I want a way to define the topic string using chained objects (not functions). The goal is to allow me a way of defining strings that lets me to take advantage of Visual Studio's IntelliSense and reduce the likelihood of spelling errors.
Here's an example:
/* Manual way */
var topic = "App.Navigation.CurrentItem"
/* Desired Solution */
// ... define the objects here ...
var topic = App.Navigation.CurrentItem;
console.log(topic); // "App.Navigation.CurrentItem"
var topic2 = App.Footer.CurrentItem;
console.log(topic2); // "App.Footer.CurrentItem"
I'd like each object to be responsible for outputing it's own value, and have the chaining process responsible for joining itself to the previous chained object via a predefined separator (in my case, a period [.]).
I've been playing with JavaScript getter syntax, but I'm curious if there's a better way.
Has anyone done something like this before, and if so, how did you solve it?
You're requirements aren't totally clear to me, but are you looking for something like this?
function namespace(ns) { this._ns = ns; }
namespace.prototype.toString = function() {return this._ns};
namespace.prototype.extend = function(suffix) {
return new namespace(this._ns + "." + suffix)
};
Usage:
App = new namespace('App');
App.Navigation = App.extend('Navigation');
App.Navigation.CurrentItem = App.Navigation.extend('CurrentItem');
console.log(App.Navigation.CurrentItem.toString()); // "App.Navigation.CurrentItem"
This is what I ended up with after reviewing StriplingWarrior's answer:
function Namespace(name, config) {
if (typeof name === "object") {
config = name;
name = null;
}
config = config || {};
this._ns = name;
this.define(config);
}
Namespace.prototype.toString = function() { return this._ns };
Namespace.prototype.define = function(config, base) {
base = base || this;
for (key in config) {
var name = (base._ns) ? base._ns + "." + key : key;
base[key] = new Namespace(name);
base.define(config[key], base[key]);
}
return base;
};
Usage:
var App = new Namespace("App", {
Navigation: {
Items: {
Current: {}
}
},
Content: {},
Footer: {
Items: {
Current: {}
}
}
});
console.log(App.toString()); // App
console.log(App.Navigation.Items.Current.toString()); // App.Navigation.Items.Current
console.log(App.Footer.toString()); // App.Footer
I also wrote a convenience method to reduce the toString():
function NS(namespace) {
return namespace.toString();
}
console.log(NS(App.Navigation.Items.Current));
Thanks again to StriplingWarrior for the the help!

Does LocalStorage support Custom (i.e. non-primitive type) Object Storage and Retrieval in any way?

So I would like to pass an object "Hello" in JavaScript file hello.js to another JavaScript file chat.js.
Hello contains members such as Strophe.Connections, and others.
I read that I could use LocalStorage, i.e. LocalStorage.SetItem("Hello", Hello) and then retrieve the object using LocalStorage.getItem("Hello").
This did not work for me, so I searched a bit more and found JSON stringify, e.g. someone at Storing Objects in HTML5 localStorage and also at How to send javascript object from one page to another page? suggested the use of stringify.
So I tried this as well, and here is the relevant code of Hello.js:
var Hello = {
connection: null,
start_time: null,
log: function (msg) {
$('#log').append("<p>" + msg + "</p>");
},
send_ping: function (to) {
var ping = $iq({
to: to,
type: "get",
id: "ping1"}).c("ping", {xmlns: "urn:xmpp:ping"});
Hello.log("Sending ping to " + to + ".");
console.log("Sending ping to " + to + ".");
Hello.start_time = (new Date()).getTime();
Hello.connection.send(ping);
},
handle_pong: function (iq) {
var elapsed = (new Date()).getTime() - Hello.start_time;
Hello.log("Received pong from server in " + elapsed + "ms.");
console.log('Received pong from server in " + elapsed + "ms.');
localStorage.setItem("hello", JSON.stringify(Hello));
return false;
}
};
Here is chat.js
var Hello = {
conn: null
};
$(document).ready(function(e) {
Hello = JSON.parse(localStorage.getItem("hello"));
$('#input3').bind('click',
Hello.connection.send("someStanza"))});
On line Hello = JSON.parse(localStorage.getItem("hello")); I try to restore the object.
And 2 line beow I call Hello.connection.send. However, here it becomes clear that I was not able to pass and restore the Hello object correctly. In Google Chrome JavaScript debugger, for example, I get an error at that line stating "Uncaught TypeError: undefined is not a function", which I would say means basically that the Chrome JS engine was not able to find any connection.send member in the Hello Object.
This leaves two options. Either what I am trying to do (passing an object that is not a primitive data type) is not possible in the way I am doing it. Or, that it is possible in the way I am doing it, and there is simply some other error/problem I am not seeing.
If it is possible, what am I doing wrong?
If it isn't possible to pass a non-primitive data type in this way, how else can I do it?
Hope I made myself clear enough for understanding,
Thanks, br,
Chris
One workaround is to toString the function and then store it in localStorage. Then, when you retrieve the object from localStorage, you eval the function. Here's a quick demo that demonstrates (it's very stupid and can be optimized/enhanced based on your needs...):
http://jsfiddle.net/nmef7utv/
function pack(obj){
var packedObj = {};
for (key in obj) {
// If obj property is a function, toString() it.
if (obj[key] && obj[key].constructor === Function) {
packedObj[key] = obj[key].toString();
} else {
packedObj[key] = obj[key];
}
}
return JSON.stringify(packedObj);
}
function unpack(obj) {
// Temporary variable to hold eval'd func, if needed
var temp;
// Parse obj to loop
obj = JSON.parse(obj);
for (key in obj) {
if (typeof obj[key] === "string") {
eval('temp =' + obj[key]);
// Assign eval'd function
obj[key] = temp;
} else {
obj[key] = obj[key];
}
}
return obj;
}
In the fiddle, I have:
// Packed Item
localStorage.setItem('test', pack(Hello));
// Unpack
testObj = unpack(localStorage.getItem('test'));
testObj.handle_pong();
Hope this is of help!

console.log timestamps in Chrome?

Is there any quick way of getting Chrome to output timestamps in console.log writes (like Firefox does). Or is prepending new Date().getTime() the only option?
In Chrome, there is the option in Console Settings (Either press F1 or select Developer Tools -> Console -> Settings [upper-right corner] ) named "Show timestamps" which is exactly what I needed.
I've just found it. No other dirty hacks needed that destroys placeholders and erases place in the code where the messages was logged from.
Update for Chrome 68+
The "Show timestamps" setting has been moved to the Preferences pane of the "DevTools settings", found in the upper-right corner of the DevTools drawer:
Try this:
console.logCopy = console.log.bind(console);
console.log = function(data)
{
var currentDate = '[' + new Date().toUTCString() + '] ';
this.logCopy(currentDate, data);
};
Or this, in case you want a timestamp:
console.logCopy = console.log.bind(console);
console.log = function(data)
{
var timestamp = '[' + Date.now() + '] ';
this.logCopy(timestamp, data);
};
To log more than one thing and in a nice way (like object tree representation):
console.logCopy = console.log.bind(console);
console.log = function()
{
if (arguments.length)
{
var timestamp = '[' + Date.now() + '] ';
this.logCopy(timestamp, arguments);
}
};
With format string (JSFiddle)
console.logCopy = console.log.bind(console);
console.log = function()
{
// Timestamp to prepend
var timestamp = new Date().toJSON();
if (arguments.length)
{
// True array copy so we can call .splice()
var args = Array.prototype.slice.call(arguments, 0);
// If there is a format string then... it must
// be a string
if (typeof arguments[0] === "string")
{
// Prepend timestamp to the (possibly format) string
args[0] = "%o: " + arguments[0];
// Insert the timestamp where it has to be
args.splice(1, 0, timestamp);
// Log the whole array
this.logCopy.apply(this, args);
}
else
{
// "Normal" log
this.logCopy(timestamp, args);
}
}
};
Outputs with that:
P.S.: Tested in Chrome only.
P.P.S.: Array.prototype.slice is not perfect here for it would be logged as an array of objects rather than a series those of.
I originally added this as a comment, but I wanted to add a screenshot as at least one person could not find the option (or maybe it was not available in their particular version for some reason).
On Chrome 68.0.3440.106 (and now checked in 72.0.3626.121) I had to
open dev tools (F12)
click the three-dot menu in the top right
click settings
select Preferences in the left menu
check show timestamps in the Console section of the settings screen
You can use dev tools profiler.
console.time('Timer name');
//do critical time stuff
console.timeEnd('Timer name');
"Timer name" must be the same. You can use multiple instances of timer with different names.
I convert arguments to Array using Array.prototype.slice so that I can concat with another Array of what I want to add, then pass it into console.log.apply(console, /*here*/);
var log = function () {
return console.log.apply(
console,
['['+new Date().toISOString().slice(11,-5)+']'].concat(
Array.prototype.slice.call(arguments)
)
);
};
log(['foo']); // [18:13:17] ["foo"]
It seems that arguments can be Array.prototype.unshifted too, but I don't know if modifying it like this is a good idea/will have other side effects
var log = function () {
Array.prototype.unshift.call(
arguments,
'['+new Date().toISOString().slice(11,-5)+']'
);
return console.log.apply(console, arguments);
};
log(['foo']); // [18:13:39] ["foo"]
Update as of for Chrome 98:
Settings -> Preferences -> Console -> Show timestamps
From Chrome 68:
"Show timestamps" moved to settings
The Show timestamps checkbox previously in Console Settings Console Settings has moved to Settings.
+new Date and Date.now() are alternate ways to get timestamps
If you are using Google Chrome browser, you can use chrome console api:
console.time: call it at the point in your code where you want to start the timer
console.timeEnd: call it to stop the timer
The elapsed time between these two calls is displayed in the console.
For detail info, please see the doc link: https://developers.google.com/chrome-developer-tools/docs/console
ES6 solution:
const timestamp = () => `[${new Date().toUTCString()}]`
const log = (...args) => console.log(timestamp(), ...args)
where timestamp() returns actually formatted timestamp and log add a timestamp and propagates all own arguments to console.log
Try this also:
this.log = console.log.bind( console, '[' + new Date().toUTCString() + ']' );
This function puts timestamp, filename and line number as same of built-in console.log.
Chrome Version 89.0.4389.90 (19.03.2021)
Press F12.
Find and press gear wheel icon.
Check Show timestamps.
If you want to preserve line number information (each message pointing to its .log() call, not all pointing to our wrapper), you have to use .bind(). You can prepend an extra timestamp argument via console.log.bind(console, <timestamp>) but the problem is you need to re-run this every time to get a function bound with a fresh timestamp.
An awkward way to do that is a function that returns a bound function:
function logf() {
// console.log is native function, has no .bind in some browsers.
// TODO: fallback to wrapping if .bind doesn't exist...
return Function.prototype.bind.call(console.log, console, yourTimeFormat());
}
which then has to be used with a double call:
logf()(object, "message...")
BUT we can make the first call implicit by installing a property with getter function:
var origLog = console.log;
// TODO: fallbacks if no `defineProperty`...
Object.defineProperty(console, "log", {
get: function () {
return Function.prototype.bind.call(origLog, console, yourTimeFormat());
}
});
Now you just call console.log(...) and automagically it prepends a timestamp!
> console.log(12)
71.919s 12 VM232:2
undefined
> console.log(12)
72.866s 12 VM233:2
undefined
You can even achieve this magical behavior with a simple log() instead of console.log() by doing Object.defineProperty(window, "log", ...).
See https://github.com/pimterry/loglevel for a well-done safe console wrapper using .bind(), with compatibility fallbacks.
See https://github.com/eligrey/Xccessors for compatibility fallbacks from defineProperty() to legacy __defineGetter__ API.
If neither property API works, you should fallback to a wrapper function that gets a fresh timestamp every time. (In this case you lose line number info, but timestamps will still show.)
Boilerplate: Time formatting the way I like it:
var timestampMs = ((window.performance && window.performance.now) ?
function() { return window.performance.now(); } :
function() { return new Date().getTime(); });
function formatDuration(ms) { return (ms / 1000).toFixed(3) + "s"; }
var t0 = timestampMs();
function yourTimeFormat() { return formatDuration(timestampMs() - t0); }
I have this in most Node.JS apps. It also works in the browser.
function log() {
const now = new Date();
const currentDate = `[${now.toISOString()}]: `;
const args = Array.from(arguments);
args.unshift(currentDate);
console.log.apply(console, args);
}
extended the very nice solution "with format string" from JSmyth to also support
all the other console.log variations (log,debug,info,warn,error)
including timestamp string flexibility param (e.g. 09:05:11.518 vs. 2018-06-13T09:05:11.518Z)
including fallback in case console or its functions do not exist in browsers
.
var Utl = {
consoleFallback : function() {
if (console == undefined) {
console = {
log : function() {},
debug : function() {},
info : function() {},
warn : function() {},
error : function() {}
};
}
if (console.debug == undefined) { // IE workaround
console.debug = function() {
console.info( 'DEBUG: ', arguments );
}
}
},
/** based on timestamp logging: from: https://stackoverflow.com/a/13278323/1915920 */
consoleWithTimestamps : function( getDateFunc = function(){ return new Date().toJSON() } ) {
console.logCopy = console.log.bind(console)
console.log = function() {
var timestamp = getDateFunc()
if (arguments.length) {
var args = Array.prototype.slice.call(arguments, 0)
if (typeof arguments[0] === "string") {
args[0] = "%o: " + arguments[0]
args.splice(1, 0, timestamp)
this.logCopy.apply(this, args)
} else this.logCopy(timestamp, args)
}
}
console.debugCopy = console.debug.bind(console)
console.debug = function() {
var timestamp = getDateFunc()
if (arguments.length) {
var args = Array.prototype.slice.call(arguments, 0)
if (typeof arguments[0] === "string") {
args[0] = "%o: " + arguments[0]
args.splice(1, 0, timestamp)
this.debugCopy.apply(this, args)
} else this.debugCopy(timestamp, args)
}
}
console.infoCopy = console.info.bind(console)
console.info = function() {
var timestamp = getDateFunc()
if (arguments.length) {
var args = Array.prototype.slice.call(arguments, 0)
if (typeof arguments[0] === "string") {
args[0] = "%o: " + arguments[0]
args.splice(1, 0, timestamp)
this.infoCopy.apply(this, args)
} else this.infoCopy(timestamp, args)
}
}
console.warnCopy = console.warn.bind(console)
console.warn = function() {
var timestamp = getDateFunc()
if (arguments.length) {
var args = Array.prototype.slice.call(arguments, 0)
if (typeof arguments[0] === "string") {
args[0] = "%o: " + arguments[0]
args.splice(1, 0, timestamp)
this.warnCopy.apply(this, args)
} else this.warnCopy(timestamp, args)
}
}
console.errorCopy = console.error.bind(console)
console.error = function() {
var timestamp = getDateFunc()
if (arguments.length) {
var args = Array.prototype.slice.call(arguments, 0)
if (typeof arguments[0] === "string") {
args[0] = "%o: " + arguments[0]
args.splice(1, 0, timestamp)
this.errorCopy.apply(this, args)
} else this.errorCopy(timestamp, args)
}
}
}
} // Utl
Utl.consoleFallback()
//Utl.consoleWithTimestamps() // defaults to e.g. '2018-06-13T09:05:11.518Z'
Utl.consoleWithTimestamps( function(){ return new Date().toJSON().replace( /^.+T(.+)Z.*$/, '$1' ) } ) // e.g. '09:05:11.518'
This adds a "log" function to the local scope (using this) using as many arguments as you want:
this.log = function() {
var args = [];
args.push('[' + new Date().toUTCString() + '] ');
//now add all the other arguments that were passed in:
for (var _i = 0, _len = arguments.length; _i < _len; _i++) {
arg = arguments[_i];
args.push(arg);
}
//pass it all into the "real" log function
window.console.log.apply(window.console, args);
}
So you can use it:
this.log({test: 'log'}, 'monkey', 42);
Outputs something like this:
[Mon, 11 Mar 2013 16:47:49 GMT] Object {test: "log"} monkey 42
A refinement on the answer by JSmyth:
console.logCopy = console.log.bind(console);
console.log = function()
{
if (arguments.length)
{
var timestamp = new Date().toJSON(); // The easiest way I found to get milliseconds in the timestamp
var args = arguments;
args[0] = timestamp + ' > ' + arguments[0];
this.logCopy.apply(this, args);
}
};
This:
shows timestamps with milliseconds
assumes a format string as first parameter to .log

Can I extend the console object (for rerouting the logging) in javascript?

Is it possible to extend the console object?
I tried something like:
Console.prototype.log = function(msg){
Console.prototype.log.call(msg);
alert(msg);
}
But this didn't work.
I want to add additional logging to the console object via a framework like log4javascript and still use the standard console object (in cases where log4javascript is not available) in my code.
Thanks in advance!
Try following:
(function() {
var exLog = console.log;
console.log = function(msg) {
exLog.apply(this, arguments);
alert(msg);
}
})()
You Can Also add log Time in This Way :
added Momentjs or use New Date() instead of moment.
var oldConsole = console.log;
console.log = function(){
var timestamp = "[" + moment().format("YYYY-MM-DD HH:mm:ss:SSS") + "] ";
Array.prototype.unshift.call(arguments, timestamp);
oldConsole.apply(this, arguments);
};
It's really the same solution some others have given, but I believe this is the most elegant and least hacky way to accomplish this. The spread syntax (...args) makes sure not a single argument is lost.
var _console={...console}
console.log = function(...args) {
var msg = {...args}[0];
//YOUR_CODE
_console.log(...args);
}
For ECMAScript 2015 and later
You can use the newer Proxy feature from the ECMAScript 2015 standard to "hijack" the global console.log.
Source-Code
'use strict';
class Mocker {
static mockConsoleLog() {
Mocker.oldGlobalConsole = window.console;
window.console = new Proxy(window.console, {
get(target, property) {
if (property === 'log') {
return function(...parameters) {
Mocker.consoleLogReturnValue = parameters.join(' ');
}
}
return target[property];
}
});
}
static unmockConsoleLog() {
window.console = Mocker.oldGlobalConsole;
}
}
Mocker.mockConsoleLog();
console.log('hello'); // nothing happens here
Mocker.unmockConsoleLog();
if (Mocker.consoleLogReturnValue === 'hello') {
console.log('Hello world!'); // Hello world!
alert(Mocker.consoleLogReturnValue);
// anything you want to do with the console log return value here...
}
Online Demo
Repl.it.
Node.js users...
... I do not forget you. You can take this source-code and replace window.console by gloabl.console to properly reference the console object (and of course, get rid of the alert call). In fact, I wrote this code initially and tested it on Node.js.
// console aliases and verbose logger - console doesnt prototype
var c = console;
c.l = c.log,
c.e = c.error,
c.v = c.verbose = function() {
if (!myclass || !myclass.verbose) // verbose switch
return;
var args = Array.prototype.slice.call(arguments); // toArray
args.unshift('Verbose:');
c.l.apply(this, args); // log
};
// you can then do
var myclass = new myClass();
myclass.prototype.verbose = false;
// generally these calls would be inside your class
c.v('1 This will NOT log as verbose == false');
c.l('2 This will log');
myclass.verbose = true;
c.v('3 This will log');
I noted that the above use of Array.prototype.unshift.call by nitesh is a better way to add the 'Verbose:' tag.
You can override the default behavior of the console.log function using the below approach, the below example demonstrates to log the line number using the overridden function.
let line = 0;
const log = console.log;
console.log = (...data) => log(`${++line} ===>`, ...data)
console.log(11, 1, 2)
console.log(11, 1, 'some')

Categories