Customized logger in javascript

最近剛好工作上有需要,所以就來寫一個。

原本預設 javascript 有 console.log() 可以用,但是如果要將 log 資料分等級的話就得自己處理。

var LogLevel = {
        Debug: { value: 1, name: "Debug", code: "debug" },
        Info: { value: 2, name: "Info", code: "info" },
        Warning: { value: 3, name: "Warn", code: "warn"},
        Error: { value: 4, name: "Err", code: "error"},
        None: { value:99, name: "None", code: "none"}
    };

var logger = function()
{
    var pub = {};

    var _currentLogLevel = LogLevel.Info;
    pub.LogLevel = _currentLogLevel;

    pub.info = function(msg){ if (_currentLogLevel.value <= LogLevel.Info.value) { console.log(msg);} };
    pub.warning = function(msg){ if (_currentLogLevel.value <= LogLevel.Warning.value) { console.log(msg);} };
    pub.error = function(msg){ if (_currentLogLevel.value <= LogLevel.Error.value) { console.log(msg);} };

    return pub;
}();

console.log(logger.LogLevel);
logger.info("hehe");
logger.warning("warn hehe");
logger.error("error hehe");
logger.LogLevel = LogLevel.Error;
logger.info("haha");
logger.warning("warn haha");
logger.error("error haha");
console.log(logger.LogLevel);