DEV Community

Roko C. Buljan
Roko C. Buljan

Posted on

Customize JavaScript's console.log

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay