卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章79558本站已运行4415

自定义 JavaScript 的控制台日志

自定义 javascript 的控制台日志

如果您想知道如何将默认的 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] test
console.log({a: "b"}); // [date time] {a: "b"}
console.log("hello, %s!", "world"); // [date time] hello, world!
console.log("number: %i", 42); // [date time] number: 42
console.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] Test
log({a: "b"}); // [Date Time] {a: "b"}
log("Hello, %s!", "World"); // [Date Time] Hello, World!
log("Number: %i", 42); // [Date Time] Number: 42
log("%cStylized text", 'color: red'); // [Date Time] Stylized text

享受日志记录的乐趣,不要忘记断点;)

卓越飞翔博客
上一篇: TDD什么时候有意义?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