1.1.0 โ€ข Published 5 months ago

@ru-dr/plip v1.1.0

Weekly downloads
-
License
MIT
Repository
github
Last release
5 months ago

๐Ÿซง Plip Logger

A delightful, colorful logging experience for modern Node.js applications

npm version License: MIT TypeScript

Installation โ€ข Quick Start โ€ข Documentation โ€ข Examples โ€ข Contributing


โœจ Why Plip?

Tired of boring console logs? Plip brings joy back to logging with:

  • ๐ŸŒˆ Smart Colors - Automatic terminal detection with beautiful color schemes
  • ๐Ÿ˜Š Expressive Emojis - Visual context that makes logs easier to scan
  • ๐ŸŽฏ 7 Log Levels - From verbose to error, perfect granularity
  • ๐Ÿ” Syntax Highlighting - JSON objects rendered beautifully
  • โš™๏ธ Fluent API - Chain methods for elegant configuration
  • ๐Ÿš€ Zero Config - Works great out of the box, CSR by default
  • ๐ŸŒ SSR/CSR Optimized - Specialized configs for server and client environments
  • ๐Ÿ“ฆ TypeScript First - Full type safety and IntelliSense
  • ๐Ÿ”ง Environment Aware - Respects NODE_ENV and terminal capabilities

๐Ÿ“ฆ Installation

::: code-group

$ npm install @ru-dr/plip
$ yarn add @ru-dr/plip
$ pnpm add @ru-dr/plip
$ bun add @ru-dr/plip

:::

๐ŸŒ Multi-Language Support Coming Soon!
Plip is currently available for JavaScript/TypeScript environments. We're actively working on bringing the same delightful logging experience to Python, Java, PHP, and other popular languages. Follow our progress or contribute to help us expand faster!

๐Ÿš€ Quick Start

Get logging in seconds:

import { plip } from '@ru-dr/plip';

plip.info("๐ŸŽ‰ Welcome to Plip!");
plip.success("โœ… Everything is working perfectly");
plip.warn("โš ๏ธ  This might need your attention");
plip.error("๐Ÿ’ฅ Something went wrong");

// Log complex objects with beautiful syntax highlighting
plip.info("User profile:", {
  name: "Alex Developer",
  age: 28,
  skills: ["TypeScript", "Node.js", "React"],
  active: true
});

Output Preview:

๐Ÿซง [INFO] ๐ŸŽ‰ Welcome to Plip!
๐ŸŽ‰ [SUCCESS] โœ… Everything is working perfectly
โš ๏ธ [WARN] โš ๏ธ  This might need your attention
๐Ÿ’ฅ [ERROR] ๐Ÿ’ฅ Something went wrong
๐Ÿซง [INFO] User profile: {
  "name": "Alex Developer",
  "age": 28,
  "skills": ["TypeScript", "Node.js", "React"],
  "active": true
}

๐Ÿ“š API Documentation

Creating Logger Instances

import { plip, createPlip } from '@ru-dr/plip';

// Use the default logger (recommended for most cases)
plip.info("Using default logger");

// Create a custom logger with specific configuration
const customLogger = createPlip({
  enableEmojis: true,
  enableColors: true,
  enabledLevels: ['info', 'warn', 'error']
});

// Create a production logger
const prodLogger = createPlip({
  enableEmojis: false,
  enableColors: false,
  enabledLevels: ['warn', 'error']
});

๐ŸŽจ Log Levels

Plip provides 7 distinct log levels, each with its own emoji and color:

LevelEmojiDescriptionUse Case
info๐ŸซงGeneral informationApp status, user actions
success๐ŸŽ‰Success messagesCompleted operations
warnโš ๏ธWarning messagesDeprecated features, recoverable errors
error๐Ÿ’ฅError messagesExceptions, failures
debug๐Ÿ”Debug informationDevelopment debugging
trace๐Ÿ›ฐ๏ธDetailed tracingPerformance monitoring
verbose๐Ÿ“ขVerbose outputDetailed system information
// Using all log levels
plip.info("Application started successfully");
plip.success("User authenticated");
plip.warn("API rate limit approaching");
plip.error("Database connection failed");
plip.debug("Processing user request", { userId: 123 });
plip.trace("Function execution time: 45ms");
plip.verbose("System memory usage:", process.memoryUsage());

โš™๏ธ Configuration Options

Customize Plip to fit your needs:

