Following instructions on the link in my previous comment, I have created a JSFiddle - Override Console methods.
I still don't know if this is the best way, but this seems to work.
Edit
After discussion, I understood, problem was not just about catching all console messages but to also capture any unhandled errors. In my understanding only way to achieve is to add a Global Exception Handler
window.onerror = function(error){
// do your stuff
}
Following is the Updated JSFiddle. I also have updated the code snippet to show the same.
Code
var error = window.console.error,
log = console.log,
info = console.info,
warn = console.warn;
var lastLog = "",
lastError="",
lastInfo="",
lastWarn="";
function overrideConsole(){
console.error = function () {
lastError = arguments;
//alert(lastError);
print(lastError, "error")
error.apply(console, arguments);
};
console.log = function () {
lastLog = arguments;
print(lastLog, "log");
log.apply(console, arguments);
};
console.info = function () {
lastInfo = arguments;
print(lastInfo, "info");
info.apply(console, arguments);
};
console.warn = function () {
lastWarn = arguments;
print(lastWarn, "warn");
warn.apply(console, arguments);
};
}
function registerEvents(){
$("#btnError").on("click", function(){
console.error("new error");
});
$("#btnLog").on("click", function(){
console.log("new log");
});
$("#btnInfo").on("click", function(){
console.info("new info");
});
$("#btnWarn").on("click", function(){
console.warn("new warn");
});
$("#btnException").on("click", function(){
throw new Error();
});
}
function registerGlobalHandler(){
window.onerror = function(error) {
console.error(error);
};
}
function print(str, type){
var msgClass= "";
switch(type){
case "log": msgClass=" log"; break;
case "error": msgClass=" error"; break;
case "info": msgClass=" info"; break;
case "warn": msgClass=" warn"; break;
}
var div = "<div class='cell'>"+
"<label class='"+msgClass+"'>"+ str[0]+"</label>" +
"</div>"
$(".content").html( div + $(".content").html());
}
(function init(){
registerEvents();
registerGlobalHandler();
overrideConsole();
// Undefined function call
test();
})();
.cell{
width:90%;
position:relative;
padding:5px;
background: #eee;
}
.info{
color:blue;
}
.error{
color:red;
}
.warn{
color:green;
}
.log{
color:black;
}
.content{
width:90%;
height:300%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="btnError">Error</button>
<button id="btnLog">Log</button>
<button id="btnInfo">Info</button>
<button id="btnWarn">Warn</button>
<button id="btnException">Exception</button>
<div class="content"></div>