Reputation: 7563
I have this code:
console.log('before');
console.groupCollapsed('main');
console.log('test1')
console.groupEnd();
console.groupCollapsed('main');
console.log('test2')
console.groupEnd();
console.groupCollapsed('main');
console.log('test2')
console.groupEnd();
console.log('after');
It adds 3 lines to browser logs.
The problem is logs are splitted into 3 different groups.
Is it possible to append logs to previous group if previous log message and the current one have same group names (main
)?
So now output is:
before
> main
test1
> main
test2
> main
test3
after
and I want this output:
before
> main
test1
test2
test3
after
Update: Code is async. So I should close the groups after logging to prevent logging from outside the groups to groups.
Upvotes: 5
Views: 3720
Reputation: 11718
How about a custom logger class
function Logger(){
var logs = [];
var gname = "default";
function group(name){
gname = name
}
function log(){
!!logs[gname] || (logs[gname] = []);
logs[gname].push(Array.prototype.slice.call(arguments, 0));
}
function flush(){
console.log(logs) // loop for groups or just output array
logs=[]; // clear values
}
return {group:group,flush:flush,log:log}
}
Usage
var l = new Logger()
l.group('main1');
l.log('foo','bar','foobar')
l.log('foo-bar')
l.group('main2');
l.log('foo')
l.log('bar')
l.group('main1');
l.log('foo2bar')
l.log('bar2foo')
l.group('main3');
l.log('foo')
l.log('bar')
l.group('main1');
l.log('foo3')
l.log('bar3')
l.flush()
Upvotes: 4
Reputation: 664548
You only can do that by not closing the group. You could use something like this:
var curGroup;
console.logInGroup = function(group, log) {
if (curGroup != group) {
console.groupEnd();
console.groupCollapsed(curGroup = group);
}
console.log.apply(console, [].slice.call(arguments, 1));
};
console.log('before');
console.logInGroup('main', 'test1');
console.logInGroup('main', 'test2');
console.logInGroup('main', 'test2');
console.groupEnd();
console.log('after');
Upvotes: 1
Reputation: 7470
You don't have to reopen a new group unless you really want to create a new group. So once you open a group, whatever you log will be attached to that group until you close it.
So with your example it would be
console.log('before');
console.groupCollapsed('main');
console.log('test1');
console.log('test2');
console.log('test2');
console.groupEnd();
console.log('after');
It shouldn't bother you but it takes a bit of a time for the browser to log these in groups. Just an additional note.
Upvotes: 2