Creating a Custom Console Logger in JavaScript
Tags: javascript, consolelogging, customconsole, learntocode
Published: 2024-04-16 13:24:53

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**
```html
<!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>
```
- 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**
```javascript
(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;
    }

})();
```

**3) Thirdly we Start with the CSS file**
```css
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 */
}

```

<h1>Final notes:</h1>
&nbsp;&nbsp;&nbsp;&nbsp;Feel free to use it or contribute to the project to improve it or make additional functionalities.

To see the working <a alt="see the working example" href="https://github.com/kiril6/customConsoleLogger"><b>example</b> </a>or visit the <a alt="visit the github repo" href="https://kiril6.github.io/customConsoleLogger/"><b>github repo</b> </a>.


<hr>
<p><i><b> For any questions or information about me you can reach out by scanning or clicking on the following qr code:</b></i></p>
<br>
<a href="http://delovski.net/qr" alt="find more about me"><img src="https://dev-to-uploads.s3.amazonaws.com/i/xtl2ad51u4zxctqvq8e2.PNG" alt="scan qr code to find more about me"/></a>