OptionTypeDefaultDescription
silentbooleanfalseSuppress all output
enableEmojisbooleanauto-detectShow emoji indicators
enableColorsbooleanauto-detectUse colorized output
enableSyntaxHighlightingbooleantrueHighlight object syntax
devOnlybooleanauto-detectOnly log in development
enabledLevelsLogLevel[]allArray of levels to enable
themePartial<PlipTheme>defaultCustom colors and emojis
const logger = createPlip({
  silent: false,
  enableEmojis: true,
  enableColors: true,
  enableSyntaxHighlighting: true,
  devOnly: false,
  enabledLevels: ['info', 'warn', 'error', 'success'],
  theme: {
    emojis: {
      info: "โ„น๏ธ",
      success: "โœ…"
    },
    colors: {
      info: customBlueColor,
      success: customGreenColor
    }
  }
});

๐Ÿ”— Fluent API (Method Chaining)

Build your perfect logger with our fluent, chainable API:

const logger = plip
  .withColors(true)           // Enable colors
  .withEmojis(true)           // Enable emojis
  .withSyntaxHighlighting(true) // Enable JSON highlighting
  .levels('info', 'error', 'success') // Only these levels
  .silent();                  // Make it silent

// Each method returns a new logger instance
const devLogger = plip.levels('debug', 'trace', 'verbose');
const prodLogger = plip.levels('warn', 'error').withEmojis(false);

Available Fluent Methods:

  • .withColors(enabled) - Toggle color output
  • .withEmojis(enabled) - Toggle emoji indicators
  • .withSyntaxHighlighting(enabled) - Toggle object highlighting
  • .withTheme(theme) - Apply custom theme
  • .withContext(context) - Add persistent context to all logs
  • .levels(...levels) - Filter enabled log levels
  • .silent() - Suppress all output

๐Ÿ’ก Examples

Basic Logging

import { plip } from '@ru-dr/plip';

// Simple messages
plip.info("Server starting on port 3000");
plip.success("Database connected successfully");

// With data
plip.info("New user registered:", { email: "user@example.com", id: 123 });
plip.error("Authentication failed:", { reason: "invalid_token", userId: 456 });

Context-Aware Logging

import { plip } from '@ru-dr/plip';

// Create context-aware loggers for different scopes
const authLogger = plip.withContext({ scope: "auth" });
const dbLogger = plip.withContext({ scope: "database", pool: "primary" });
const apiLogger = plip.withContext({ scope: "api", version: "v1" });

// All logs will include the context automatically
authLogger.info("User login attempt", { userId: 123, method: "oauth" });
// Output: ๐Ÿซง [INFO] User login attempt {"scope":"auth","userId":123,"method":"oauth"}

dbLogger.warn("Connection pool high usage", { activeConnections: 45 });
// Output: โš ๏ธ [WARN] Connection pool high usage {"scope":"database","pool":"primary","activeConnections":45}

// Context can be chained and extended
const requestLogger = apiLogger.withContext({ requestId: "req-789" });
requestLogger.error("Request processing failed", { endpoint: "/users" });
// Output: ๐Ÿ’ฅ [ERROR] Request processing failed {"scope":"api","version":"v1","requestId":"req-789","endpoint":"/users"}

Environment-Specific Logging

import { createPlip } from '@ru-dr/plip';

// Development logger - verbose and colorful
const devLogger = createPlip({
  enabledLevels: ['debug', 'trace', 'info', 'warn', 'error'],
  enableEmojis: true,
  enableColors: true
});

// Production logger - errors and warnings only
const prodLogger = createPlip({
  enabledLevels: ['warn', 'error'],
  enableEmojis: false,
  enableColors: false,
  enableSyntaxHighlighting: false
});

// Use based on environment
const logger = process.env.NODE_ENV === 'production' ? prodLogger : devLogger;

Custom Themes

import { createPlip, colors } from '@ru-dr/plip';

const logger = createPlip({
  theme: {
    emojis: {
      info: "๐Ÿ“˜",
      success: "โœ…", 
      warn: "โš ๏ธ",
      error: "โŒ"
    },
    colors: {
      info: colors.blue,
      success: colors.green,
      warn: colors.yellow,
      error: colors.red
    }
  }
});

Conditional Logging

import { createPlip } from '@ru-dr/plip';

// Only log in development
const debugLogger = createPlip({
  devOnly: true,
  enabledLevels: ['debug', 'trace']
});

// Log everything except in production
const logger = createPlip({
  enabledLevels: process.env.NODE_ENV === 'production' 
    ? ['warn', 'error'] 
    : ['debug', 'info', 'warn', 'error']
});

๐ŸŒ SSR vs CSR Logging

Plip provides optimized configurations for both Server-Side Rendering (SSR) and Client-Side Rendering (CSR) environments. CSR is the default for the best modern web development experience.

Quick Usage

import { plip, createSSRLogger, createCSRLogger } from '@ru-dr/plip';

// Default logger uses CSR configuration (with emojis & colors)
plip.info("Hello world!"); // ๐Ÿซง [INFO] Hello world!

// Explicit SSR logger (optimized for servers)
const serverLogger = createSSRLogger();
serverLogger.info("Server started", { port: 3000 }); 
// Output: [INFO] Server started {"port":3000}

