繁体   English   中英

自定义“使用严格”之类的指令

[英]custom 'use strict' like directives

我正在为我的项目寻找更好的日志记录/调试方法。 因此,我想到了使用自定义指令(例如“严格使用”)的想法。

是否可以写这样的东西

function xyz () {
   'loglevel: info';
   /// Some other code
   logging.debug("foobar");
}

而且,如果xyz具有指令loglevel> = info,则logging.debug将不会记录消息。

这可能吗?

不,如果没有将当前函数转换为字符串并检查指令的信息,您将无法创建这样的指令。 没时间检查。 但是,您可以使用功能性装饰器来执行相同的功能,这有点棘手,但是一旦完成,它就会非常强大。

我应该提到es7将具有更易于实现的装饰器。 它们仍然以相同的方式创建。 它们是一个函数,它代替原始函数返回一个函数。 但是他们有糖。

对不起,我停不下来,所以走了一点。 但现在这是一个非常完整的示例。

@logLevel('warn')
function xyz(){
  // do some stuff
}

要么

@logLevelInfo
function abc(){
  // do some stuff
}

 // if this is false the logging will not occur var __debug__ = true; var __debug_levels__ = ['error', 'warn']; // decorator to create a log level function. this is a function // that takes the log type, that returns a function that takes the // function you want to decorate with the logging functionality // that returns the decorated function that you call as xyz( ...arguments ). function logLevel( type ) { return function logger(fn) { return function() { // save time if __debug__ is false if( __debug__ ){ // run the decorated function and get the result // may as well wrap it in a try catch in case there are any errors try { var result = fn.apply(this, arguments); } catch( e ){ console.error( e ); } if( __debug_levels__.indexOf( type ) > -1 ){ // log the result to the console or whatever functionality you require console[ type || 'log' ](result); } // return the result so you can do something with the result return result; } return fn.apply(this, arguments); } } } // this will return the first function that takes the function to decorate var logLevelInfo = logLevel('warn'); var logLevelDebug = logLevel('error'); // here we are using the decorators to wrap the original function var xyz = logLevelInfo(function xyz( arg ) { return arg + 'bar'; }); // same here but we are using the other decorator var abc = logLevelDebug(function abc( arg ){ return arg + 'baz'; }); // these functions have been decorated to perform the logging // functionality on the returned result xyz('foo'); //=> 'foobar' abc('foo'); //=> 'foobaz' 
 <script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script> 

function Log(level)
{
    var levels = { 'debug': 10, 'info': 20};

    function write(lvl)
    {
        var handle = function(msg)
        {
            if (levels[lvl] <= levels[level]) 
                console.log(lvl + ': ' + msg);
        };

        return handle;
    }

    for (var i in levels)
    {
        this[i] = write(i);
    }
}

var log1 = new Log('info');
log1.info('hello'); // will result with an output
log1.debug('hello'); // still has an output output

var log2 = new Log('debug');
log2.info('hello'); // no output here

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM