简体   繁体   English

如何使console.log可配置

[英]How to make console.log configurable

In my web-app( heavy on client side, light on server side), while in development, I need to do a lot of debugging, console.log is very helpful, but ideally in production, there must not be any debug message shown, so I am planning to add the below code: 在我的web-app中(在客户端很重,在服务器端轻松),在开发中,我需要做很多调试, console.log非常有用,但理想情况下在生产中,一定不能显示任何调试消息,所以我打算添加以下代码:

window.production = false;  // set to true when in production mode.

if(window.production){    
    window.log = function(){};
}else{
    window.log = function(){
        console.log.apply(console, arguments);
    };
}    
//then replace all console.log(a, b, c, ...) into window.log(a, b, c, ...) in my code.

is this a good way to make debugging configurable, or must I just make a grunt that removes all console.log lines for production? 这是一个使调试可配置的好方法,或者我是否只需要删除所有用于生产的console.log行的grunt

So if your only end goal is to not show debug messages in production you have a huge amount of options to choose from! 因此,如果你唯一的目标是不在生产中显示调试消息,那么你有大量的选择可供选择! You should also decide if the following are important to you: 您还应该决定以下内容对您是否重要:

  1. Being able to perform other work outside of your log statement that also should not run in production. 能够在日志语句之外执行其他工作,这些工作也不应该在生产中运行。
  2. Minimizing file size in production and not shipping logging code. 最小化生产中的文件大小而不发送日志记录代码。
  3. Multiple log levels, or different logging groups. 多个日志级别或不同的日志记录组。
  4. The ability to turn these logging levels or groups on/off in production. 能够在生产中打开/关闭这些日志记录级别或组。
  5. Minimizing the amount that you have to type for each log statement. 最小化为每个日志语句键入的数量。

At a very basic level simply calling 在一个非常基本的层面上简单地呼叫

if (window.console && window.console.log)
{
    window.log = console.log.bind(console); // function devnull() { };
}
else
{
    window.log = function() { };
}

log('This is a log!');

will be enough to allow you to turn logging on/off. 足以让你打开/关闭登录。 This would fulfill goal (5) in the list above and works quite well. 这将满足上面列表中的目标(5)并且运行良好。

An alternate solution which works well with minifiers like uglify which can remove dead code would be to surround your logging statements with something like (you may not want to pollute the global namespace however): 一个替代解决方案适用于像uglify这样可以删除死代码的缩小器,可以用你喜欢的东西包围你的日志记录语句(你可能不想污染全局命名空间):

window.LogLevels =
{
    Off:        0x00000000,
    Error:      0x00000001,
    Warning:    0x00000002,
    Timing:     0x00000004,
    Data:       0x00000008,
    Status:     0x00000010,
    ...
    Verbose:    0x04000000,
};

window.LogLevel = LogLevels.Error | LogLevels.Warning;

window.ShouldLog = function(mask)
{
    return ((window.LogLevel & mask) === mask);
};

if (ShouldLog(LogLEvels.Error)) { log('This is an error!'); }

This would satisfy condition (1), (3), and (4) and sets you up to solve (2) as well at the cost of (5). 这将满足条件(1),(3)和(4),并以(5)为代价设置解决(2)。

Coupled with a pre-defined DEBUG constant (or similar), in your build step you can replace the log statements with a regex: 结合预定义的DEBUG常量(或类似),在构建步骤中,您可以使用正则表达式替换日志语句:

productionCode = debugCode.replace(/ShouldLog\(((?!LogLevels\.Error|LogLevels\.Warning)[^)]*)\)/g, 'DEBUG');

This would completely remove non-error and non-warning level logging in your code and satisfy (2). 这将完全删除代码中的非错误和非警告级别日志记录并满足(2)。 You don't really want people peeking at your logs right.. plus better perf! 你真的不希望有人偷看你的日志..加上更好的性能! :) :)

Bonus If you want to get extra funky, you can use the following (at least in Chrome) to get a stack trace for each logging statement in your console. 奖励如果您想获得额外的时髦,可以使用以下内容(至少在Chrome中)为控制台中的每个日志记录语句获取堆栈跟踪。 No more 'why did this log get hit'! 没有更多'为什么这个日志被击中'!

window.log = function ()
{
    console.groupCollapsed.apply(console, arguments);
    var stack = new Error().stack.split('\n');
    for(var i = 2; i < stack.length; i ++)
    {
        // Trim and remove 'at ';
        console.log('%c' + stack[i].trim().substring(3), 'padding-left: 10px; color: #777');
    }
    console.groupEnd();
};

If you are using build tools like Gulp.js or Grunt.js , then there are modules to do that : 如果您正在使用像Gulp.jsGrunt.js这样的构建工具,那么有一些模块可以做到这一点:

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

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