// Explicit CSR logger (optimized for browsers) 
const clientLogger = createCSRLogger();
clientLogger.success("User logged in", { userId: 123 });
// Output: ๐ŸŽ‰ [SUCCESS] User logged in {"userId":123}

Key Differences

FeatureSSR (Server)CSR (Client)
EmojisโŒ Disabledโœ… Enabled
ColorsโŒ Disabledโœ… Enabled
Syntax HighlightingโŒ Disabledโœ… Enabled
Best ForAPIs, servers, logsBrowsers, debugging
Output StyleStructured, plainRich, visual

Framework Examples

// Next.js API Route (SSR)
import { createSSRLogger } from '@ru-dr/plip';
const serverLogger = createSSRLogger();

export default function handler(req, res) {
  serverLogger.info("API request", { method: req.method, url: req.url });
}

// React Component (CSR)  
import { createCSRLogger } from '@ru-dr/plip';
const clientLogger = createCSRLogger();

function App() {
  useEffect(() => {
    clientLogger.success("App loaded"); // ๐ŸŽ‰ [SUCCESS] App loaded
  }, []);
}

๐Ÿ“– Learn More: Check out our SSR vs CSR Guide for detailed examples and best practices.

import { createPlip } from '@ru-dr/plip';

// Only log in development const debugLogger = createPlip({ devOnly: true });

// Custom conditions const logger = createPlip({ enabledLevels: process.env.DEBUG ? 'debug', 'trace', 'info', 'warn', 'error' : 'warn', 'error' });

## ๐Ÿ› ๏ธ Advanced Usage

### TypeScript Integration
```typescript
import { PlipConfig, LogLevel, createPlip } from '@ru-dr/plip';

// Type-safe configuration
const config: PlipConfig = {
  enabledLevels: ['info', 'error'] as LogLevel[],
  enableColors: true,
  theme: {
    emojis: {
      info: "๐Ÿ’ก",
      error: "๐Ÿšจ"
    }
  }
};

const logger = createPlip(config);

Framework Integration

Express.js Middleware

import express from 'express';
import { createPlip } from '@ru-dr/plip';

const logger = createPlip();
const app = express();

app.use((req, res, next) => {
  logger.info(`${req.method} ${req.path}`, {
    ip: req.ip,
    userAgent: req.get('User-Agent')
  });
  next();
});

Error Handling

import { createPlip } from '@ru-dr/plip';

const logger = createPlip();

process.on('uncaughtException', (error) => {
  logger.error('Uncaught Exception:', {
    message: error.message,
    stack: error.stack,
    timestamp: new Date().toISOString()
  });
  process.exit(1);
});

try {
  // Your application logic
} catch (error) {
  logger.error('Application error:', error);
}

๐Ÿ“š Learn More

Explore our comprehensive documentation to master Plip Logger:

๐Ÿ“– Guides

๐Ÿ’ก Examples & Patterns

๐Ÿ”ง Integrations

๐Ÿ“‹ API Reference

๐Ÿ’ก Pro Tip: Start with Custom Loggers to learn context-aware logging with plip.withContext({ scope: "auth" })

๐Ÿค Contributing

We love contributions! Here's how you can help make Plip even better:

๐Ÿ› Found a Bug?

  • Check if it's already reported in Issues
  • If not, create a new issue with:
    • Clear description of the problem
    • Steps to reproduce
    • Expected vs actual behavior
    • Your environment details

๐Ÿ’ก Have an Idea?

๐Ÿ”ง Want to Code?

  1. Fork the repository
  2. Clone your fork: git clone https://github.com/YOUR_USERNAME/plip.git
  3. Create a branch: git checkout -b feature/amazing-feature
  4. Install dependencies: bun install
  5. Make your changes
  6. Test your changes: bun test
  7. Build the project: bun run build
  8. Commit your changes: git commit -m 'Add amazing feature'
  9. Push to your branch: git push origin feature/amazing-feature
  10. Open a Pull Request

๐Ÿ“ Development Setup

# Clone the repository
git clone https://github.com/ru-dr/plip.git
cd plip

# Install dependencies
bun install

# Run tests
bun test

# Run tests in watch mode
bun test --watch

# Build the project
bun run build

# Test your changes
bun run dev

๐Ÿงช Testing

We use Bun for testing. Please ensure:

  • All tests pass: bun test
  • Add tests for new features
  • Maintain or improve code coverage
  • Follow existing test patterns

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

TL;DR: You can use, modify, and distribute this project freely. Just keep the copyright notice! ๐Ÿ˜Š


Made with โค๏ธ by ru-dr

โญ Star this repo if you find it useful! โญ

Report Bug โ€ข Request Feature โ€ข Discussions