DEV Community

Cover image for Creating a Custom Console Logger in JavaScript
Kiril Delovski
Kiril Delovski

Posted on

Creating a Custom Console Logger in JavaScript

In the following tutorial, you will learn how to make a "custom console logging in a html page" instead of accessing the browser native developer tools "console section".

Let's Start đź‘€

1) First we Start with the HTML file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

</head>
<body>
    <script>
        // add your console.log() here
        setTimeout(()=> {
            console.log('...this is console.log');
        }, 100);
        // add your console.info() here
        setTimeout(()=> {
            console.info('...this is console.info');
        }, 110);
        // add your console.warn() here
        setTimeout(()=> {
            console.warn('...this is console.warn');
        }, 120);
        // add your console.debug() here
        setTimeout(()=> {
            console.debug('...this is console.debug');
        }, 130);
        // add your console.error() here
        setTimeout(()=> {
            console.error('...this is console.error');
        }, 140);
    </script>
    <script src="console-script.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
  • The scripts block is your place where u want to write your js and your js logic with the needed console keyword.

  • The following script tag is for importing our custom js for overriding the default console methods and to display their output in the custom console container as well as the browser's console.

2) Secondly we Start with the JS file

(function() {
    // Dynamically import CSS file
    const link = document.createElement('link');
    link.rel = 'stylesheet';
    link.type = 'text/css';
    link.href = 'console-style.css';
    document.head.appendChild(link);

    // Create toggle button
    const toggleConsoleBtn = document.createElement('div');
    toggleConsoleBtn.id = 'toggleConsoleBtn';
    toggleConsoleBtn.className = 'toggle-console-btn';
    toggleConsoleBtn.textContent = 'Show Console';
    document.body.appendChild(toggleConsoleBtn);

    // Create console container
    const consoleContainer = document.createElement('div');
    consoleContainer.id = 'consoleContainer';
    consoleContainer.className = 'console-container';
    document.body.appendChild(consoleContainer);

    let consoleVisible = false;

    // Toggle console visibility
    toggleConsoleBtn.addEventListener('click', function() {
        consoleVisible = !consoleVisible;
        if (consoleVisible) {
            consoleContainer.classList.add('show');
            toggleConsoleBtn.textContent = 'Hide Console';
            toggleConsoleBtn.style.bottom = 'calc(200px + 20px)'; // Adjust based on console window height
        } else {
            consoleContainer.classList.remove('show');
            toggleConsoleBtn.textContent = 'Show Console';
            toggleConsoleBtn.style.bottom = '10px'; // Set back to bottom of the screen
        }
    });

    // Save reference to original console methods
    const originalConsoleLog = console.log;
    const originalConsoleInfo = console.info;
    const originalConsoleDebug = console.debug;
    const originalConsoleWarn = console.warn;
    const originalConsoleError = console.error;

    // Override console.log method
    console.log = function() {
        // Call original console.log with the arguments
        originalConsoleLog.apply(console, arguments);

        // Output message to UI with color (limegreen)
        appendToConsole(arguments, 'log', 'limegreen');
    };

    // Override console.info method
    console.info = function() {
        // Call original console.info with the arguments
        originalConsoleInfo.apply(console, arguments);

        // Output message to UI with color (cornflowerblue)
        appendToConsole(arguments, 'info', 'cornflowerblue');
    };

    // Override console.debug method
    console.debug = function() {
        // Call original console.debug with the arguments
        originalConsoleDebug.apply(console, arguments);

        // Output message to UI with color (darkgray)
        appendToConsole(arguments, 'debug', 'darkgray');
    };

    // Override console.warn method
    console.warn = function() {
        // Call original console.warn with the arguments
        originalConsoleWarn.apply(console, arguments);

        // Output message to UI with color (orange)
        appendToConsole(arguments, 'warn', 'orange');
    };

    // Override console.error method
    console.error = function() {
        // Call original console.error with the arguments
        originalConsoleError.apply(console, arguments);

        // Output message to UI with color (orangered)
        appendToConsole(arguments, 'error', 'orangered');
    };

    // Function to append message to UI
    function appendToConsole(args, messageType, color) {
        const message = Array.prototype.slice.call(args).join(' '); // Convert arguments to a string
        const messageElement = document.createElement('p');
        messageElement.textContent = message;
        if (color) {
            messageElement.style.color = color;
        }
        if (messageType) {
            messageElement.classList.add(messageType);
        }
        const consoleContainer = document.getElementById('consoleContainer');
        consoleContainer.appendChild(messageElement);
        // Scroll to bottom (assuming console-output is the ID of your console container)
        consoleContainer.scrollTop = consoleContainer.scrollHeight;
    }

})();
Enter fullscreen mode Exit fullscreen mode

3) Thirdly we Start with the CSS file

body {
    margin: 0;
    padding: 0;
    position: relative;
    min-height: 100vh; /* Ensure the body takes up the entire viewport height */
}

.console-container {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 200px; /* Set desired height */
    background-color: rgba(0,0,0,0.8);
    -webkit-backdrop-filter: blur(10px);
    backdrop-filter: blur(10px);
    color: white;
    overflow-y: auto; /* Enable scrolling if content exceeds height */
    padding: 10px;
    box-sizing: border-box;
    font-family: monospace;
    display: none; /* Initially hidden */
    z-index: 1; /* Ensure the console window is behind the button */
    border-top: 5px solid silver;
}

.console-container.show {
    display: block; /* Show when toggled */
}

.console-container p {
    margin: 0;
    white-space: pre-wrap;
}

.console-container .warn {
    color: yellow;
}

.console-container .error {
    color: red;
}

.toggle-console-btn {
    position: fixed;
    bottom: 10px; /* Initially set to bottom of the screen */
    left: 10px;
    padding: 8px 16px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 14px;
    z-index: 2; /* Ensure the button is on top of the console window */
}

Enter fullscreen mode Exit fullscreen mode

Final notes:

    Feel free to use it or contribute to the project to improve it or make additional functionalities.

To see the working example or visit the github repo .


For any questions or information about me you can reach out by scanning or clicking on the following qr code:



scan qr code to find more about me

Top comments (1)

Collapse
 
kiril6 profile image
Kiril Delovski

Looking to excel in your JavaScript interviews? Check out this comprehensive article: JavaScript Interview Cheat Sheet Manual.