Skip to content
Β 
Β 

Repository files navigation

πŸ“ Zario

⚑ The Ultimate Minimal Logging Solution for Node.js

npm version license downloads bundle size


Fast β€’ Lightweight β€’ Zero Dependencies β€’ TypeScript Native


πŸ“– Documentation Β· ⚑ Quick Start Β· ✨ Features Β· πŸ’¬ Community


separator


✨ Highlights

  • ⚑ Super lightweight β€” minimal footprint, fast execution
  • 🎯 Simple API β€” intuitive methods like info(), warn(), etc.
  • 🎨 Custom formatting β€” plain text or JSON
  • ⏱️ Automatic timestamps
  • πŸ“ Multiple transports
  • 🧩 Child loggers for modular logging
  • 🧡 Async writes β€” keeps Node responsive
  • πŸ”’ Small, safe, dependency-light design
  • 🌈 Custom log levels with color support

πŸ“¦ Installation

npm install zario
πŸ“‹ Other Package Managers
# Using Yarn
yarn add zario

# Using pnpm
pnpm add zario

# Using bun
bun add zario

πŸš€ Quick Start

import { Logger, ConsoleTransport } from "zario";

const logger = new Logger({
  level: "info",
  colorize: true,
  transports: [new ConsoleTransport()],
  prefix: "[MyApp]",
});
// Start logging
logger.info("πŸš€ Server started on port 3000");
logger.warn("⚠️ High memory usage detected");
logger.error("❌ Database connection failed", { code: 500 });

Output:

[MyApp] INFO  πŸš€ Server started on port 3000
[MyApp] WARN  ⚠️ High memory usage detected
[MyApp] ERROR ❌ Database connection failed { code: 500 }

πŸ“ Log Levels

Level Method Use Case Example
πŸ” DEBUG logger.debug() Detailed debugging info Variable values, function calls
ℹ️ INFO logger.info() General information Server started, user logged in
⚠️ WARN logger.warn() Warning messages Deprecated API usage, high load
❌ ERROR logger.error() Error conditions Failed requests, exceptions
πŸ’€ FATAL logger.fatal() Critical failures System crash, data corruption
πŸ”‡ SILENT logger.silent() Suppresses logging Disable logging for specific scenarios
πŸ˜‘ BORING logger.boring() Low priority info

Example:

logger.debug("Debugging user authentication flow");
logger.info("User successfully authenticated");
logger.warn("Session about to expire");
logger.error("Failed to save user data");
logger.fatal("Database connection lost");

🌱 Child Loggers

Perfect when you want separate logs per module or request:

const main = new Logger({ prefix: "[APP]" });
const db = main.createChild({ prefix: "[DB]" });

main.info("App initialized");
db.error("Connection timeout");

Output:

[APP] [INFO] App initialized
[APP][DB] [ERROR] Connection timeout

⏱️ Performance Timer

Built-in timer utility for measuring execution time:

const logger = new Logger({ prefix: "[PERFORMANCE]" });

// Create a timer
const timer = logger.startTimer("Database query");

// Simulate some work
await databaseQuery();

// End the timer - logs the duration automatically
timer.end(); // Output: [PERFORMANCE] [INFO] Database query took 150ms

The timer is idempotent - calling end() multiple times will only log the duration once.

🌍 Environment Detection & Auto-Config

Auto-configure based on NODE_ENV:

// Development: colorized, debug level, console transport, sync mode
process.env.NODE_ENV = 'development';
const devLogger = new Logger();

// Production: JSON, warn level, file transport, async mode
process.env.NODE_ENV = 'production';
const prodLogger = new Logger();

Auto-configuration behavior:

  • Development: level: 'debug', colorize: true, json: false, asyncMode: false, transports: [new ConsoleTransport()]
  • Production: level: 'warn', colorize: false, json: true, asyncMode: true, transports: [new ConsoleTransport(), new FileTransport({path: './logs/app.log'})]

All settings can be overridden with explicit options.


separator


✨ Features

🎯 Core Features

πŸš€ High Performance

  • Async logging for non-blocking I/O
  • Optimized for high-throughput apps
  • Minimal overhead in production
  • Fast JSON serialization

🎨 Developer Experience

  • Beautiful colorized output
  • TypeScript definitions
  • Intuitive API
  • Easy configuration

πŸ”§ Flexible Configuration

  • Multiple transports
  • Custom formatters
  • Log level filtering
  • Metadata support
  • Custom log levels and colors

πŸ“Š Transport Options

πŸ“Ί Console Transport
const logger = new Logger({
  transports: [
    new ConsoleTransport({ colorize: true })
  ]
});

Perfect for development and debugging.

πŸ“ File Transport
const logger = new Logger({
  transports: [
    new FileTransport({
      path: './logs/app.log',
      maxSize: 10485760, // 10MB in bytes
      maxFiles: 5
    })
  ]
});

