如果您想知道如何将默认的 console.log() 扩展为即:用当前日期时间作为前缀:
// store the default log method:const _log = console.log;// override:console.log = (...args) => { const prefix = `[${new date().tolocalestring()}]`; if (typeof args[0] === "string") args[0] = `${prefix} ${args[0]}` else args.unshift(prefix); _log(...args);};// examples:console.log("test"); // [date time] testconsole.log({a: "b"}); // [date time] {a: "b"}console.log("hello, %s!", "world"); // [date time] hello, world!console.log("number: %i", 42); // [date time] number: 42console.log("%cstylized text", 'color: red'); // [date time] stylized text
登录后复制
编写 console.log 很乏味,因此我们不要覆盖默认行为,而是创建一个在内部使用 console.log 的 log() 函数:
const log = (...args) => { const prefix = `[${new Date().toLocaleString()}]`; if (typeof args[0] === "string") args[0] = `${prefix} ${args[0]}` else args.unshift(prefix); console.log(...args);};// Examples:log("Test"); // [Date Time] Testlog({a: "b"}); // [Date Time] {a: "b"}log("Hello, %s!", "World"); // [Date Time] Hello, World!log("Number: %i", 42); // [Date Time] Number: 42log("%cStylized text", 'color: red'); // [Date Time] Stylized text
登录后复制
享受日志记录的乐趣,不要忘记断点;)
以上就是自定义 JavaScript 的控制台日志的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2668300.html