Logo

dev-resources.site

for different kinds of informations.

Creating a Custom Console Logger in JavaScript

Published at
4/16/2024
Categories
javascript
consolelogging
customconsole
learntocode
Author
kiril6
Author
6 person written this
kiril6
open
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

learntocode Article's
30 articles in total
Favicon
Your Journey to Web Development: A Beginner's Guide to Frontend Development
Favicon
MYTH: You Need a CS Degree to Get Started with Software Engineering
Favicon
Decoding YouTube Programming Tutorials: Escape Tutorial Hell ๐Ÿ”ฅ
Favicon
Demystifying Data Structure Algorithms: A Series on Patterns, Complexities, and Real-World Insights
Favicon
Why Industrial Python Training is the Ultimate Career Boost
Favicon
๐“๐ก๐ž ๐Œ๐ข๐ฌ๐ญ๐š๐ค๐ž๐ฌ ๐ˆ ๐Œ๐š๐๐ž ๐€๐ฌ ๐š ๐๐ž๐ ๐ข๐ง๐ง๐ž๐ซ ๐๐ซ๐จ๐ ๐ซ๐š๐ฆ๐ฆ๐ž๐ซ
Favicon
Creating Extensions In Opera For Beginners
Favicon
JavaScript for Beginners: All You Need to Know to Perfect Your Basics
Favicon
Unable To Open Dompdf PDF File? Here's The Solution
Favicon
Why Learn to Program? Key Benefits from Different Perspectives
Favicon
Creating Reusable HTML Components In PHP
Favicon
Why Irohub Infotech is the Best Python Training in Kochi
Favicon
The Path to Coding Mastery A Beginner's Guide
Favicon
Reconnecting with Front-End Development: Building a Cat Photo App
Favicon
Is learning to code hard? A pragmatic guide
Favicon
Pros and Cons of Choosing Python as Your Programming Language
Favicon
3 things I'd do differently if I learned to code today
Favicon
How to learn to code with AI in 2024
Favicon
Learning Programming for Beginners: How to Get Started
Favicon
Creating a Custom Console Logger in JavaScript
Favicon
What is Vscode
Favicon
5 things I wish I knew before I learned to code
Favicon
Harnessing Your Inner Saiyan: Mastering Programming Languages Through the Lens of Dragon Ball Z
Favicon
How GIGO uses NATS to talk across its cluster
Favicon
Which is More Important: Hard or Soft Skills for Programmers?
Favicon
What exactly led me to push myself into learning how to code?
Favicon
What is a REST API?
Favicon
Scrimba's Teacher Talent Program - An Awesome Learning Experience
Favicon
Redis client-side cache with async Python
Favicon
The Mycelium Network Podcast

Featured ones: