cloudflare-graylog-client
v1.0.10
Published
JavaScript client library for sending logs to Cloudflare Graylog Worker
Maintainers
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-clientUsage
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 WorkerdefaultFields(object, optional): Default fields to include in all log entries
Methods
Log Methods
log(level, message, fields): Send a log entry with the specified leveldebug(message, fields): Send a DEBUG level log entryinfo(message, fields): Send an INFO level log entrywarn(message, fields): Send a WARN level log entryerror(message, fields): Send an ERROR level log entryfatal(message, fields): Send a FATAL level log entry
Batch Methods
addToBatch(level, message, fields): Add a log entry to the batch queuedebugBatch(message, fields): Add a DEBUG level log entry to the batch queueinfoBatch(message, fields): Add an INFO level log entry to the batch queuewarnBatch(message, fields): Add a WARN level log entry to the batch queueerrorBatch(message, fields): Add an ERROR level log entry to the batch queuefatalBatch(message, fields): Add a FATAL level log entry to the batch queuesendBatch(): Send all logs in the batch queueclearBatch(): Clear all logs in the batch queue
Static Methods
GraylogClient.setGlobalDefaults({ host, environment, application }): Set global default valuesGraylogClient.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-clientBasic 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
