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

cloudflare-graylog-client

v1.0.10

Published

JavaScript client library for sending logs to Cloudflare Graylog Worker

Readme

Cloudflare Graylog Client

A JavaScript client library for sending logs to the Cloudflare Graylog Worker. This client supports all standard log levels (DEBUG, INFO, WARN, ERROR, FATAL) and provides both single and batch logging capabilities.

Installation

npm install cloudflare-graylog-client

Usage

Basic Usage

// Import the client library
const { GraylogClient, LOG_LEVELS } = require('cloudflare-graylog-client');

// Create a new client instance
const client = new GraylogClient('https://graylog-worker.thefamouscat.com/log', {
  // Default fields to include in all log entries
  host: 'your-app',
  environment: 'production',
  application: 'your-application-name'
});

// Send logs with different levels
client.debug('Debug message', { component: 'auth' });
client.info('User logged in', { userId: 123 });
client.warn('Rate limit approaching', { endpoint: '/api/data' });
client.error('Failed to process request', { errorCode: 500 });
client.fatal('Database connection lost', { dbServer: 'primary' });

// Using the generic log method
client.log(LOG_LEVELS.INFO, 'Custom log message', { custom: 'field' });

Batch Logging

// Add logs to the batch queue
client.debugBatch('Starting batch process', { processId: 789 });
client.infoBatch('Processing item 1', { itemId: 1 });
client.warnBatch('Slow processing detected', { duration: 1500 });
client.errorBatch('Failed to process item 3', { itemId: 3, reason: 'Invalid data' });

// Send all logs in the batch queue
client.sendBatch().then(response => {
  console.log('Batch logs sent:', response);
});

// Clear the batch queue without sending
client.clearBatch();

Setting Default Fields

You can set default fields at different levels:

// Global defaults (affect all instances)
const { setGlobalDefaults } = require('cloudflare-graylog-client');
setGlobalDefaults({
  environment: 'production',
  host: 'global-app-name'
});

// Class defaults (affect all new instances)
GraylogClient.setClassDefaults({
  environment: 'staging',
  application: 'class-app-name'
});

// Instance defaults (highest priority, set in constructor)
const client = new GraylogClient('https://graylog-worker.thefamouscat.com/log', {
  host: 'instance-host',
  application: 'instance-app'
});

API Reference

GraylogClient

Constructor

const client = new GraylogClient(baseUrl, defaultFields);
  • baseUrl (string): The base URL of the Cloudflare Graylog Worker
  • defaultFields (object, optional): Default fields to include in all log entries

Methods

Log Methods
  • log(level, message, fields): Send a log entry with the specified level
  • debug(message, fields): Send a DEBUG level log entry
  • info(message, fields): Send an INFO level log entry
  • warn(message, fields): Send a WARN level log entry
  • error(message, fields): Send an ERROR level log entry
  • fatal(message, fields): Send a FATAL level log entry
Batch Methods
  • addToBatch(level, message, fields): Add a log entry to the batch queue
  • debugBatch(message, fields): Add a DEBUG level log entry to the batch queue
  • infoBatch(message, fields): Add an INFO level log entry to the batch queue
  • warnBatch(message, fields): Add a WARN level log entry to the batch queue
  • errorBatch(message, fields): Add an ERROR level log entry to the batch queue
  • fatalBatch(message, fields): Add a FATAL level log entry to the batch queue
  • sendBatch(): Send all logs in the batch queue
  • clearBatch(): Clear all logs in the batch queue
Static Methods
  • GraylogClient.setGlobalDefaults({ host, environment, application }): Set global default values
  • GraylogClient.setClassDefaults({ host, environment, application }): Set class-level default values

LOG_LEVELS

Constants for log levels:

const LOG_LEVELS = {
  DEBUG: 'DEBUG',
  INFO: 'INFO',
  WARN: 'WARN',
  ERROR: 'ERROR',
  FATAL: 'FATAL'
};

setGlobalDefaults

setGlobalDefaults({ host, environment, application });

A utility function to set global default values for all GraylogClient instances.

React Integration

Installation in React Projects

npm install cloudflare-graylog-client
# or
yarn add cloudflare-graylog-client

Basic Usage in React

import React, { useEffect } from 'react';
import { GraylogClient, LOG_LEVELS } from 'cloudflare-graylog-client';