Ideal for production logging and auditing.

🌐 HTTP Transport
const logger = new Logger({
  transports: [
    new HttpTransport({
      url: 'https://api.example.com/logs',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer your-token-here'
      },
      timeout: 10000,  // Request timeout in ms
      retries: 3       // Number of retry attempts
    })
  ]
});

Send logs to a remote HTTP endpoint with retry logic and timeout handling.

πŸ”Œ Custom Transport
const logger = new Logger({
  transports: [{
    type: 'custom',
    instance: {
      write: (log, formatter) => {
        // Send to external service
        sendToDatadog(log);
      }
    }
  }]
});

Integrate with any logging service.


🎭 Advanced Features

🏷️ Metadata Support

logger.info('User login', {
  userId: 12345,
  ip: '192.168.1.1',
  timestamp: new Date()
});

πŸ” Error Tracking

try {
  riskyOperation();
} catch (error) {
  logger.error('Operation failed', error);
}

🎯 Prefix/Namespace

const logger = new Logger({
  prefix: '[MyService]'
});

βš™οΈ Environment Aware

const logger = new Logger({
  level: process.env.LOG_LEVEL || 'info'
});

🎨 Advanced Usage: Custom Levels & Colors

Define Custom Log Levels

Create your own log levels with specific priorities and colors for more granular logging.

import { Logger } from 'zario';

const logger = new Logger({
  level: 'info',
  customLevels: {
    'success': 6,      // Higher priority than error (5).
    'verbose': 1,      // Lower priority than debug (2).
    'critical': 7,     // Highest priority.
  },
  customColors: {
    'success': 'green',
    'verbose': 'cyan',
    'critical': 'brightRed',
  },
  transports: [
    new ConsoleTransport()
  ]
});

// Using custom levels.
logger.logWithLevel('success', 'This is a success message in green!');
logger.logWithLevel('verbose', 'This is a verbose message in cyan');
logger.logWithLevel('critical', 'This is a critical message in bright red');
Log Level Filtering

Set the logger's level to a custom level to filter messages based on their priority.

// Only logs levels with priority >= 7 (critical in this case).
const highLevelLogger = new Logger({
  level: 'critical', 
  customLevels: {
    'success': 6,
    'verbose': 1,
    'critical': 7,
  },
  transports: [
    new ConsoleTransport()
  ]
});

// This will NOT be shown (verbose has priority 1 < critical threshold 7).
highLevelLogger.logWithLevel('verbose', 'This will not appear');

// This WILL be shown (critical has priority 7 >= threshold 7).
highLevelLogger.logWithLevel('critical', 'This critical message appears');
Child Logger with Custom Levels

Child loggers inherit custom levels and colors from their parent, and can also have their own.

const parentLogger = new Logger({
  level: 'info',
  customLevels: {
    'parent_custom': 6,
  },
  customColors: {
    'parent_custom': 'blue',
  },
  transports: [
    new ConsoleTransport()
  ]
});

// Child will inherit parent's custom levels and can add its own.
const childLogger = parentLogger.createChild({
  customLevels: {
    'child_custom': 7,  // Add child-specific level.
  },
  customColors: {
    'child_custom': 'red',
  }
});

childLogger.logWithLevel('parent_custom', 'Inherited from parent');
childLogger.logWithLevel('child_custom', 'Defined in child');

separator


πŸ’‘ Use Cases

🌐 Web Applications

import express from 'express';
import Logger from 'zario';

const app = express();
const logger = new Logger({ prefix: '[API]' });

app.use((req, res, next) => {
  const reqLogger = logger.createChild({ prefix: `[${req.method} ${req.url}]` });
  reqLogger.info("Incoming request");
  next();
});

app.get("/", (req, res) => {
  res.send("Hello!");
});

app.listen(3000, () => {
  logger.info("API running on port 3000");
});

Perfect for:

  • Express.js applications
  • Fastify servers
  • Koa.js projects
  • REST APIs

⚑ Serverless Functions

import Logger from 'zario';

const logger = new Logger({
  level: 'info',
  transports: [new ConsoleTransport()]
});

export async function handler(event) {
  logger.info('Lambda invoked', { 
    requestId: event.requestId 
  });
  
  try {
    const result = await processEvent(event);
    logger.info('Processing complete');
    return result;
  } catch (error) {
    logger.error('Processing failed', error);
    throw error;
  }
}

Perfect for:

  • AWS Lambda
  • Vercel Functions
  • Netlify Functions
  • Cloudflare Workers

πŸ”§ CLI Applications

import Logger from 'zario';

const logger = new Logger({
  colorize: true,
  prefix: '[CLI]'
});

async function buildProject() {
  logger.info('Starting build process...');
  
  logger.debug('Reading config file');
  logger.info('Compiling TypeScript...');
  logger.info('Bundling assets...');
  
  logger.info('βœ… Build completed successfully!');
}

Perfect for:

  • Command-line tools
  • Build scripts
  • DevOps automation
  • System utilities

πŸ—οΈ Microservices

import Logger from 'zario';

// Create service-specific loggers
const userService = new Logger({
  prefix: '[UserService]'
});

const paymentService = new Logger({
  prefix: '[PaymentService]'
});

const orderService = new Logger({
  prefix: '[OrderService]'
});

// Use in distributed system
userService.info('User created', { id: 123 });
paymentService.info('Payment processed');
orderService.info('Order placed');

Perfect for:

  • Distributed systems
  • Message queues
  • Event-driven architecture
  • Container deployments

separator


🧩 Log Formats

Plain Text (default)

[2025-01-23 10:22:20] [INFO] User logged in

JSON Format

const logger = new Logger({ json: true });

Output:

{
  "timestamp": "2025-01-23T10:22:20Z",
  "level": "info",
  "message": "User logged in"
}

πŸ“ Recommended Project Structure

/src
  /logs
  /modules
    database.js
    users.js
logger.js
server.js

Example logger.js:

import Logger from "zario";

export const logger = new Logger({
  prefix: "[API]",
  transports: [new ConsoleTransport()],
});

πŸ§ͺ Testing Example

import Logger from "zario";

describe("Logger", () => {
  it("should log messages", () => {
    const logger = new Logger({ timestamp: false });
    logger.info("Testing logger");
  });
});

πŸ“š Full Options Reference

Option Type Description
level string Log level threshold
json boolean Output in JSON format
timestamp boolean Include timestamps
prefix string Prepended label
transports array Where logs are written (with transport-specific options like path, maxSize, maxFiles for file transport)
asyncMode boolean Whether to enable asynchronous logging mode for better performance under heavy logging
customLevels object Define custom log levels and their priorities
customColors object Assign colors to custom log levels
createChild() method Creates a scoped logger
setAsyncMode() method Toggles asynchronous logging mode at runtime
startTimer() method Creates a timer to measure execution duration

separator


πŸ“– Documentation

πŸ“š Resource πŸ“ Description πŸ”— Link
πŸ“˜ Usage Guide Complete guide with examples and best practices Read β†’
βš™οΈ Configuration All configuration options explained in detail Read β†’
🎯 API Reference Full API documentation with type definitions Read β†’
πŸ’Ό Use Cases Real-world examples and implementation patterns Read β†’
πŸš€ Migration Guide Migrate from other logging libraries Read β†’
πŸ”Œ Custom Transports Build your own transport implementations Read β†’

separator


πŸ—ΊοΈ Roadmap

🎯 Coming Soon

  • βœ… Console & File transports
  • βœ… Child loggers
  • βœ… TypeScript support
  • βœ… Log rotation
  • βœ… HTTP transport
  • πŸ”„ Syslog support

πŸš€ Future Plans

  • πŸ“Š Performance metrics
  • πŸ” Advanced filtering
  • πŸ“± React Native support
  • 🌈 Custom themes
  • πŸ” Log encryption
  • πŸ“ˆ Analytics dashboard

πŸ’‘ Under Consideration

  • WebSocket transport
  • MongoDB transport
  • Redis transport
  • Elasticsearch integration
  • Structured logging
  • Log aggregation

πŸ—³οΈ Vote for features: Have a feature request? Open an issue and let us know!


separator


🀝 Contributing

We ❀️ contributions! Whether it's bug reports, feature requests, or code contributions.

πŸ› Report Bugs
Found a bug?
Report it β†’
πŸ’‘ Request Features
Have an idea?
Suggest it β†’
πŸ“– Improve Docs
Fix a typo?
Submit PR β†’
πŸ’¬ Join Discussion
Questions?
Discuss β†’

πŸ› οΈ Development Setup

Follow these steps if you want to work on the project locally:

# Clone the repository
git clone https://github.com/Dev-Dami/zario.git

# Navigate into the project
cd zario

# Install dependencies
npm install

# Run tests
npm test

# Build the project
npm run build

πŸ’¬ Community

GitHub Stars GitHub Forks GitHub Issues

Join our growing community!

πŸ’¬ Discussions β€’ πŸ› Issues β€’ πŸ“’ Changelog


separator


πŸ“„ License

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

MIT License - feel free to use this in your projects!

Made with ❀️ by developers, for developers


🌟 Show Your Support

If Zario made your logging easier, consider:

⭐ Star this repository to show your support

🐦 Share on Twitter to spread the word

β˜• Buy us a coffee to fuel development

Star History Chart


⬆ Back to Top

About

A minimal, fast logging library for Node.js.

Resources

Contributing

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages