【问题标题】:How to omit file/line number with console.log如何使用 console.log 省略文件/行号
【发布时间】:2016-06-30 18:17:50
【问题描述】:

如今,您可以在 Chrome 的控制台中编写相当不错的东西。结帐this 链接。我也做了截图:

您也可以在屏幕截图中看到,文件名/行号 (VM298:4) 写在右侧。是否有可能删除它,因为在我的情况下,这是一个很长的名称,或多或少会破坏我试图在我的控制台中产生的效果?

【问题讨论】:

    标签: javascript browser google-chrome-devtools console.log


    【解决方案1】:

    这很简单。您需要将setTimeoutconsole.log.bind 一起使用:

    setTimeout (console.log.bind (console, "This is a sentence."));
    

    如果您想对其应用 CSS 或其他文本,只需添加 %c 或任何其他 % 变量:

    setTimeout (console.log.bind (console, "%cThis is a sentence.", "font-weight: bold;"));
    var css = "text-decoration: underline;";
    setTimeout (console.log.bind (console, "%cThis is a sentence.", css));
    

    请注意,此方法将始终放在日志列表的末尾。例如:

    console.log ("Log 1");
    setTimeout (console.log.bind (console, "This is a sentence."));
    console.log ("Log 2");
    

    将显示为

    Log 1
    Log 2
    This is a sentence.
    

    而不是

    Log 1
    This is a sentence.
    Log 2
    

    我希望这能回答你的问题。

    【讨论】:

      【解决方案2】:

      为了保持你的日志语句干净,你可以定义以下函数并简单地使用console.print 来记录没有文件名/行号:

      // console.print: console.log without filename/line number
      console.print = function (...args) {
          queueMicrotask (console.log.bind (console, ...args));
      }
      

      console.print 采用与console.log 相同的参数,例如:

      console.print("Text with no filename info.")

      console.print('%c Custom CSS and no line numbers! ', 'background: #555555; color: #00aaff');

      【讨论】:

      • 嵌套在console.group()中时,似乎显示的日志乱序。
      【解决方案3】:

      另一种选择是使用 sourceURL 为源脚本文件提供更短的名称

      //# sourceURL=new_file_name.js 
      

      【讨论】:

        【解决方案4】:

        在记录时使用queueMicrotaskconsole.log.bind 来释放源文件信息:

        queueMicrotask (console.log.bind (console, "Look! No source file info..."));
        

        如果有多个调用,排队的微任务将保持日志记录的顺序,而setTimeout不保证按顺序执行任务。

        【讨论】:

        • 仅供参考 setTimeout 保证订单。它只是不保证它会在准确的时间被调用。
        猜你喜欢
        • 2020-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-20
        • 2013-03-06
        • 1970-01-01
        • 1970-01-01
        • 2019-10-19
        相关资源
        最近更新 更多