2012-06-25 45 views
5

google-closure库还包含大多数开发人员应该熟悉的logging system。这很好。不幸的是,从某些浏览器/插件提供的console.log获得的输出不如表达。是否有可能为`goog.debug.Logger`获得更好的输出(如`console.log`)?

例如,如果您在Chrome中编写console.log(window),则控制台将显示一个可交互检查的对象。当使用google-closure记录器时,它不会那样做。我假设它将在内部简单地将对象的字符串表示形式传递给console.log。所以你失去了很多便利。因此,我仍然继续使用console.log。但是,如果运气不好,你忘了从产品代码中删除它,那么你的代码将在没有console.log(f.ex .: IE)的浏览器中被破坏。

或者,也可以防止这种情况,通过检查是否存在第一,例如:

window.console && window.console.log && console.log(...) 

或:

if (DEBUG) { 
    console.log(...) 
} 

但是这两种解决方案是远远不够完善。并且,假设库具有日志框架,那么能够使用它是很好的。现在,我发现console.log有时更有用。

所以我的问题(在TL/DR):我可以让谷歌闭合用户console.log(x)当我使用的x一个字符串表示写myLogger.info(x)代替它?

回答

5

您也可以使用goog.debug.FancyWindow有一个单独的窗口来显示日志记录。有关更多信息,请参阅google关闭演示页面:https://github.com/google/closure-library/blob/master/closure/goog/demos/debug.html并查看源代码。

如果你只是使用控制台日志的另一个优点是,该框架将自动在前面加上模块名称和时间...只需添加如下因素线使用控制台日志记录:

goog.require('goog.debug.Console'); 

if (goog.DEBUG) { 
    debugConsole = new goog.debug.Console; 
    debugConsole.setCapturing(true); 
} 

这也会阻止在生产代码中显示控制台日志记录。

问候,

刘若英

+0

我一直在寻找的关键位是'goog.debug.expose'。当我第一次查看日志框架的文档时,我错过了这一点!尽管不如交互式的console.log转储方便,但在大多数情况下这样做会很好。那谢谢啦! – exhuma

+0

恐怕这个答案中的代码会导致错误。由于您在导入后立即使用'goog.debug.Console',因此'goog.require ...' – hguser

2

关闭谷歌能提供的信息,按您的需要。具有功能,没有对象的功能。请参阅下面的代码片段。

goog.require('goog.debug'); 
goog.require('goog.debug.Logger'); 

var theLogger = goog.debug.Logger.getLogger('demo'); 
theLogger.info('Logging examples'); 

// Create a simple object. 
var someone = { 
    'name': 'peder', 
     'age': 33, 
     'gender': 'm', 
     'kids': ['hari', 'sam', 'sneha'] 
}; 

// Show the object, note that it will output '[object Object]'. 
theLogger.info(someone); 

// Use expose to walk through the object and show all data. 
theLogger.info('Person: ' + goog.debug.expose(someone)); 


// Does not show the functions by default. 
theLogger.info('expose (no functions): ' + goog.debug.expose(yourObject)); 


// Shows the functions as well. 
theLogger.info('expose (w/functions): ' + goog.debug.expose(yourObject, true)); 

// Show deepExpose, which walks recursively through data. 
theLogger.info('deepExpose (no functions): ' + goog.debug.deepExpose(yourObject)); 

theLogger.info('deepExpose (w/functions): ' + goog.debug.deepExpose(yourObject, true)); 
+0

'goog.debug.expose'很有用。仍然不如从'console.log'得到的输出有用。 – exhuma

相关问题