npm package: @supriyodana/pretty-console-log
Description: Simple colorful logger for Node.js
Author: supriyodana
Latest version: 2.0.0

# 🎨 Pretty Console Log

> **Colorful, Modern Logger for Node.js** — Make your console output beautiful and meaningful ✨

<div align="center">

[![npm version](https://img.shields.io/badge/npm-2.0.0-blue?style=flat-square&logo=npm)](https://www.npmjs.com/package/@supriyodana/pretty-console-log)
[![License](https://img.shields.io/badge/license-MIT-green?style=flat-square)](LICENSE)
[![Node.js](https://img.shields.io/badge/node-14+-green?style=flat-square&logo=node.js)](https://nodejs.org/)
[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-3178c6?style=flat-square&logo=typescript)](src/index.d.ts)
[![Zero Dependencies](https://img.shields.io/badge/dependencies-0-brightgreen?style=flat-square)](package.json)
[![npm downloads](https://img.shields.io/badge/dynamic/json?url=https://api.npmjs.org/downloads/point/last-month/@supriyodana/pretty-console-log&query=$.downloads&label=downloads%2Fmonth&style=flat-square&color=brightgreen)](https://www.npmjs.com/package/@supriyodana/pretty-console-log)

✨ **Lightweight** • 🎯 **Modular** • 📊 **Flexible** • 🔓 **Zero Dependencies** • 💚 **Production-Ready**

</div>

---

## 📑 Table of Contents

- [✨ Features](#-features)
- [📦 Installation](#-installation)
- [🚀 Quick Start](#-quick-start)
- [📚 API Reference](#-api-reference)
- [💡 Usage Examples](#-usage-examples)
- [⚙️ Advanced Configuration](#-advanced-configuration)
- [📘 TypeScript Support](#-typescript-support)
- [📋 Log Level Hierarchy](#-log-level-hierarchy)
- [🎯 Best Practices](#-best-practices)

---

## ✨ Features

<table>
<tr>
<td width="50%">

- 🎯 **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

</td>
<td width="50%">

- 📊 **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

</td>
</tr>
</table>

---

## 📦 Installation

### via NPM

```bash
npm install @supriyodana/pretty-console-log
```

### via Yarn

```bash
yarn add @supriyodana/pretty-console-log
```

### via PNPM

```bash
pnpm add @supriyodana/pretty-console-log
```

**Requirements:** Node.js 14 or higher

---

## 🚀 Quick Start

### Basic Usage

Get up and running in seconds:

```javascript
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:

```javascript
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**.

```javascript
log.success("User created", "AUTH");
log.success("Database connected", "DB");
log.success("File uploaded");
// [12:40:00] [AUTH] ✔ SUCCESS: User created
```

**Parameters:**
- `message` (string): Success message to log
- `prefix?` (string): Optional context prefix

---

#### ✖️ `log.error(message, prefix?)`

Log errors in **red** (always visible).

```javascript
log.error("Connection timeout", "API");
log.error("Invalid token", "AUTH");
log.error("Server crashed");
// [12:40:00] [API] ✖ ERROR: Connection timeout
```

**Parameters:**
- `message` (string): Error message to log
- `prefix?` (string): Optional context prefix

---

#### ⚠️ `log.warn(message, prefix?)`

Log warnings in **yellow**.

```javascript
log.warn("Deprecated API used");
log.warn("High memory usage", "SYSTEM");
log.warn("Rate limit approaching", "API");
// [12:40:00] ⚠ WARNING: Deprecated API used
```

**Parameters:**
- `message` (string): Warning message to log
- `prefix?` (string): Optional context prefix

---

#### ℹ️ `log.info(message, prefix?)`

Log information in **blue**.

```javascript
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 3000
```

**Parameters:**
- `message` (string): Informational message to log
- `prefix?` (string): Optional context prefix

---

#### 🐞 `log.debug(message, prefix?)`

Log debug info in **magenta** (hidden in production).

```javascript
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 log
- `prefix?` (string): Optional context prefix

---

### Configuration Methods

---

#### 🌍 `log.setEnvironment(env)`

Control where debug logs appear.

```javascript
// 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"); // ✅ Visible
```

**Parameters:**
- `env` (string): Environment - `"development"` or `"production"`

---

#### 📊 `log.setLogLevel(level)`

Filter logs by severity level.

```javascript
// 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 visible
```

**Parameters:**
- `level` (string): Log level - `"debug"`, `"info"`, `"warn"`, or `"error"`

---

#### ⏰ `log.setShowTimestamp(show)`

Toggle timestamp display.

```javascript
log.setShowTimestamp(true);  // [12:40:00] ✔ SUCCESS: Done
log.setShowTimestamp(false); // ✔ SUCCESS: Done
```

**Parameters:**
- `show` (boolean): Whether to show timestamps

---

## 💡 Usage Examples

Real-world scenarios and patterns for using pretty-console-log effectively.

### Real-World Application Startup

```javascript
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

```javascript
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:

```javascript
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

```javascript
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

```javascript
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" });
  }
});
```

---

<a id="-advanced-configuration"></a>

## ⚙️ Advanced Configuration

Take full control of your logging behavior with custom logger instances.

### Creating Logger Instances

```javascript
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

```typescript
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:

```typescript
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 |

```javascript
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
```javascript
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
```javascript
const env = process.env.NODE_ENV || "development";
log.setEnvironment(env);
```

✅ **Use appropriate log levels** — Match severity to message type
```javascript
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
```javascript
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
```javascript
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](./API.md)

---

<div align="center">

**[⬆ back to top](#-pretty-console-log)**

**Happy logging!**

</div>