In-Page Logging for Web Devs – PrettyLogger.js

Category: Javascript | August 24, 2024
AuthorMidi12
Last UpdateAugust 24, 2024
LicenseMIT
Views39 views
In-Page Logging for Web Devs – PrettyLogger.js

PrettyLogger is a tiny JavaScript that logs plain messages, objects, and event DOM elements directly into your page for easy debugging.

Instead of sifting through browser console logs, you can view debug information in context, right alongside your application. This makes identifying and resolving issues during development easier.

How it works:

PrettyLogger uses an IIFE (Immediately Invoked Function Expression) for module encapsulation. It supports AMD, CommonJS, and global variable assignment for different environments.

The main PrettyLogger function initializes the logger with a specified debug panel ID. It includes methods for creating log entries, formatting messages, and handling different data types.

Key features:

  • Timestamp generation for each log entry
  • Color-coding based on log levels
  • Object and DOM element formatting with collapsible structures
  • HTML escaping for safe display
  • Depth-limited recursion to prevent infinite loops
  • Event listeners for expanding/collapsing nested structures
  • The logger uses DOM manipulation in browser environments and falls back to console.log for non-browser contexts.

How to use it:

1. Add the PrettyLogger CSS and JavaScript files to your HTML page.

<link rel="stylesheet" href="/src/pretty-logger.css">
<script src="/src/pretty-logger.js"></script>

2. Create an empty <div> element where you want the logs to appear. Give it a unique ID for reference.

<div id="debug">
</div>

3. Create a new PrettyLogger instance and pass in the ID of your log container element.

var logger = new PrettyLogger('debug');

4. You can now use the logger’s methods to display various log types:

// info message
logger.info('This is an informational message');
// warning message
logger.warn('This is a warning message');
// A JS Object
logger.error({ 
  message: 'An error occurred', 
  code: 404 
});
// Log DOM elements
logger.debug(document.getElementById('myElement'));

Changelog:

08/24/2024

  • Added arry handling

You Might Be Interested In:


Leave a Reply