簡體   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