console.log的正确包装器,具有正确的行号? [英] A proper wrapper for console.log with correct line number?

查看:471
本文介绍了console.log的正确包装器,具有正确的行号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在开发一个应用程序,并放置一个全局 isDebug 开关。我想包装 console.log 以方便使用。

I'm now developing an application, and place a global isDebug switch. I would like to wrap console.log for more convenient usage.

//isDebug controls the entire site.
var isDebug = true;

//debug.js
function debug(msg, level){
    var Global = this;
    if(!(Global.isDebug && Global.console && Global.console.log)){
        return;
    }
    level = level||'info';
    Global.console.log(level + ': '+ msg);
}

//main.js
debug('Here is a msg.');

然后我在Firefox控制台中得到这个结果。

Then I get this result in Firefox console.

info: Here is a msg.                       debug.js (line 8)

如果我想使用<$ c $的行号进行记录,该怎么办? c> debug()被调用,如 info:这是一个msg。 main.js(第2行)

What if I want to log with line number where debug() gets called, like info: Here is a msg. main.js (line 2)?

推荐答案

这是一个老问题,并提供了所有答案是过分hackey,有MAJOR跨浏览器问题,并没有提供任何超级有用的东西。此解决方案适用于每个浏览器,并准确报告所有控制台数据。不需要黑客和一行代码查看代码簿

This is an old question and All the answers provided are overly hackey, have MAJOR cross browser issues, and don't provide anything super useful. This solution works in every browser and reports all console data exactly as it should. No hacks required and one line of code Check out the codepen.

var debug = console.log.bind(window.console)

按如下所示创建开关:

isDebug = true // toggle this to turn on / off for global controll

if (isDebug) var debug = console.log.bind(window.console)
else var debug = function(){}

然后简单地调用如下:

debug('This is happening.')

您甚至可以通过类似开关接管console.log这个:

You can even take over the console.log with a switch like this:

if (!isDebug) console.log = function(){}

如果你想做一些有用的东西..你可以添加所有的控制台方法并将其包装在一个可重复使用的功能中,不仅可以提供全局功能控制,但类级别:

If you want to do something useful with that.. You can add all the console methods and wrap it up in a reusable function that gives not only global control, but class level as well:

var Debugger = function(gState, klass) {

  this.debug = {}

  if (gState && klass.isDebug) {
    for (var m in console)
      if (typeof console[m] == 'function')
        this.debug[m] = console[m].bind(window.console, klass.toString()+": ")
  }else{
    for (var m in console)
      if (typeof console[m] == 'function')
        this.debug[m] = function(){}
  }
  return this.debug
}

isDebug = true //global debug state

debug = Debugger(isDebug, this)

debug.log('Hello log!')
debug.trace('Hello trace!')

现在你可以把它添加到你的班级:

Now you can add it to your classes:

var MyClass = function() {
  this.isDebug = true //local state
  this.debug = Debugger(isDebug, this)
  this.debug.warn('It works in classses')
}

这篇关于console.log的正确包装器,具有正确的行号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