如果您想知道如何将默认的 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
享受日志记录的乐趣,不要忘记断点;)