2016-01-21 2 views
2

Я ищу лучший метод ведения журнала/отладки для моего проекта. Поэтому я придумал использовать пользовательские директивы, такие как «use strict».custom 'use strict' like директивы

Можно ли написать что-то вроде этого

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

И если хуг имеет директиву LOGLEVEL> = информация logging.debug не будет регистрировать сообщение.

Возможно ли это?

+0

Это может быть возможно с некоторыми запутанные писак, но * много * простое решение было бы просто 'каротаж. level = 'info'; '. – JJJ

+0

Это невозможно, если вы не пишете пользовательский препроцессор, который анализирует файл и заменяет собой записи ведения журнала для вас. –

+0

Я думаю, что вы ищете «декораторов». –

ответ

2

Нет, вы не можете создавать такие директивы без какого-либо реального хакера, преобразовывая текущую функцию в строку и проверяя ее. это не стоило бы времени проверять. Тем не менее, вы можете использовать функциональные декораторы для выполнения одной и той же функции, это немного сложно сделать вокруг, но очень мощно, как только вы это сделаете.

Следует упомянуть, что 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>

+0

Стоит упомянуть, что декораторы доступны в Babel с соответствующими пресетами. –

-2
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