使用正确的行号为console.log正确包装吗?


132

我现在正在开发应用程序,并进行全局isDebug切换。我想包装起来console.log以方便使用。

//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控制台中得到此结果。

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

如果我想使用debug()被呼叫的行号登录该info: Here is a msg. main.js (line 2)怎么办?


您可以使用console.log信息,console.warn警告和console.error错误,而不用console.log通过包装器函数添加某些内容。
Alvin Wong

2
@AlvinWong是的,我知道,但是问题是我需要一个全局调试开关,该开关控制是否console需要使用。为了实现这一目标,包装器似乎是唯一的方法?
鲁弗斯(Rufus)2012年

对于Google Chrome浏览器,请访问stackoverflow.com/a/25729203/1429301 您的情况是模式为debug.js
Frison Alexander

Answers:


117

这是一个古老的问题,提供的所有答案都太过分了,存在跨浏览器的重大问题,并且没有提供任何超级有用的东西。该解决方案可在每种浏览器中使用,并完全按需报告所有控制台数据。无需黑客,只需一行代码即可签出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:

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

如果您想对此做一些有用的事情,则可以添加所有控制台方法并将其包装在可重用的函数中,该函数不仅提供全局控制,而且还提供类级别:

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!')

现在,您可以将其添加到您的班级中:

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

16
如果我错了,请纠正我,但是这不允许您添加任何其他功能,对吗?您本质上仅是别名控制台对象?一个粗略的例子-是否没有办法为每个debug.log()两次控制台事件?
AB卡罗尔

3
@ABCarroll您可以console.log通过绑定log()包含两个对的调用的自定义函数来进行两次操作console.log,但是行号将反映console.log实际驻留的行,而不是debug.log被调用的行。但是,您可以执行一些操作,例如添加动态前缀/后缀等。还有其他方法可以补偿行号问题,但这是我认为的另一个问题。查看该项目的示例:github.com/arctelix/iDebugConsole/blob/master/README.md
arctelix,2016年

2
从47至49(含)的版本的Firefox中,此方法无效。并且仅在版本50.0a2中得到修复。FF50会在2周内发布,但是我花了几个小时才意识到为什么它不起作用。因此,我认为这些信息可能对某人有所帮助。链接
弗拉基米尔·柳比莫夫'16

我相信@ABCarroll的意思是实例中的所有内容都无法在运行时使用。对于另一个实例,只能在实例化中定义全局状态,因此,如果您以后更改this.isDebugfalse,则没有关系。我只是不知道有没有解决办法,也许是设计使然。从这个意义上讲,isDebug确实是一种误导var,应该const改为。
cregox

2
这没有回答问题“如果我想使用调用debug()的行号登录怎么办?”
technomage

24

我喜欢@fredrik的答案,所以我将其汇总为另一个答案,该答案拆分了Webkit 堆栈跟踪,并将其与@PaulIrish的安全console.log包装器合并。“标准化”filename:line为“特殊对象”,使其脱颖而出,在FF和Chrome中看起来基本相同。

在小提琴中测试:http : //jsfiddle.net/drzaus/pWe6W/

