@supriyodana/pretty-console-log
v2.0.0
Published
Simple colorful logger for Node.js
Maintainers
Readme
🎨 Pretty Console Log
Colorful, Modern Logger for Node.js — Make your console output beautiful and meaningful ✨
✨ Lightweight • 🎯 Modular • 📊 Flexible • 🔓 Zero Dependencies • 💚 Production-Ready
📑 Table of Contents
- ✨ Features
- 📦 Installation
- 🚀 Quick Start
- 📚 API Reference
- 💡 Usage Examples
- ⚙️ Advanced Configuration
- 📘 TypeScript Support
- 📋 Log Level Hierarchy
- 🎯 Best Practices
✨ Features
- 🎯 Multiple Log Levels — success, error, warning, info, debug
- 🏷️ Custom Prefixes — Tag logs with context (API, DB, AUTH, CACHE, etc.)
- 🕐 Timestamps — Automatic time formatting in locale format
- 🌍 Environment Control — Automatically hide debug logs in production
- 📊 Log Level Filtering — Show only warnings and errors when needed
- 🔧 Full Customization — Create multiple logger instances with different configs
- 📘 TypeScript Support — Fully typed for better development experience
- 🔓 Zero Dependencies — Tiny footprint, no external packages needed
- 💚 Colorful Output — Easy-to-read colored console messages with symbols
📦 Installation
via NPM
npm install @supriyodana/pretty-console-logvia Yarn
yarn add @supriyodana/pretty-console-logvia PNPM
pnpm add @supriyodana/pretty-console-logRequirements: Node.js 14 or higher
🚀 Quick Start
Basic Usage
Get up and running in seconds:
const log = require("@supriyodana/pretty-console-log");
// Simple logging
log.success("Server started");
log.error("Database failed");
log.warn("Memory usage high");
log.info("User logged in");
log.debug("Loading configuration");With Custom Prefixes
Add context to your logs using prefixes:
const log = require("@supriyodana/pretty-console-log");
log.success("Server started", "API");
log.error("Database failed", "DB");
log.warn("Cache miss", "CACHE");
log.info("Payment processed", "PAYMENT");
log.debug("Variable x = 42", "DEBUG");Output Preview
Here's what your console output looks like:
[12:40:00] ✔ SUCCESS: Server started
[12:40:01] [API] ✔ SUCCESS: User created
[12:40:02] [DB] ✖ ERROR: Connection timeout
[12:40:03] ⚠ WARNING: Memory usage high
[12:40:04] ℹ INFO: Server listening on port 3000
[12:40:05] [DEBUG] 🐞 DEBUG: Loading configuration📚 API Reference
Comprehensive documentation for all logging methods and configuration options.
Core Logging Methods
✔️ log.success(message, prefix?)
Log successful operations in green.
log.success("User created", "AUTH");
log.success("Database connected", "DB");
log.success("File uploaded");
// [12:40:00] [AUTH] ✔ SUCCESS: User createdParameters:
message(string): Success message to logprefix?(string): Optional context prefix
✖️ log.error(message, prefix?)
Log errors in red (always visible).
log.error("Connection timeout", "API");
log.error("Invalid token", "AUTH");
log.error("Server crashed");
// [12:40:00] [API] ✖ ERROR: Connection timeoutParameters:
message(string): Error message to logprefix?(string): Optional context prefix
⚠️ log.warn(message, prefix?)
Log warnings in yellow.
log.warn("Deprecated API used");
log.warn("High memory usage", "SYSTEM");
log.warn("Rate limit approaching", "API");
// [12:40:00] ⚠ WARNING: Deprecated API usedParameters:
message(string): Warning message to logprefix?(string): Optional context prefix
ℹ️ log.info(message, prefix?)
Log information in blue.
log.info("Server running on port 3000", "SERVER");
log.info("Cache refreshed", "CACHE");
log.info("Configuration loaded");
// [12:40:00] [SERVER] ℹ INFO: Server running on port 3000Parameters:
message(string): Informational message to logprefix?(string): Optional context prefix
🐞 log.debug(message, prefix?)
Log debug info in magenta (hidden in production).
log.debug("User object: {...}", "DEBUG");
log.debug("Query: SELECT * FROM users", "DB");
log.debug("Initializing middleware");
// [12:40:00] [DEBUG] 🐞 DEBUG: User object: {...}Parameters:
message(string): Debug message to logprefix?(string): Optional context prefix
Configuration Methods
🌍 log.setEnvironment(env)
Control where debug logs appear.
// Development: All logs visible
log.setEnvironment("development");
log.debug("This shows in development", "DEV"); // ✅ Visible
// Production: Debug logs hidden
log.setEnvironment("production");
log.debug("This is hidden in production", "DEV"); // ❌ Hidden
log.error("But errors always show", "ERROR"); // ✅ VisibleParameters:
env(string): Environment -"development"or"production"
📊 log.setLogLevel(level)
Filter logs by severity level.
// Show all logs (default)
log.setLogLevel("debug");
// ✅ Debug, Info, Warn, Error all visible
// Show only important messages
log.setLogLevel("warn");
// ❌ Debug & Info hidden
// ✅ Warn & Error visible
// Show only errors
log.setLogLevel("error");
// ❌ Debug, Info, Warn hidden
// ✅ Error visibleParameters:
level(string): Log level -"debug","info","warn", or"error"
⏰ log.setShowTimestamp(show)
Toggle timestamp display.
log.setShowTimestamp(true); // [12:40:00] ✔ SUCCESS: Done
log.setShowTimestamp(false); // ✔ SUCCESS: DoneParameters:
show(boolean): Whether to show timestamps
💡 Usage Examples
Real-world scenarios and patterns for using pretty-console-log effectively.
Real-World Application Startup
const log = require("@supriyodana/pretty-console-log");
log.info("Application starting", "APP");
log.debug("Loading configuration", "CONFIG");
log.debug("Reading environment variables", "ENV");
log.info("Connecting to database", "DB");
log.debug("Database connection string: ...", "DB");
log.success("Connected to MongoDB", "DB");
log.info("Initializing API routes", "API");
log.debug("Registering 25 routes", "API");
log.success("API routes initialized", "API");
log.info("Starting server", "SERVER");
log.success("Server listening on http://localhost:3000", "SERVER");Error Handling with Context
const log = require("@supriyodana/pretty-console-log");
async function fetchUserData(userId) {
try {
log.debug(`Fetching user ${userId}`, "API");
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) {
log.error(`User ${userId} not found (404)`, "API");
return null;
}
const data = await response.json();
log.success(`User ${userId} fetched successfully`, "API");
return data;
} catch (error) {
log.error(`Failed to fetch user: ${error.message}`, "API");
throw error;
}
}Multiple Logger Instances
Create separate loggers for different environments:
const { Logger } = require("@supriyodana/pretty-console-log");
// Development logger (all logs visible)
const devLogger = new Logger({
environment: "development",
logLevel: "debug",
showTimestamp: true
});
// Production logger (only errors and warnings)
const prodLogger = new Logger({
environment: "production",
logLevel: "warn",
showTimestamp: true
});
// Use appropriate logger
const logger = process.env.NODE_ENV === "production" ? prodLogger : devLogger;
logger.info("Application started", "APP");
logger.debug("Debug info", "DEV");Database Operations
const log = require("@supriyodana/pretty-console-log");
async function createUser(userData) {
try {
log.debug(`Creating user with email: ${userData.email}`, "DB");
const user = await User.create(userData);
log.success(`User created with ID: ${user.id}`, "DB");
return user;
} catch (error) {
if (error.code === "DUPLICATE_KEY") {
log.warn(`User with email ${userData.email} already exists`, "DB");
} else {
log.error(`Database error: ${error.message}`, "DB");
}
}
}API Request/Response Logging
const log = require("@supriyodana/pretty-console-log");
app.get("/users/:id", (req, res) => {
const userId = req.params.id;
log.debug(`GET request for user ${userId}`, "ROUTE");
try {
const user = findUser(userId);
if (!user) {
log.warn(`User ${userId} not found`, "ROUTE");
return res.status(404).json({ error: "Not found" });
}
log.info(`Returning user ${userId} data`, "ROUTE");
res.json(user);
} catch (error) {
log.error(`Request failed: ${error.message}`, "ROUTE");
res.status(500).json({ error: "Server error" });
}
});⚙️ Advanced Configuration
Take full control of your logging behavior with custom logger instances.
Creating Logger Instances
const { Logger } = require("@supriyodana/pretty-console-log");
// Create a custom logger
const logger = new Logger({
environment: "development",
logLevel: "debug",
showTimestamp: true
});
logger.success("Logger initialized", "SYSTEM");Logger Options
interface LoggerOptions {
// Current environment
environment?: "development" | "production"; // default: "development"
// Initial log level
logLevel?: "debug" | "info" | "warn" | "error"; // default: "debug"
// Show timestamps
showTimestamp?: boolean; // default: true
}📘 TypeScript Support
Fully typed for TypeScript projects with complete IntelliSense support:
import { Logger } from "@supriyodana/pretty-console-log";
const logger = new Logger({
environment: "development",
logLevel: "debug",
showTimestamp: true
});
logger.success("Connected to database", "DB");
logger.error("Connection failed", "DB");
logger.warn("High memory usage", "SYSTEM");
logger.info("Server ready", "SERVER");
logger.debug("Debug information", "DEV");Type Safety Benefits:
- ✅ Full autocomplete for method names
- ✅ Parameter validation at development time
- ✅ IntelliSense documentation hints
- ✅ Catch errors before runtime
📋 Log Level Hierarchy
The log level determines what gets shown in your console:
| Level | Shows | Hides |
|-------|-------|-------|
| debug | Debug, Info, Warn, Error | — |
| info | Info, Warn, Error | Debug |
| warn | Warn, Error | Debug, Info |
| error | Error | Debug, Info, Warn |
log.setLogLevel("warn");
log.debug("Hidden"); // ❌
log.info("Hidden"); // ❌
log.warn("Visible"); // ✅
log.error("Visible"); // ✅🎯 Best Practices
Make the most of pretty-console-log with these proven patterns and conventions:
🎓 Pro Tip: Following these best practices will make your logs more useful and your debugging more efficient.
✅ Use prefixes for context — Always add prefixes to identify source
log.error("Connection failed", "DB"); // ✅ Good
log.error("Connection failed"); // ⚠️ Less clear✅ Set environment based on NODE_ENV — Let debug logs help in development only
const env = process.env.NODE_ENV || "development";
log.setEnvironment(env);✅ Use appropriate log levels — Match severity to message type
log.debug("Processing item #42", "WORKER"); // ✅ Debug info
log.info("Task completed", "WORKER"); // ✅ Important event
log.warn("Performance degraded", "SYSTEM"); // ✅ Attention needed
log.error("Task failed", "WORKER"); // ✅ Error✅ Include relevant data in messages — Make logs actionable
log.info(`User logged in from ${ip}`, "AUTH"); // ✅ Useful
log.info("User logged in", "AUTH"); // ⚠️ Less useful✅ Create application-specific logger instances — Keep configurations organized
const { Logger } = require("@supriyodana/pretty-console-log");
const appLogger = new Logger({
environment: process.env.NODE_ENV || "development",
logLevel: process.env.LOG_LEVEL || "debug",
showTimestamp: true
});For more information, see API.md
Happy logging!
