Skip to content

Instantly share code, notes, and snippets.

@ClementNerma
Last active December 21, 2015 17:51
Show Gist options
  • Save ClementNerma/4a0d7558735fc137c02f to your computer and use it in GitHub Desktop.
Save ClementNerma/4a0d7558735fc137c02f to your computer and use it in GitHub Desktop.
A micro-library to debug your code without opening the inspector
'use strict';
var Console = function(parent) {
var DOM = document.createElement('div');
DOM.setAttribute('class', 'console');
DOM.setAttribute('style', 'border:1px solid gray;max-height:200px;overflow:auto;');
(parent || document.body).appendChild(DOM);
// Here are the logs
this.logs = {};
// You can change the displaying colors here
this.colors = {
error: 'red',
info: 'blue',
log: 'black',
warn: 'yellow'
}
function _append(cl, message, that) {
var msg = document.createElement('div');
msg.setAttribute('class', 'console-log console-' + cl);
msg.setAttribute('style', 'padding:5px;border-bottom:1px solid gray;color:' + (that.colors[cl] || 'black') + ';');
msg.innerHTML = message;
msg.innerHTML = (msg.textContent || msg.innerText || message).replace(/\r|\n|\r\n/g, '<br/>');
DOM.appendChild(msg);
if(!Array.isArray(that.logs[cl]))
that.logs[cl] = [];
that.logs[cl].push(message);
}
this.log = function(message) { _append('log' , message, this); };
this.info = function(message) { _append('info' , message, this); };
this.warn = function(message) { _append('warn' , message, this); };
this.error = function(message) { _append('error', message, this); };
};
@ClementNerma
Copy link
Author

A short example :

<script type="text/javascript">
    var con = new Console();
    con.log('I\'m walking in the street...');
    con.warn('A car !!');
    con.info('There is no car anymore');
    con.warn('A bus !!');
    con.info('There is no bus anymore');
    con.log('- Singing -');
    con.info('You have a new message !');
    con.log('Let\'s see my phone...');
    con.error('NO BATTERY :(');
    con.log('Oh no !');

    con.info('--- THE END ---');
</script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment