npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@nlabs/arkhamjs-middleware-logger

v3.30.6

Published

Add console logging for ArkhamJS

Readme

@nlabs/arkhamjs-middleware-logger

Powerful Logging Middleware for ArkhamJS - Comprehensive action and state logging with customizable output formats, filtering, and performance insights.

npm version npm downloads Travis Issues TypeScript MIT license Chat

🚀 Features

  • 📝 Comprehensive Logging - Log actions, state changes, and performance metrics
  • 🎨 Customizable Output - Beautiful console formatting with colors and grouping
  • 🔍 Action Filtering - Filter specific actions or action types
  • ⚡ Performance Tracking - Measure action execution time and state update performance
  • 🌲 Tree-shakable - Only include what you need in production
  • 🔧 Configurable - Extensive options for customization
  • 📱 Browser Support - Works in Chrome, Firefox, Safari, and Edge

📦 Installation

npm install @nlabs/arkhamjs-middleware-logger

🎯 Quick Start

Basic Setup

import { Flux } from '@nlabs/arkhamjs';
import { Logger } from '@nlabs/arkhamjs-middleware-logger';

// Initialize Flux with logger middleware
Flux.init({
  name: 'my-app',
  stores: [UserStore, CartStore],
  middleware: [
    Logger() // Enable basic logging
  ]
});

// Dispatch actions and see beautiful logs
Flux.dispatch({ type: 'ADD_USER', user: { name: 'John' } });

Console Output

🚀 ArkhamJS Logger - Action Dispatched
┌─────────────────────────────────────────────────────────────┐
│ Action: ADD_USER                                            │
│ Timestamp: 2024-01-15T10:30:45.123Z                        │
│ Duration: 2.5ms                                             │
├─────────────────────────────────────────────────────────────┤
│ Payload:                                                    │
│ {                                                           │
│   "user": {                                                 │
│     "name": "John"                                          │
│   }                                                         │
│ }                                                           │
├─────────────────────────────────────────────────────────────┤
│ State Changes:                                              │
│ • user.list: [] → [{"name":"John"}]                        │
│ • user.count: 0 → 1                                         │
└─────────────────────────────────────────────────────────────┘

🔧 Configuration Options

Basic Configuration

import { Logger } from '@nlabs/arkhamjs-middleware-logger';

Flux.init({
  name: 'my-app',
  stores: [UserStore],
  middleware: [
    Logger({
      // Enable/disable features
      logActions: true,        // Log dispatched actions
      logState: true,          // Log state changes
      logPerformance: true,    // Log performance metrics

      // Filtering options
      filterActions: ['ADD_USER', 'UPDATE_USER'], // Only log specific actions
      excludeActions: ['TICK', 'MOUSE_MOVE'],     // Exclude specific actions

      // Output options
      groupActions: true,      // Group related logs
      showTimestamp: true,     // Show timestamps
      showDuration: true,      // Show action duration

      // Styling
      colors: true,            // Enable colored output
      compact: false,          // Compact mode for less verbose output

      // Performance thresholds
      slowActionThreshold: 100, // Warn for actions taking >100ms

      // Custom formatting
      formatAction: (action) => `🎯 ${action.type}`,
      formatState: (path, oldValue, newValue) =>
        `${path}: ${JSON.stringify(oldValue)} → ${JSON.stringify(newValue)}`
    })
  ]
});

Production Configuration

import { Logger } from '@nlabs/arkhamjs-middleware-logger';

const isDevelopment = process.env.NODE_ENV === 'development';

Flux.init({
  name: 'my-app',
  stores: [UserStore],
  middleware: [
    // Only enable logging in development
    ...(isDevelopment ? [Logger()] : [])
  ]
});

Advanced Filtering

import { Logger } from '@nlabs/arkhamjs-middleware-logger';

interface UserAction {
  type: string;
  user?: { premium?: boolean };
}

Flux.init({
  name: 'my-app',
  stores: [UserStore],
  middleware: [
    Logger({
      // Filter by action type pattern
      filterActions: (action: UserAction) => action.type.startsWith('USER_'),

      // Filter by action payload
      filterActions: (action: UserAction) => action.user && action.user.premium,

      // Filter state changes
      filterState: (path: string, oldValue: any, newValue: any): boolean => {
        // Only log significant changes
        return JSON.stringify(oldValue) !== JSON.stringify(newValue);
      },

      // Custom action grouping
      groupBy: (action: UserAction): string => {
        if (action.type.startsWith('USER_')) return 'User Actions';
        if (action.type.startsWith('CART_')) return 'Cart Actions';
        return 'Other Actions';
      }
    })
  ]
});

🎨 Custom Logging Formats

Custom Action Formatter

import { Logger } from '@nlabs/arkhamjs-middleware-logger';

interface Action {
  type: string;
}

Flux.init({
  name: 'my-app',
  stores: [UserStore],
  middleware: [
    Logger({
      formatAction: (action: Action): string => {
        const icons: Record<string, string> = {
          'ADD_USER': '👤',
          'UPDATE_USER': '✏️',
          'DELETE_USER': '🗑️',
          'CART_ADD': '🛒',
          'CART_REMOVE': '❌'
        };

        const icon = icons[action.type] || '📝';
        return `${icon} ${action.type}`;
      }
    })
  ]
});

Custom State Formatter

import { Logger } from '@nlabs/arkhamjs-middleware-logger';

Flux.init({
  name: 'my-app',
  stores: [UserStore],
  middleware: [
    Logger({
      formatState: (path: string, oldValue: any, newValue: any): string => {
        const formatValue = (value: any): string => {
          if (Array.isArray(value)) return `[${value.length} items]`;
          if (typeof value === 'object' && value !== null) return '{...}';
          return String(value);
        };

        return `${path}: ${formatValue(oldValue)} → ${formatValue(newValue)}`;
      }
    })
  ]
});

🎯 Advanced Usage

Performance Monitoring

import { Logger } from '@nlabs/arkhamjs-middleware-logger';

Flux.init({
  name: 'my-app',
  stores: [UserStore],
  middleware: [
    Logger({
      logPerformance: true,
      slowActionThreshold: 50, // Warn for actions >50ms

      // Custom performance formatter
      formatPerformance: (duration: number, action: any): string => {
        if (duration > 100) return `🐌 Slow action: ${action.type} (${duration}ms)`;
        if (duration > 50) return `⚠️ Medium action: ${action.type} (${duration}ms)`;
        return `⚡ Fast action: ${action.type} (${duration}ms)`;
      }
    })
  ]
});

Conditional Logging

import { Logger } from '@nlabs/arkhamjs-middleware-logger';

const createLogger = (options: any) => {
  const isDevelopment = process.env.NODE_ENV === 'development';
  const isTest = process.env.NODE_ENV === 'test';

  if (isTest) {
    return Logger({
      logActions: false,
      logState: false,
      logPerformance: false
    });
  }

  if (isDevelopment) {
    return Logger({
      ...options,
      colors: true,
      groupActions: true
    });
  }

  return Logger({
    ...options,
    colors: false,
    groupActions: false,
    compact: true
  });
};

Flux.init({
  name: 'my-app',
  stores: [UserStore],
  middleware: [createLogger()]
});

Custom Log Handlers

import { Logger } from '@nlabs/arkhamjs-middleware-logger';

Flux.init({
  name: 'my-app',
  stores: [UserStore],
  middleware: [
    Logger({
      // Custom log handler for external logging services
      onActionLogged: (action: any, duration: number) => {
        // Send to external logging service
        analytics.track('action_dispatched', {
          action: action.type,
          duration,
          timestamp: Date.now()
        });
      },

      onStateChanged: (path: string, oldValue: any, newValue: any) => {
        // Track state changes
        analytics.track('state_changed', {
          path,
          oldValue,
          newValue
        });
      }
    })
  ]
});

🔧 API Reference

Logger Options

interface LoggerOptions {
  // Basic settings
  logActions?: boolean;
  logState?: boolean;
  logPerformance?: boolean;

  // Filtering
  filterActions?: string[] | ((action: any) => boolean);
  excludeActions?: string[] | ((action: any) => boolean);
  filterState?: (path: string, oldValue: any, newValue: any) => boolean;

  // Output formatting
  groupActions?: boolean;
  showTimestamp?: boolean;
  showDuration?: boolean;
  colors?: boolean;
  compact?: boolean;

  // Performance
  slowActionThreshold?: number;

  // Custom formatters
  formatAction?: (action: any) => string;
  formatState?: (path: string, oldValue: any, newValue: any) => string;
  formatPerformance?: (duration: number, action: any) => string;

  // Custom handlers
  onActionLogged?: (action: any, duration: number) => void;
  onStateChanged?: (path: string, oldValue: any, newValue: any) => void;

  // Grouping
  groupBy?: (action: any) => string;
}

🎯 Use Cases

Development Debugging

import { Logger } from '@nlabs/arkhamjs-middleware-logger';

// Development setup with full logging
const devLogger = Logger({
  logActions: true,
  logState: true,
  logPerformance: true,
  colors: true,
  groupActions: true,
  showTimestamp: true,
  showDuration: true
});

Flux.init({
  name: 'my-app',
  stores: [UserStore],
  middleware: [devLogger]
});

Production Monitoring

import { Logger } from '@nlabs/arkhamjs-middleware-logger';

// Production setup with minimal logging
const prodLogger = Logger({
  logActions: false,
  logState: false,
  logPerformance: true,
  colors: false,
  compact: true,
  slowActionThreshold: 100,

  onActionLogged: (action, duration) => {
    if (duration > 100) {
      // Send slow action alerts
      errorReporting.captureMessage(`Slow action: ${action.type}`, {
        level: 'warning',
        extra: { action, duration }
      });
    }
  }
});

Flux.init({
  name: 'my-app',
  stores: [UserStore],
  middleware: [prodLogger]
});

Testing Setup

import { Logger } from '@nlabs/arkhamjs-middleware-logger';

// Testing setup with no logging
const testLogger = Logger({
  logActions: false,
  logState: false,
  logPerformance: false
});

Flux.init({
  name: 'test-app',
  stores: [UserStore],
  middleware: [testLogger]
});

🔗 Related Packages

📚 Documentation

🤝 Community & Support

📄 License

MIT License - see LICENSE file for details.


Start debugging your ArkhamJS applications with powerful logging today! 🚀