_log = (function (undefined) {
    var Log = Error; // does this do anything?  proper inheritance...?
    Log.prototype.write = function (args) {
        /// <summary>
        /// Paulirish-like console.log wrapper.  Includes stack trace via @fredrik SO suggestion (see remarks for sources).
        /// </summary>
        /// <param name="args" type="Array">list of details to log, as provided by `arguments`</param>
        /// <remarks>Includes line numbers by calling Error object -- see
        /// * http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
        /// * /programming/13815640/a-proper-wrapper-for-console-log-with-correct-line-number
        /// * https://stackoverflow.com/a/3806596/1037948
        /// </remarks>

        // via @fredrik SO trace suggestion; wrapping in special construct so it stands out
        var suffix = {
            "@": (this.lineNumber
                    ? this.fileName + ':' + this.lineNumber + ":1" // add arbitrary column value for chrome linking
                    : extractLineNumberFromStack(this.stack)
            )
        };

        args = args.concat([suffix]);
        // via @paulirish console wrapper
        if (console && console.log) {
            if (console.log.apply) { console.log.apply(console, args); } else { console.log(args); } // nicer display in some browsers
        }
    };
    var extractLineNumberFromStack = function (stack) {
        /// <summary>
        /// Get the line/filename detail from a Webkit stack trace.  See https://stackoverflow.com/a/3806596/1037948
        /// </summary>
        /// <param name="stack" type="String">the stack string</param>

        if(!stack) return '?'; // fix undefined issue reported by @sigod

        // correct line number according to how Log().write implemented
        var line = stack.split('\n')[2];
        // fix for various display text
        line = (line.indexOf(' (') >= 0
            ? line.split(' (')[1].substring(0, line.length - 1)
            : line.split('at ')[1]
            );
        return line;
    };

    return function (params) {
        /// <summary>
        /// Paulirish-like console.log wrapper
        /// </summary>
        /// <param name="params" type="[...]">list your logging parameters</param>

        // only if explicitly true somewhere
        if (typeof DEBUGMODE === typeof undefined || !DEBUGMODE) return;

        // call handler extension which provides stack trace
        Log().write(Array.prototype.slice.call(arguments, 0)); // turn into proper array
    };//--  fn  returned

})();//--- _log

这在节点中也可以使用,您可以使用以下命令进行测试:

// no debug mode
_log('this should not appear');

// turn it on
DEBUGMODE = true;

_log('you should', 'see this', {a:1, b:2, c:3});
console.log('--- regular log ---');
_log('you should', 'also see this', {a:4, b:8, c:16});

// turn it off
DEBUGMODE = false;

_log('disabled, should not appear');
console.log('--- regular log2 ---');

一个更高级的答案占了额外的console方法,如warnerror等- stackoverflow.com/a/14842659/1037948
drzaus

1
var line = stack.split('\n')[2];'undefined' is not an object
sigod

@sigod-可能取决于浏览器,或者我两年前写的内容以及浏览器已更改。您的情况如何?
drzaus

1
我的一位同事将您的代码复制粘贴到我们的项目中。它破坏了IE11和Safari 5中的网站。不确定此浏览器的其他版本。也许您会添加一张支票以备将来复制粘贴?
sigod

1
@sigod现在呢?添加if(!stack) return '?'到失败的方法中,而不是失败的方法中(因此,如果有人使用该方法本身,它们也将受到“保护”)
drzaus

18

您可以通过一些巧妙的用法来维护行号输出日志级别Function.prototype.bind

function setDebug(isDebug) {
  if (window.isDebug) {
    window.debug = window.console.log.bind(window.console, '%s: %s');
  } else {
    window.debug = function() {};
  }
}

setDebug(true);

// ...

debug('level', 'This is my message.'); // --> level: This is my message. (line X)

更进一步,您可以利用console的错误/警告/信息区别,并且仍然具有自定义级别。试试吧!

function setDebug(isDebug) {
  if (isDebug) {
    window.debug = {
      log: window.console.log.bind(window.console, '%s: %s'),
      error: window.console.error.bind(window.console, 'error: %s'),
      info: window.console.info.bind(window.console, 'info: %s'),
      warn: window.console.warn.bind(window.console, 'warn: %s')
    };
  } else {
    var __no_op = function() {};

    window.debug = {
      log: __no_op,
      error: __no_op,
      warn: __no_op,
      info: __no_op
    }
  }
}

setDebug(true);

// ...

debug.log('wat', 'Yay custom levels.'); // -> wat: Yay custom levels.    (line X)
debug.info('This is info.');            // -> info: This is info.        (line Y)
debug.error('Bad stuff happened.');     // -> error: Bad stuff happened. (line Z)

1
我已经尝试了一段时间,以console.debug(...)使用function name和自动为输出添加前缀arguments-有关如何执行此操作的任何想法?
Daniel Sokolowski14年

3
我一直在看众多的控制台包装/垫片/等。这是我遇到的第一个将保留行号与自定义输出结合在一起的方法。.bind还会为您带来一些麻烦,这可以巧妙地利用这一事实,您可以在上下文之外还绑定一个或多个参数。您可以更进一步,并通过.toString方法向其传递noop函数,该方法可以在调用log方法时运行代码!看到这个jsfiddle
Sam Hasler

