views:

88

answers:

2

I'd like to find a better way to output console messages to an HTML page. This method seems to be pretty slow.

<html>
<title>Logging test</title>
<head>
<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
<!--

function log(s) {
    if(!log.start) {
     var date = new Date();
     log.count = 0;
     _log("0", "log() started at " + date);
     log.start = date.valueOf();
    }
    _log(new Date().valueOf() - log.start, s);
}

function _log(header, s) {
    var logMessages = document.getElementById("logMessages");
    if(!logMessages) {
     alert(logMessages);
     return;
    }
    var message = document.createElement("div");
    message.className = "logMessage";
    var content = "";
    content += "<span class=\"time\">" + header + "</span>";
    content += "<span class=\"line\">" + (log.count++) + "</span>";
    content += "<span class=\"level\">" + "" + "</span>";
    content += "<span class=\"msg\">" + s.replace(/ /g, "&nbsp;").replace(/\n/g, "<BR />") + "</span>";
    message.innerHTML = content;
    logMessages.appendChild(message);
    setTimeout(function(){message.scrollIntoView(true)},1);
}

function main(e) {
    if(window.confirm("Would you like to display logging?")) {
     for(var i=0;i<5000;i++) {
      log("Hello World " + i);
     }
    }
}
//-->
</SCRIPT>

<style>
.logMessage {
    border-bottom: 1px black solid;
    font-size: 8pt;
    font-family: Lucida Console;
}

.logMessage .line, .logMessage .time {
    width: 30px;
}

.logMessage .level {
    display: none;
}

.logMessage .msg {
}

#logMessages {
    overflow: auto;
}
</style>

</head>
<body onload="main()">
<div id="logMessages"></div>
</body>

</html>
+1  A: 

What's the use case here? For debugging, Firebug's console.log is all I can ever imagine needing. For your specific case, if you really want it to go to on the page and find your current solution to be too slow, I would definitely replace all the string concatenations with something a little more efficient (pushing strings into an array and joining them at the end, or a StringBuffer that abstracts it out), as string manipulation in Javascript is infamously bad in some browsers (I'm looking at you, Redmond!)

Paolo Bergantino
Out of curiosity I modified his code to use the array method. 10x faster! (original code took 11 seconds in Chrome. array method took slightly less than 2 seconds).
Herms
Yup. Makes a world of difference.
Paolo Bergantino
+2  A: 

Firebug is nice is you're using Firefox to test your work (assuming you want to log messages for debugging purposes). If you're testing other browsers, you can also use Firebug Lite which mimics the functionality of Firebug in other browsers. That way you don't have to re-invent the wheel.

Justin Niessner