1. 程式人生 > >簡單實用的js除錯logger元件

簡單實用的js除錯logger元件

<span style="color:#CC0000;">這個元件的實現參考了log4net元件的記錄方式,我們利用這個js的logger元件,就可以用log的輸出的方式來進行你的除錯工作了</span>

<pre name="code" class="java">/* 
js除錯元件 
*/
(function () { 
    var logger = function (level, object, viewType) { 
        this.level = level; 
        this.object = object; 
        this.viewType = viewType; 
    } 
    logger.LEVEL_DEBUG = 0; 
    logger.LEVEL_INFO = 1; 
    logger.LEVEL_WARN = 2; 
    logger.LEVEL_ERROR = 3; 
    logger.LEVEL_FATAL = 4; 
    logger.VIEW_TYPE_ALERT = 0; 
    logger.VIEW_TYPE_APPEND = 1; 
    logger.prototype = { 
        setLevel: function (level) { 
            this.level = level; 
        }, 
        setObject: function (o) { 
            if (typeof o == 'string') { 
                this.object = document.getElementById(o); 
            } else { 
                this.object = o; 
            } 
        }, 
        setViewType: function (type) { 
            this.viewType = type; 
        }, 
        log: function (s) { 
            this.message(100, s); 
        }, 
        debug: function (s) { 
            this.message(logger.LEVEL_DEBUG, s); 
        }, 
        info: function (s) { 
            this.message(logger.LEVEL_INFO, s); 
        }, 
        warn: function (s) { 
            this.message(logger.LEVEL_WARN, s); 
        }, 
        error: function (s) { 
            this.message(logger.LEVEL_ERROR, s); 
        }, 
        fatal: function (s) { 
            this.message(logger.LEVEL_FATAL, s); 
        }, 
        message: function (level, s) { 
            if (level >= this.level) { 
                if (this.object != null) { 
                    this.object.innerHTML = s; 
                } else if (this.viewType == logger.VIEW_TYPE_ALERT) { 
                    alert(s); 
                } else { 
                    document.body.appendChild(document.createTextNode(s)); 
                    document.body.appendChild(document.createElement("br")); 
                } 
            } 
        } 
    }; 
    if (typeof window.Logger == 'undefined' || window.Logger == null) 
        window.Logger = new logger(logger.LEVEL_DEBUG, null, logger.VIEW_TYPE_APPEND); 
})();

這個js元件往window物件註冊了Logger物件,我們可以用Logger.log/Logger.debug/Logger.info/Logger.warn/Logger.error/Logger.fatal來輸出不同的除錯資訊。

示例程式碼如下

Logger.debug(new Date()); Logger.debug(new Date().addHours(3));