2
也许不是在所有浏览器中(都没有研究过),但是在Chrome %s中用替换%o将以您期望的方式打印参数(对象是可扩展的,数字和字符串是彩色的,等等)。
anson

喜欢这个解决方案。我进行了一些更改,这些更改对我的应用程序更有效,但是其中大部分仍然完好无损且运行良好。谢谢
Ward

9

发件人:如何获取JavaScript调用函数行号?如何获取JavaScript调用者源URL?Error对象具有行号属性(以FF为单位)。所以这样的事情应该工作:

var err = new Error();
Global.console.log(level + ': '+ msg + 'file: ' + err.fileName + ' line:' + err.lineNumber);

在Webkit浏览器中 err.stack,该字符串代表当前调用堆栈。它将显示当前行号和更多信息。

更新

为了获得正确的行号,您需要在该行上调用错误。就像是:

var Log = Error;
Log.prototype.write = function () {
    var args = Array.prototype.slice.call(arguments, 0),
        suffix = this.lineNumber ? 'line: '  + this.lineNumber : 'stack: ' + this.stack;

    console.log.apply(console, args.concat([suffix]));
};

var a = Log().write('monkey' + 1, 'test: ' + 2);

var b = Log().write('hello' + 3, 'test: ' + 4);

1
new Error();给我执行它的上下文,如果我把它放进去debug.js,我会得到的info: Here is a msg. file: http://localhost/js/debug.js line:7
鲁弗斯(Rufus)2012年

1
有什么意义Log = Error?您仍在修改Error类,对吗?
drzaus

将您的答案与其他几个答案结合在一起-参见以下stackoverflow.com/a/14841411/1037948
drzaus 2013年

8

保持行号的一种方法是在这里:https : //gist.github.com/bgrins/5108712。它或多或少归结为:

if (Function.prototype.bind) {
    window.log = Function.prototype.bind.call(console.log, console);
}
else {
    window.log = function() { 
        Function.prototype.apply.call(console.log, console, arguments);
    };
}

如果不进行调试,则可以将其包装isDebug并设置window.logfunction() { }


7

您可以将行号传递给调试方法,如下所示:

//main.js
debug('Here is a msg.', (new Error).lineNumber);

在这里,(new Error).lineNumber将为您提供javascript代码中的当前行号。


2
有点冗长,不是吗?
Rufus 2012年

2
我认为足以回答您的查询。:)
Subodh 2012年

1
lineNumber属性是非标准属性,目前仅在Firefox上有效,请参见此处
Matthias

6

Chrome Devtools可让您通过 Blackboxing。您可以创建console.log包装器,该包装器可能会有副作用,调用其他函数等,并且仍保留调用包装器函数的行号。

只需将一个小的console.log包装器放到一个单独的文件中,例如

(function() {
    var consolelog = console.log
    console.log = function() {
        // you may do something with side effects here.
        // log to a remote server, whatever you want. here
        // for example we append the log message to the DOM
        var p = document.createElement('p')
        var args = Array.prototype.slice.apply(arguments)
        p.innerText = JSON.stringify(args)
        document.body.appendChild(p)

        // call the original console.log function
        consolelog.apply(console,arguments)
    }
})()

将其命名为log-blackbox.js

然后转到Chrome Devtools设置并找到“黑匣子”部分,为要黑匣子的文件名添加一个模式,在本例中为log-blackbox.js


注意:确保你没有你的任何代码要在堆栈跟踪显示在同一个文件,它也将被从跟踪中删除。
jamesthollowell

6

我找到了一个简单的解决方案,将接受的答案(绑定到console.log / error / etc)与一些外部逻辑相结合,以过滤实际记录的内容。

// or window.log = {...}
var log = {
  ASSERT: 1, ERROR: 2, WARN: 3, INFO: 4, DEBUG: 5, VERBOSE: 6,
  set level(level) {
    if (level >= this.ASSERT) this.a = console.assert.bind(window.console);
    else this.a = function() {};
    if (level >= this.ERROR) this.e = console.error.bind(window.console);
    else this.e = function() {};
    if (level >= this.WARN) this.w = console.warn.bind(window.console);
    else this.w = function() {};
    if (level >= this.INFO) this.i = console.info.bind(window.console);
    else this.i = function() {};
    if (level >= this.DEBUG) this.d = console.debug.bind(window.console);
    else this.d = function() {};
    if (level >= this.VERBOSE) this.v = console.log.bind(window.console);
    else this.v = function() {};
    this.loggingLevel = level;
  },
  get level() { return this.loggingLevel; }
};
log.level = log.DEBUG;

用法:

log.e('Error doing the thing!', e); // console.error
log.w('Bonus feature failed to load.'); // console.warn
log.i('Signed in.'); // console.info
log.d('Is this working as expected?'); // console.debug
log.v('Old debug messages, output dominating messages'); // console.log; ignored because `log.level` is set to `DEBUG`
log.a(someVar == 2) // console.assert
  • 请注意,console.assert使用条件日志记录。
  • 确保浏览器的开发工具显示所有消息级别!

因为它没有提供任何行号,也没有显示日志级别的工作示例。
not2qubit

行号与直接使用控制台时相同。我用用法示例更新了答案。它没有很多票,因为两年后我回答了:)
雅各布·菲利普斯

4

如果只想控制是否使用debug并具有正确的行号,则可以执行以下操作:

if(isDebug && window.console && console.log && console.warn && console.error){
    window.debug = {
        'log': window.console.log,
        'warn': window.console.warn,
        'error': window.console.error
    };
}else{
    window.debug = {
        'log': function(){},
        'warn': function(){},
        'error': function(){}
    };
}

当需要访问调试时,可以执行以下操作:

debug.log("log");
debug.warn("warn");
debug.error("error");

如果为isDebug == true,则控制台中显示的行号和文件名将是正确的,因为debug.logetc实际上是etc的别名console.log

如果为isDebug == false,则不会显示任何调试消息,因为debug.log etc根本不执行任何操作(空函数)。

如您所知,包装函数会弄乱行号和文件名,因此,最好不要使用包装函数。


太好了,我需要注意isDebug = true和的顺序debug.js,但是这个答案确实有用!
Rufus

3
window.debug = window.console会比较干净。
fredrik

