[javascript] Javascript: console.log to html

I would like to write the console.log output to a div layer.

For example:

document.write(console.log(5+1)); //Incorrect, random example

Can someone give me a solution to my problem?

Thank you.

EDIT:

what i meant is, for example:

console.log("hi");

and it shows the output "hi" on the screen.

Note: An example: http://labs.codecademy.com/#:workspace

This question is related to javascript

The answer is


This post has helped me a lot, and after a few iterations, this is what we use.

The idea is to post log messages and errors to HTML, for example if you need to debug JS and don't have access to the console.

You do need to change 'console.log' with 'logThis', as it is not recommended to change native functionality.

What you'll get:

  • A plain and simple 'logThis' function that will display strings and objects along with current date and time for each line
  • A dedicated window on top of everything else. (show it only when needed)
  • Can be used inside '.catch' to see relevant errors from promises.
  • No change of default console.log behavior
  • Messages will appear in the console as well.

_x000D_
_x000D_
function logThis(message) {
  // if we pass an Error object, message.stack will have all the details, otherwise give us a string
  if (typeof message === 'object') {
    message = message.stack || objToString(message);
  }

  console.log(message);

  // create the message line with current time
  var today = new Date();
  var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
  var time = today.getHours() + ':' + today.getMinutes() + ':' + today.getSeconds();
  var dateTime = date + ' ' + time + ' ';

  //insert line
  document.getElementById('logger').insertAdjacentHTML('afterbegin', dateTime + message + '<br>');
}

function objToString(obj) {
  var str = 'Object: ';
  for (var p in obj) {
    if (obj.hasOwnProperty(p)) {
      str += p + '::' + obj[p] + ',\n';
    }
  }
  return str;
}

const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

logThis(object1)
logThis('And all the roads we have to walk are winding, And all the lights that lead us there are blinding')
_x000D_
#logWindow {
  overflow: auto;
  position: absolute;
  width: 90%;
  height: 90%;
  top: 5%;
  left: 5%;
  right: 5%;
  bottom: 5%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 20;
}
_x000D_
<div id="logWindow">
  <pre id="logger"></pre>
</div>
_x000D_
_x000D_
_x000D_

Thanks this answer too, JSON.stringify() didn't work for this.


Create an ouput

<div id="output"></div>

Write to it using JavaScript

var output = document.getElementById("output");
output.innerHTML = "hello world";

If you would like it to handle more complex output values, you can use JSON.stringify

var myObj = {foo: "bar"};
output.innerHTML = JSON.stringify(myObj);

Slight improvement on @arun-p-johny answer:

In html,

<pre id="log"></pre>

In js,

(function () {
    var old = console.log;
    var logger = document.getElementById('log');
    console.log = function () {
      for (var i = 0; i < arguments.length; i++) {
        if (typeof arguments[i] == 'object') {
            logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify(arguments[i], undefined, 2) : arguments[i]) + '<br />';
        } else {
            logger.innerHTML += arguments[i] + '<br />';
        }
      }
    }
})();

Start using:

console.log('How', true, new Date());

A little late to the party, but I took @Hristiyan Dodov's answer a bit further still.

All console methods are now rewired and in case of overflowing text, an optional autoscroll to bottom is included. Colors are now based on the logging method rather than the arguments.

_x000D_
_x000D_
rewireLoggingToElement(_x000D_
    () => document.getElementById("log"),_x000D_
    () => document.getElementById("log-container"), true);_x000D_
_x000D_
function rewireLoggingToElement(eleLocator, eleOverflowLocator, autoScroll) {_x000D_
    fixLoggingFunc('log');_x000D_
    fixLoggingFunc('debug');_x000D_
    fixLoggingFunc('warn');_x000D_
    fixLoggingFunc('error');_x000D_
    fixLoggingFunc('info');_x000D_
_x000D_
    function fixLoggingFunc(name) {_x000D_
        console['old' + name] = console[name];_x000D_
        console[name] = function(...arguments) {_x000D_
            const output = produceOutput(name, arguments);_x000D_
            const eleLog = eleLocator();_x000D_
_x000D_
            if (autoScroll) {_x000D_
                const eleContainerLog = eleOverflowLocator();_x000D_
                const isScrolledToBottom = eleContainerLog.scrollHeight - eleContainerLog.clientHeight <= eleContainerLog.scrollTop + 1;_x000D_
                eleLog.innerHTML += output + "<br>";_x000D_
                if (isScrolledToBottom) {_x000D_
                    eleContainerLog.scrollTop = eleContainerLog.scrollHeight - eleContainerLog.clientHeight;_x000D_
                }_x000D_
            } else {_x000D_
                eleLog.innerHTML += output + "<br>";_x000D_
            }_x000D_
_x000D_
            console['old' + name].apply(undefined, arguments);_x000D_
        };_x000D_
    }_x000D_
_x000D_
    function produceOutput(name, args) {_x000D_
        return args.reduce((output, arg) => {_x000D_
            return output +_x000D_
                "<span class=\"log-" + (typeof arg) + " log-" + name + "\">" +_x000D_
                    (typeof arg === "object" && (JSON || {}).stringify ? JSON.stringify(arg) : arg) +_x000D_
                "</span>&nbsp;";_x000D_
        }, '');_x000D_
    }_x000D_
}_x000D_
_x000D_
_x000D_
setInterval(() => {_x000D_
  const method = (['log', 'debug', 'warn', 'error', 'info'][Math.floor(Math.random() * 5)]);_x000D_
  console[method](method, 'logging something...');_x000D_
}, 200);
_x000D_
#log-container { overflow: auto; height: 150px; }_x000D_
_x000D_
.log-warn { color: orange }_x000D_
.log-error { color: red }_x000D_
.log-info { color: skyblue }_x000D_
.log-log { color: silver }_x000D_
_x000D_
.log-warn, .log-error { font-weight: bold; }
_x000D_
<div id="log-container">_x000D_
  <pre id="log"></pre>_x000D_
</div>
_x000D_
_x000D_
_x000D_


I come a bit late with a more advanced version of Arun P Johny's answer. His solution doesn't handle multiple console.log() arguments and doesn't give an access to the original function.

Here's my version:

_x000D_
_x000D_
(function (logger) {_x000D_
    console.old = console.log;_x000D_
    console.log = function () {_x000D_
        var output = "", arg, i;_x000D_
_x000D_
        for (i = 0; i < arguments.length; i++) {_x000D_
            arg = arguments[i];_x000D_
            output += "<span class=\"log-" + (typeof arg) + "\">";_x000D_
_x000D_
            if (_x000D_
                typeof arg === "object" &&_x000D_
                typeof JSON === "object" &&_x000D_
                typeof JSON.stringify === "function"_x000D_
            ) {_x000D_
                output += JSON.stringify(arg);   _x000D_
            } else {_x000D_
                output += arg;   _x000D_
            }_x000D_
_x000D_
            output += "</span>&nbsp;";_x000D_
        }_x000D_
_x000D_
        logger.innerHTML += output + "<br>";_x000D_
        console.old.apply(undefined, arguments);_x000D_
    };_x000D_
})(document.getElementById("logger"));_x000D_
_x000D_
// Testing_x000D_
console.log("Hi!", {a:3, b:6}, 42, true);_x000D_
console.log("Multiple", "arguments", "here");_x000D_
console.log(null, undefined);_x000D_
console.old("Eyy, that's the old and boring one.");
_x000D_
body {background: #333;}_x000D_
.log-boolean,_x000D_
.log-undefined {color: magenta;}_x000D_
.log-object,_x000D_
.log-string {color: orange;}_x000D_
.log-number {color: cyan;}
_x000D_
<pre id="logger"></pre>
_x000D_
_x000D_
_x000D_

I took it a tiny bit further and added a class to each log so you can color it. It outputs all arguments as seen in the Chrome console. You also have access to the old log via console.old().

Here's a minified version of the script above to paste inline, just for you:

<script>
    !function(o){console.old=console.log,console.log=function(){var n,e,t="";for(e=0;e<arguments.length;e++)t+='<span class="log-'+typeof(n=arguments[e])+'">',"object"==typeof n&&"object"==typeof JSON&&"function"==typeof JSON.stringify?t+=JSON.stringify(n):t+=n,t+="</span>&nbsp;";o.innerHTML+=t+"<br>",console.old.apply(void 0,arguments)}}
    (document.body);
</script>

Replace document.body in the parentheses with whatever element you wish to log into.