Saving Console Messages in JavaScript

Have you ever encountered a situation where it would be beneficial to save whatever is written to the console across browser sessions?  If you have, you know there are not many solutions.  I recently decided that localStorage would be a good candidate to implement a solution to this problem with.

logsaver.js

logsaver.js is a lightweight, simple log preservation script.  It utilizes the flexibility of JavaScript to replace the default console.log function with a new, customized one.  Along with writing messages to the original console.log, this custom console.log  also writes messages to the specified localStorage key.

  • To start saving console.log messages, call startSavingLog().
  • To stop saving console.log messages, call stopSavingLog().
  • To clear saved console.log messages, call clearSavedLog().
  • To completely remove the localStorage key used by logsaver, call removeSavedLog().

For more information on options and how to use them, checkout the readme.
While you can copy the source below, I strongly recommend grabbing the latest from github here: logsaver.js.

Notes:

  • It doesn’t handle objects well.  Results in [Object object] appearing in the localStorage key value.  This is because localStorage is limited to strings.
  • It is possible to exceed the maximum space allocated to you in localStorage.  For desktop browsers, Chrome and Firefox have a 10 MB limit, while Safari and IE both have a 5 MB limit.  These number differs for mobile browsers.  More details.  In this event, logsaver.js will stop trying to save the log and display additional error messages in the console.

v0.1.0 Source

/*
logsaver.js v0.1.0
https://github.com/chaddotson/logsaver/
(c) 2016 Chad Dotson
logsaver.js may be freely distributed under the GNUv3 license.
*/
(function(root) {
    'use strict';
    var _root = root;
    var _localStorageKeyForLog = "console.log.saved";
    var _includeTimestamp = false;
    var _originalLog;
    function _isEnabled() {
        return _originalLog !== undefined;
    }
    function _zeroPad(str) {
        str = str + ""; // force it to be a string.
        return ((str.length < 2) ? "0" + str : str);
    }
    function _formatDate() {
       return this.getFullYear() + "/" + _zeroPad(this.getMonth()) + "/" + _zeroPad(this.getDay()) + " - " + _zeroPad(this.getHours()) + ":" + _zeroPad(this.getMinutes()) + ":" + _zeroPad(this.getSeconds());
    }
    _root.clearSavedLog = function () {
        if(localStorage[_localStorageKeyForLog]) {
            localStorage[_localStorageKeyForLog] = "";
            return true;
        }
        return false;
    };
    _root.removeSavedLog = function () {
        if(localStorage[_localStorageKeyForLog] !== undefined) {
            localStorage.removeItem(_localStorageKeyForLog);
            return true;
        }
        return false;
    };
    _root.stopSavingLog = function () {
        if(!_isEnabled()) {
            console.log("Not currently saving console.log to localStorage.");
            return false;
        }
        console.log = _originalLog;
        _originalLog = undefined;
        console.log("No longer saving console.log to localStorage.");
        return true;
    };
    _root.startSavingLog = function (options) {
        options = options || {};
        if(_isEnabled()) {
            _originalLog.call(console, "Already saving console.log. localStorage Key:" + _localStorageKeyForLog);
            return false;
        }
        _localStorageKeyForLog = options.keyForLocalStorage || _localStorageKeyForLog;
        var timestampFormatter = options.timestampFormatter || _formatDate;
        _originalLog = console.log;
        console.log = function(){
            _originalLog.apply(console, arguments);
            var formattedTimestamp = timestampFormatter.apply(new Date());
            var message =  "\n "+ formattedTimestamp + " :: " + Array.prototype.join.call(arguments, ", ");
            try {
                if(!localStorage[_localStorageKeyForLog]) {
                    localStorage[_localStorageKeyForLog] = "";
                }
                localStorage[_localStorageKeyForLog] += message;
            } catch (e) {
                if (e == QUOTA_EXCEEDED_ERR) {
                    _originalLog.apply(console, arguments.splice(0, 0, "SAVE FAILED - LOCAL STORAGE QUOTA EXCEEDED"));
                } else {
                    _originalLog.apply(console, arguments.splice(0, 0, "SAVE FAILED"));
                }
            }
        }
        _originalLog.call(console, "Now saving console.log to localStorage Key:" + _localStorageKeyForLog);
        return true;
    };
})(this);

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply