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 🙏

© 2026 – Pkg Stats / Ryan Hefner

log-system-sdk

v1.0.3

Published

Log System SDK for Next.js applications - Server-side and Client-side logging made easy

Readme

log-system-sdk

Log System SDK for Next.js applications - Server-side and Client-side logging made easy.

Features

  • 🌐 Universal: Works on both server-side (API Routes, Server Actions) and client-side
  • 📦 Batching: Automatic batch sending for better performance
  • 🔄 Auto-flush: Configurable flush interval
  • 🪝 React Hooks: Easy integration with React applications
  • 🎯 TypeScript: Full TypeScript support
  • 🔒 API Key Auth: Secure authentication via API Key
  • 📊 Log Levels: DEBUG, INFO, WARN, ERROR, FATAL
  • 🔍 Auto Error Tracking: Automatic error and unhandled promise rejection capture
  • Server/Client Split: Optimized bundles for server and client separately

Installation

npm install log-system-sdk --registry https://registry.npmjs.org/
# or
yarn add log-system-sdk --registry https://registry.npmjs.org/
# or
pnpm add log-system-sdk --registry https://registry.npmjs.org/

Quick Start

1. Get API Credentials

  1. Log in to Log System admin panel
  2. Go to Applications → Create or select an application
  3. Generate an API Key

2. Environment Variables

Add to your .env.local or .env:

# Log System API URL
NEXT_PUBLIC_LOG_API_URL=http://localhost:3001/api

# API Key (from admin panel)
LOG_API_KEY=sk_your_api_key_here

# App ID (from admin panel)
LOG_APP_ID=your_app_id

# Environment (optional, auto-detected)
LOG_ENV=production

Server-side Usage (API Routes / Server Actions)

Import from log-system-sdk/client to avoid React-related issues in Node.js environment.

Method 1: Direct Logger Instance

// src/lib/logger.ts
import { createLogger } from 'log-system-sdk/client';

export const logger = createLogger({
  apiUrl: process.env.NEXT_PUBLIC_LOG_API_URL!,
  apiKey: process.env.LOG_API_KEY!,
  appId: process.env.LOG_APP_ID!,
  environment: process.env.LOG_ENV || 'server',
  serviceName: 'my-api',
  level: process.env.NODE_ENV === 'production' ? 'WARN' : 'DEBUG',
});
// src/app/api/users/route.ts
import { logger } from '@/lib/logger';

export async function GET() {
  try {
    const users = await fetchUsers();

    logger.info({
      message: 'Users fetched successfully',
      context: { count: users.length },
    });

    return Response.json(users);
  } catch (error) {
    logger.error({
      message: 'Failed to fetch users',
      extra: {
        error: error.message,
        stack: error.stack,
      },
    });

    return Response.json({ error: 'Failed to fetch users' }, { status: 500 });
  }
}

Method 2: Server Actions

// src/app/actions.ts
'use server';

import { createLogger } from 'log-system-sdk/client';

const logger = createLogger({
  apiUrl: process.env.NEXT_PUBLIC_LOG_API_URL!,
  apiKey: process.env.LOG_API_KEY!,
  appId: process.env.LOG_APP_ID!,
  environment: 'server',
});

export async function submitOrder(data: OrderData) {
  try {
    const result = await processOrder(data);

    logger.info({
      message: 'Order submitted successfully',
      context: { orderId: result.orderId, amount: data.amount },
    });

    return { success: true, orderId: result.orderId };
  } catch (error) {
    logger.error({
      message: 'Order submission failed',
      extra: { error: error.message, data },
    });

    return { success: false, error: error.message };
  }
}

Client-side Usage (React)

Import from log-system-sdk/react.

Method 1: Provider + Hook

// src/app/providers.tsx
'use client';

import { LogSystemProvider } from 'log-system-sdk/react';

export function Providers({ children }: { children: React.ReactNode }) {
  return (
    <LogSystemProvider
      options={{
        apiUrl: process.env.NEXT_PUBLIC_LOG_API_URL!,
        apiKey: process.env.LOG_API_KEY!,
        appId: process.env.LOG_APP_ID!,
        environment: 'client',
        serviceName: 'my-app',
        level: 'INFO',
        batchSize: 10,
        flushInterval: 5000,
      }}
    >
      {children}
    </LogSystemProvider>
  );
}
// src/app/layout.tsx
import { Providers } from './providers';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html>
      <body>
        <Providers>{children}</Providers>
      </body>
    </html>
  );
}
// src/components/UserList.tsx
'use client';

import { useLogger } from 'log-system-sdk/react';

export function UserList() {
  const { info, error } = useLogger();

  const handleFetch = async () => {
    try {
      const users = await fetchUsers();
      info('Users loaded', { context: { count: users.length } });
    } catch (err) {
      error('Failed to load users', { extra: { error: err.message } });
    }
  };

  return <button onClick={handleFetch}>Load Users</button>;
}

Method 2: Error Boundary

// src/app/error.tsx
'use client';

import { LogErrorBoundary } from 'log-system-sdk/react';

export default function Error({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  return (
    <LogErrorBoundary
      fallback={
        <div>
          <h2>Something went wrong!</h2>
          <button onClick={() => reset()}>Try again</button>
        </div>
      }
    >
      <div>
        <h2>{error.message}</h2>
        <button onClick={() => reset()}>Try again</button>
      </div>
    </LogErrorBoundary>
  );
}

Method 3: Auto Error Tracking

Wrap your app with LogErrorBoundary to automatically capture uncaught errors:

// src/app/providers.tsx
'use client';

import { LogSystemProvider, LogErrorBoundary } from 'log-system-sdk/react';

export function Providers({ children }: { children: React.ReactNode }) {
  return (
    <LogSystemProvider
      options={{
        apiUrl: process.env.NEXT_PUBLIC_LOG_API_URL!,
        apiKey: process.env.LOG_API_KEY!,
        appId: process.env.LOG_APP_ID!,
      }}
    >
      <LogErrorBoundary>
        {children}
      </LogErrorBoundary>
    </LogSystemProvider>
  );
}

Method 4: HOC for Component Tracking

import { withLogger } from 'log-system-sdk/react';

function UserProfile({ userId }: { userId: string }) {
  return <div>User: {userId}</div>;
}

// Automatically log mount/unmount
export const TrackedUserProfile = withLogger(UserProfile, (props) => ({
  serviceName: 'user-profile',
  context: { userId: props.userId },
}));

API Reference

createLogger(options) (Server-side)

Creates a server-side logger instance.

Options:

| Option | Type | Required | Default | Description | |--------|------|----------|---------|-------------| | apiUrl | string | Yes | - | Log System API URL | | apiKey | string | Yes | - | API Key from admin panel | | appId | string | Yes | - | Application ID | | environment | string | No | 'server' | Environment name | | serviceName | string | No | 'app' | Service name | | logType | string | No | 'application' | Log type | | level | string | No | 'INFO' | Minimum log level | | batchSize | number | No | 10 | Number of logs to batch | | flushInterval | number | No | 5000 | Flush interval (ms) | | enableConsole | boolean | No | false | Override console methods | | requestTimeout | number | No | 5000 | Request timeout (ms) |

Logger Methods (Server-side)

  • logger.debug(params) - Log DEBUG level
  • logger.info(params) - Log INFO level
  • logger.warn(params) - Log WARN level
  • logger.error(params) - Log ERROR level
  • logger.fatal(params) - Log FATAL level
  • logger.log(entry) - Log with custom level
  • logger.flush() - Manually flush buffer (non-blocking)
  • logger.flushImmediate() - Immediately flush buffer
  • logger.flushBlocking() - Flush and wait for completion
  • logger.logWithFlush(params) - Log and immediately flush
  • logger.isBlocked() - Check if currently sending
  • logger.getBufferSize() - Get pending log count
  • logger.destroy() - Cleanup logger

Log Parameters:

{
  message: string;           // Required
  level?: LogLevel;         // Optional (overrides method)
  serviceName?: string;     // Override default
  environment?: string;     // Override default
  traceId?: string;         // For distributed tracing
  requestId?: string;       // Request ID
  userId?: string;          // User ID
  bizId?: string;           // Business ID
  tags?: string[];          // Tags for categorization
  context?: object;         // Contextual data
  extra?: object;           // Extra metadata
}

React Components

<LogSystemProvider>

Provides logger context to React components.

<LogSystemProvider
  options={{
    apiUrl: 'http://localhost:3001/api',
    apiKey: 'sk_xxx',
    appId: 'app_xxx',
  }}
>
  {children}
</LogSystemProvider>

useLogger() Hook

const { log, debug, info, warn, error, fatal } = useLogger();

info('Message', { context: { key: 'value' } });

<LogErrorBoundary>

Catches React component errors and logs them automatically.

withLogger(Component, getEntry)

HOC to track component mount/unmount.


Best Practices

1. Use Environment-Specific Log Levels

const logger = createLogger({
  // ...
  level: process.env.NODE_ENV === 'production' ? 'WARN' : 'DEBUG',
});

2. Add Tracing IDs

// In API route
const traceId = crypto.randomUUID();

// Pass to logger
logger.info({
  message: 'Processing request',
  traceId,
  context: { path: '/api/users' },
});

// Pass to downstream services
await fetch('/api/orders', {
  headers: { 'X-Trace-ID': traceId },
});

3. Sanitize Sensitive Data

logger.info({
  message: 'User action',
  context: {
    userId: user.id,
    // Never log passwords, tokens, or PII directly
    // Instead log flags or hashes
    hasPassword: true,
    emailHash: hash(user.email),
  },
});

4. Use batchSize for Performance

For high-traffic applications, increase batch size and flush interval:

const logger = createLogger({
  // ...
  batchSize: 50,
  flushInterval: 10000,
});

5. Immediate Flush for Critical Operations

For critical operations that need guaranteed logging:

// Method 1: Log and flush in one call
await logger.logWithFlush({
  message: 'Payment completed',
  level: 'INFO',
  context: { orderId: order.id },
});

// Method 2: Flush immediately after logging
logger.error({ message: 'Payment failed', extra: { error } });
await logger.flushImmediate();

TypeScript

The SDK is written in TypeScript and provides full type definitions. Import types when needed:

import { Logger, LogEntry, LogLevel, LogType, FlushResult } from 'log-system-sdk/client';

License

MIT