首页 > web前端 > js教程 > 正文

Customize JavaScript&#s console.log

Mary-Kate Olsen
发布: 2024-09-23 06:19:07
原创
805 人浏览过

Customize JavaScript

If you ever wondered how to extend the default console.log() to i.e: prefix it with the current date-time:

// 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
登录后复制

Writing console.log is tedious, so instead of overriding the default behavior let's just create a log() function that uses console.log internally:

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
登录后复制

Have fun logging, and don't forget about breakpoints ;)

以上是Customize JavaScript&#s console.log的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板