@fredrik然后,如果需要,我将需要“实现”所有成员函数isDebug == false。:{
黄文

@AlvinWong我只是想念if isDebug===true。或与此相关的事件:jsfiddle.net/fredrik/x6Jw5
fredrik

4

堆栈跟踪解决方案显示行号,但不允许单击以获取源代码,这是一个主要问题。保持这种行为的唯一解决方案是绑定到原始函数。

绑定阻止包含中间逻辑,因为该逻辑会与行号混淆。但是,通过重新定义绑定函数并使用控制台字符串替换,仍然可以实现一些其他行为。

该要点显示了一个简约的日志记录框架,该框架以34行提供模块,日志级别,格式和适当的可单击行号。使用它作为满足您自己需求的基础或灵感。

var log = Logger.get("module").level(Logger.WARN);
log.error("An error has occured", errorObject);
log("Always show this.");

编辑:要点包括在下面

/*
 * Copyright 2016, Matthieu Dumas
 * This work is licensed under the Creative Commons Attribution 4.0 International License.
 * To view a copy of this license, visit http://creativecommons.org/licenses/by/4.0/
 */

/* Usage : 
 * var log = Logger.get("myModule") // .level(Logger.ALL) implicit
 * log.info("always a string as first argument", then, other, stuff)
 * log.level(Logger.WARN) // or ALL, DEBUG, INFO, WARN, ERROR, OFF
 * log.debug("does not show")
 * log("but this does because direct call on logger is not filtered by level")
 */
var Logger = (function() {
    var levels = {
        ALL:100,
        DEBUG:100,
        INFO:200,
        WARN:300,
        ERROR:400,
        OFF:500
    };
    var loggerCache = {};
    var cons = window.console;
    var noop = function() {};
    var level = function(level) {
        this.error = level<=levels.ERROR ? cons.error.bind(cons, "["+this.id+"] - ERROR - %s") : noop;
        this.warn = level<=levels.WARN ? cons.warn.bind(cons, "["+this.id+"] - WARN - %s") : noop;
        this.info = level<=levels.INFO ? cons.info.bind(cons, "["+this.id+"] - INFO - %s") : noop;
        this.debug = level<=levels.DEBUG ? cons.log.bind(cons, "["+this.id+"] - DEBUG - %s") : noop;
        this.log = cons.log.bind(cons, "["+this.id+"] %s");
        return this;
    };
    levels.get = function(id) {
        var res = loggerCache[id];
        if (!res) {
            var ctx = {id:id,level:level}; // create a context
            ctx.level(Logger.ALL); // apply level
            res = ctx.log; // extract the log function, copy context to it and returns it
            for (var prop in ctx)
                res[prop] = ctx[prop];
            loggerCache[id] = res;
        }
        return res;
    };
    return levels; // return levels augmented with "get"
})();


这个答案只有3个投票,但比页面上的其他任何投票都更加丰富和干净
Tom

但是,看起来所有有用的部分都在外部。
Ryan The Leach

3

绑定的想法Function.prototype.bind很棒。您也可以使用npm库lines-logger。它显示原始源文件:

在您的项目中一次创建记录器的任何人:

var LoggerFactory = require('lines-logger').LoggerFactory;
var loggerFactory = new LoggerFactory();
var logger = loggerFactory.getLoggerColor('global', '#753e01');

打印日志:

logger.log('Hello world!')();

在此处输入图片说明


2

这是console在将文件名和行号或其他堆栈跟踪信息添加到输出时保留现有日志记录语句的一种方法:

(function () {
  'use strict';
  var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
  var isChrome = !!window.chrome && !!window.chrome.webstore;
  var isIE = /*@cc_on!@*/false || !!document.documentMode;
  var isEdge = !isIE && !!window.StyleMedia;
  var isPhantom = (/PhantomJS/).test(navigator.userAgent);
  Object.defineProperties(console, ['log', 'info', 'warn', 'error'].reduce(function (props, method) {
    var _consoleMethod = console[method].bind(console);
    props[method] = {
      value: function MyError () {
        var stackPos = isOpera || isChrome ? 2 : 1;
        var err = new Error();
        if (isIE || isEdge || isPhantom) { // Untested in Edge
          try { // Stack not yet defined until thrown per https://docs.microsoft.com/en-us/scripting/javascript/reference/stack-property-error-javascript
            throw err;
          } catch (e) {
            err = e;
          }
          stackPos = isPhantom ? 1 : 2;
        }

        var a = arguments;
        if (err.stack) {
          var st = err.stack.split('\n')[stackPos]; // We could utilize the whole stack after the 0th index
          var argEnd = a.length - 1;
          [].slice.call(a).reverse().some(function(arg, i) {
            var pos = argEnd - i;
            if (typeof a[pos] !== 'string') {
              return false;
            }
            if (typeof a[0] === 'string' && a[0].indexOf('%') > -1) { pos = 0 } // If formatting
            a[pos] += ' \u00a0 (' + st.slice(0, st.lastIndexOf(':')) // Strip out character count
              .slice(st.lastIndexOf('/') + 1) + ')'; // Leave only path and line (which also avoids ":" changing Safari console formatting)
            return true;
          });
        }
        return _consoleMethod.apply(null, a);
      }
    };
    return props;
  }, {}));
}());

然后像这样使用它:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <script src="console-log.js"></script>
</head>
<body>
  <script>
  function a () {
    console.log('xyz'); // xyz   (console-log.html:10)
  }
  console.info('abc'); // abc   (console-log.html:12)
  console.log('%cdef', "color:red;"); // (IN RED:) // def   (console-log.html:13)
  a();
  console.warn('uuu'); // uuu   (console-log.html:15)
  console.error('yyy'); // yyy   (console-log.html:16)
  </script>
</body>
</html>

此功能可在Firefox,Opera,Safari,Chrome和IE 10(尚未在IE11或Edge上进行测试)上运行。


不错的工作,但仍然不是我需要的100%。我想在控制台视图的右侧获得文件名和行号信息,可以在其中单击以打开源。此解决方案将信息显示为消息的一部分(例如:),该信息my test log message (myscript.js:42) VM167 mypage.html:15不那么可读,而且没有链接。因此仍然是一项出色的工作。
Frederic Leitenberger '18

是的,虽然那是理想的选择,但AFAIK无法欺骗显示在控制台中的文件名链接...
Brett Zamir

@BrettZamir在这里发布了有关此代码的问题:stackoverflow.com/questions/52618368/…–
Mahks

1
//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';
    return 'console.log(\'' + level + ': '+ JSON.stringify(msg) + '\')';
}

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

这会给我info: "Here is a msg." main.js(line:2)

但是eval可惜,还需要额外的钱。


2
评估是邪恶的!所以每一个邪恶。
fredrik

1

来自http://www.briangrinstead.com/blog/console-log-helper-function的代码:

// Full version of `log` that:
//  * Prevents errors on console methods when no console present.
//  * Exposes a global 'log' function that preserves line numbering and formatting.
(function () {
  var method;
  var noop = function () { };
  var methods = [
      'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
      'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
      'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
      'timeStamp', 'trace', 'warn'
  ];
  var length = methods.length;
  var console = (window.console = window.console || {});

  while (length--) {
    method = methods[length];

    // Only stub undefined methods.
    if (!console[method]) {
        console[method] = noop;
    }
  }


  if (Function.prototype.bind) {
    window.log = Function.prototype.bind.call(console.log, console);
  }
  else {
    window.log = function() { 
      Function.prototype.apply.call(console.log, console, arguments);
    };
  }
})();

var a = {b:1};
var d = "test";
log(a, d);

这似乎没有显示原始行号log的调用位置
ragamufin 2015年

我几乎可以确定它在测试时可以正常工作,但是我在同一页面上用“完整”版本替换了代码。在Chrome 45.至少工作
蒂莫Kähkönen

明白了 有了这些更改,现在它与其他一些答案和工作原理基本相同。我只是对您以前的代码感到好奇,因为最后您有一个应用程序,这为我提供了更多使用此代码的有趣可能性,但由于它没有显示行号,因此我回到了第一位。不过谢谢!
ragamufin 2015年

1

我最近一直在研究这个问题。需要一些非常简单的方法来控制日志记录,而且还要保留行号。我的解决方案在代码上看起来并不优雅,但是可以提供我所需的东西。如果对封闭和固定足够小心。

我在应用程序的开头添加了一个小包装:

window.log = {
    log_level: 5,
    d: function (level, cb) {
        if (level < this.log_level) {
            cb();
        }
    }
};

这样以后我就可以做:

log.d(3, function(){console.log("file loaded: utils.js");});

我已经测试了firefox和crome,并且两种浏览器似乎都按预期显示了控制台日志。如果这样填充,则始终可以扩展'd'方法并将其他参数传递给它,以便它可以执行一些额外的日志记录。

到目前为止,我的方法还没有发现任何严重的缺陷,除了日志记录中的丑陋代码行。


1