function App() {
  // Create client instance
  const client = new GraylogClient('https://graylog-worker.thefamouscat.com/log', {
    host: 'react-app',
    environment: process.env.NODE_ENV,
    application: 'my-react-app'
  });

  useEffect(() => {
    // Log when component mounts
    client.info('App component mounted', { timestamp: Date.now() });

    // Log when component unmounts
    return () => {
      client.info('App component unmounted', { timestamp: Date.now() });
    };
  }, []);

  const handleButtonClick = async () => {
    try {
      // Log user interaction
      await client.info('Button clicked', { action: 'button-click' });
    } catch (error) {
      console.error('Failed to log event:', error);
    }
  };

  return (
    <div>
      <h1>React App with Graylog Logging</h1>
      <button onClick={handleButtonClick}>Log Click Event</button>
    </div>
  );
}

export default App;

Creating a Logger Context

For larger applications, it's recommended to create a React context to provide the logger throughout your component tree:

// LoggerContext.js
import React, { createContext, useContext } from 'react';
import { GraylogClient, LOG_LEVELS } from 'cloudflare-graylog-client';

// Create the context
const LoggerContext = createContext(null);

// Create a provider component
export function LoggerProvider({ children, workerUrl, defaultFields }) {
  // Initialize the client
  const client = new GraylogClient(workerUrl, {
    environment: process.env.NODE_ENV,
    ...defaultFields
  });

  return (
    <LoggerContext.Provider value={client}>
      {children}
    </LoggerContext.Provider>
  );
}

// Custom hook to use the logger
export function useLogger() {
  const logger = useContext(LoggerContext);
  if (!logger) {
    throw new Error('useLogger must be used within a LoggerProvider');
  }
  return logger;
}

Then use it in your application:

// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { LoggerProvider } from './LoggerContext';

ReactDOM.render(
  <LoggerProvider
    workerUrl="https://graylog-worker.thefamouscat.com/log"
    defaultFields={{
      host: 'react-app',
      application: 'my-react-app'
    }}
  >
    <App />
  </LoggerProvider>,
  document.getElementById('root')
);

And in your components:

// SomeComponent.js
import React from 'react';
import { useLogger } from './LoggerContext';

function SomeComponent() {
  const logger = useLogger();

  const handleAction = async () => {
    try {
      // Log some action
      await logger.info('User performed an action', {
        component: 'SomeComponent',
        action: 'user-action'
      });
    } catch (error) {
      logger.error('Failed to complete action', {
        component: 'SomeComponent',
        error: error.message
      });
    }
  };

  return (
    <button onClick={handleAction}>Perform Action</button>
  );
}

Batch Logging in React

For operations that generate multiple logs, you can use batch logging to reduce network requests:

import React from 'react';
import { useLogger } from './LoggerContext';

function DataProcessor({ items }) {
  const logger = useLogger();

  const processItems = async () => {
    // Start batch logging
    logger.infoBatch('Starting batch processing', {
      itemCount: items.length
    });

    for (let i = 0; i < items.length; i++) {
      try {
        // Process item...
        logger.infoBatch(`Processed item ${i+1}`, {
          itemId: items[i].id,
          status: 'success'
        });
      } catch (error) {
        logger.errorBatch(`Failed to process item ${i+1}`, {
          itemId: items[i].id,
          error: error.message
        });
      }
    }

    // Send all logs at once
    try {
      await logger.sendBatch();
    } catch (error) {
      console.error('Failed to send batch logs:', error);
    }
  };

  return (
    <button onClick={processItems}>Process All Items</button>
  );
}

Error Boundary Integration

You can integrate the logger with React Error Boundaries to log component errors:

import React from 'react';
import { GraylogClient } from 'cloudflare-graylog-client';

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
    this.logger = new GraylogClient('https://graylog-worker.thefamouscat.com/log', {
      host: 'react-app',
      environment: process.env.NODE_ENV,
      application: 'my-react-app'
    });
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // Log the error to Graylog
    this.logger.error('React component error', {
      error: error.toString(),
      componentStack: errorInfo.componentStack,
      ...this.props.logContext
    }).catch(err => {
      console.error('Failed to log error to Graylog:', err);
    });
  }

  render() {
    if (this.state.hasError) {
      return this.props.fallback || <h1>Something went wrong.</h1>;
    }

    return this.props.children;
  }
}

export default ErrorBoundary;

License

MIT