Home > Web Front-end > JS Tutorial > body text

Customize JavaScript&#s console.log

Mary-Kate Olsen
Release: 2024-09-23 06:19:07
Original
773 people have browsed it

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
Copy after login

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
Copy after login

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

The above is the detailed content of Customize JavaScript&#s console.log. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!