window.line = function () {
    var error = new Error(''),
        brower = {
            ie: !-[1,], // !!window.ActiveXObject || "ActiveXObject" in window
            opera: ~window.navigator.userAgent.indexOf("Opera"),
            firefox: ~window.navigator.userAgent.indexOf("Firefox"),
            chrome: ~window.navigator.userAgent.indexOf("Chrome"),
            safari: ~window.navigator.userAgent.indexOf("Safari"), // /^((?!chrome).)*safari/i.test(navigator.userAgent)?
        },
        todo = function () {
            // TODO: 
            console.error('a new island was found, please told the line()\'s author(roastwind)');        
        },
        line = (function(error, origin){
            // line, column, sourceURL
            if(error.stack){
                var line,
                    baseStr = '',
                    stacks = error.stack.split('\n');
                    stackLength = stacks.length,
                    isSupport = false;
                // mac版本chrome(55.0.2883.95 (64-bit))
                if(stackLength == 11 || brower.chrome){
                    line = stacks[3];
                    isSupport = true;
                // mac版本safari(10.0.1 (12602.2.14.0.7))
                }else if(brower.safari){
                    line = stacks[2];
                    isSupport = true;
                }else{
                    todo();
                }
                if(isSupport){
                    line = ~line.indexOf(origin) ? line.replace(origin, '') : line;
                    line = ~line.indexOf('/') ? line.substring(line.indexOf('/')+1, line.lastIndexOf(':')) : line;
                }
                return line;
            }else{
                todo();
            }
            return '😭';
        })(error, window.location.origin);
    return line;
}
window.log = function () {
    var _line = window.line.apply(arguments.callee.caller),
        args = Array.prototype.slice.call(arguments, 0).concat(['\t\t\t@'+_line]);
    window.console.log.apply(window.console, args);
}
log('hello');

这是我对这个问题的解决方案。当您调用方法:日志时,它将在您打印日志的位置打印行号


1

有一点变化是使debug()返回一个函数,然后在需要的地方执行该函数-debug(message)(); 因此可以在控制台窗口中正确显示正确的行号和调用脚本,同时允许进行多种更改,例如重定向为警报或保存到文件。

var debugmode='console';
var debugloglevel=3;

function debug(msg, type, level) {

  if(level && level>=debugloglevel) {
    return(function() {});
  }

  switch(debugmode) {
    case 'alert':
      return(alert.bind(window, type+": "+msg));
    break;
    case 'console':
      return(console.log.bind(window.console, type+": "+msg));
    break;
    default:
      return (function() {});
  }

}

由于它返回一个函数,因此需要在调试行中使用();执行该函数。其次,将消息发送到调试功能,而不是发送到返回的函数中,以便进行预处理或检查您可能需要的信息,例如检查日志级别的状态,使消息更具可读性,跳过不同类型或仅报告项目符合日志级别标准;

debug(message, "serious", 1)();
debug(message, "minor", 4)();

1

您可以在这里简化逻辑。这假定您的全局调试标志不是动态的,并且在应用程序加载时设置或作为某些配置传入。这旨在用于环境标记(例如,仅在开发模式下才打印而不在生产中)

香草JS:

(function(window){ 
  var Logger = {},
      noop = function(){};

  ['log', 'debug', 'info', 'warn', 'error'].forEach(function(level){
    Logger[level] = window.isDebug ? window.console[level] : noop;
  });

  window.Logger = Logger;
})(this);

ES6:

((window) => {
  const Logger = {};
  const noop = function(){};

  ['log', 'debug', 'info', 'warn', 'error'].forEach((level) => {
    Logger[level] = window.isDebug ? window.console[level] : noop;
  });

  window.Logger = Logger;
})(this);

模块:

const Logger = {};
const noop = function(){};

['log', 'debug', 'info', 'warn', 'error'].forEach((level) => {
  Logger[level] = window.isDebug ? window.console[level] : noop;
});

export default Logger;

角度1.x:

angular
  .module('logger', [])
  .factory('Logger', ['$window',
    function Logger($window) {
      const noop = function(){};
      const logger = {};

      ['log', 'debug', 'info', 'warn', 'error'].forEach((level) => {
        logger[level] = $window.isDebug ? $window.console[level] : noop;
      });

      return logger;
    }
  ]);

您现在需要做的就是用Logger替换所有控制台引用


1

此实现基于选定的答案,并有助于减少错误控制台中的噪音:https : //stackoverflow.com/a/32928812/516126

var Logging = Logging || {};

const LOG_LEVEL_ERROR = 0,
    LOG_LEVEL_WARNING = 1,
    LOG_LEVEL_INFO = 2,
    LOG_LEVEL_DEBUG = 3;

Logging.setLogLevel = function (level) {
    const NOOP = function () { }
    Logging.logLevel = level;
    Logging.debug = (Logging.logLevel >= LOG_LEVEL_DEBUG) ? console.log.bind(window.console) : NOOP;
    Logging.info = (Logging.logLevel >= LOG_LEVEL_INFO) ? console.log.bind(window.console) : NOOP;
    Logging.warning = (Logging.logLevel >= LOG_LEVEL_WARNING) ? console.log.bind(window.console) : NOOP;
    Logging.error = (Logging.logLevel >= LOG_LEVEL_ERROR) ? console.log.bind(window.console) : NOOP;

}

Logging.setLogLevel(LOG_LEVEL_INFO);

0

我发现这个问题的一些答案对于我的需求来说太复杂了。这是一个简单的解决方案,以Coffeescript呈现。It'a改编自布莱恩格林斯蒂德的版本在这里

它假定为全局控制台对象。

# exposes a global 'log' function that preserves line numbering and formatting.
(() ->
    methods = [
      'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
      'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
      'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
      'timeStamp', 'trace', 'warn']
    noop = () ->
    # stub undefined methods.
    for m in methods  when  !console[m]
        console[m] = noop

    if Function.prototype.bind?
        window.log = Function.prototype.bind.call(console.log, console);
    else
        window.log = () ->
            Function.prototype.apply.call(console.log, console, arguments)
)()

0

我解决问题的方法是创建一个对象,然后使用Object.defineProperty()在该对象上创建一个新属性,然后返回console属性,该属性随后用作常规功能,但现在具有扩展的功能。

var c = {};
var debugMode = true;

var createConsoleFunction = function(property) {
    Object.defineProperty(c, property, {
        get: function() {
            if(debugMode)
                return console[property];
            else
                return function() {};
        }
    });
};

然后,要定义一个属性,您只需...

createConsoleFunction("warn");
createConsoleFunction("log");
createConsoleFunction("trace");
createConsoleFunction("clear");
createConsoleFunction("error");
createConsoleFunction("info");

现在,您可以像

c.error("Error!");

0

基于其他答案(主要是@arctelix一个),我为Node ES6创建了这个,但是快速测试也显示了在浏览器中的良好结果。我只是通过其他功能作为参考。

let debug = () => {};
if (process.argv.includes('-v')) {
    debug = console.log;
    // debug = console; // For full object access
}

0

这是我的记录器功能(基于一些答案)。希望有人可以利用它:

const DEBUG = true;

let log = function ( lvl, msg, fun ) {};

if ( DEBUG === true ) {
    log = function ( lvl, msg, fun ) {
        const d = new Date();
        const timestamp = '[' + d.getHours() + ':' + d.getMinutes() + ':' +
            d.getSeconds() + '.' + d.getMilliseconds() + ']';
        let stackEntry = new Error().stack.split( '\n' )[2];
        if ( stackEntry === 'undefined' || stackEntry === null ) {
            stackEntry = new Error().stack.split( '\n' )[1];
        }
        if ( typeof fun === 'undefined' || fun === null ) {
            fun = stackEntry.substring( stackEntry.indexOf( 'at' ) + 3,
                stackEntry.lastIndexOf( ' ' ) );
            if ( fun === 'undefined' || fun === null || fun.length <= 1 ) {
                fun = 'anonymous';
            }
        }
        const idx = stackEntry.lastIndexOf( '/' );
        let file;
        if ( idx !== -1 ) {
            file = stackEntry.substring( idx + 1, stackEntry.length - 1 );
        } else {
            file = stackEntry.substring( stackEntry.lastIndexOf( '\\' ) + 1,
                stackEntry.length - 1 );
        }
        if ( file === 'undefined' || file === null ) {
            file = '<>';
        }

        const m = timestamp + ' ' + file + '::' + fun + '(): ' + msg;

        switch ( lvl ) {
        case 'log': console.log( m ); break;
        case 'debug': console.log( m ); break;
        case 'info': console.info( m ); break;
        case 'warn': console.warn( m ); break;
        case 'err': console.error( m ); break;
        default: console.log( m ); break;
        }
    };
}

例子:

log( 'warn', 'log message', 'my_function' );
log( 'info', 'log message' );
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.