client.ingest
v1.0.0
Published
JavaScript client for sending logs to service.ingest via Socket.IO
Readme
client.ingest
A JavaScript/TypeScript client for sending logs to service.ingest via Socket.IO. Works in both browser (React) and Node.js environments.
Installation
npm install client.ingest socket.io-clientQuick Start
import { IngestClient } from 'client.ingest';
// Create a client instance
const client = new IngestClient({
url: 'http://localhost:3000'
});
// Send logs
await client.info('Application started');
await client.error('Something went wrong', { errorCode: 500 });Usage
Basic Usage
import { IngestClient } from 'client.ingest';
const client = new IngestClient({
url: 'http://localhost:3000'
});
// Wait for connection
await client.connect();
// Send different log levels
await client.debug('Debug message');
await client.info('Info message');
await client.warn('Warning message');
await client.error('Error message');
await client.fatal('Fatal message');
// With metadata
await client.info('User logged in', {
userId: '123',
email: '[email protected]'
});React Usage
import { useEffect, useRef } from 'react';
import { IngestClient } from 'client.ingest';
function App() {
const clientRef = useRef<IngestClient | null>(null);
useEffect(() => {
// Initialize client
const client = new IngestClient({
url: 'http://localhost:3000'
});
clientRef.current = client;
// Set up event handlers
client.on('connect', () => {
console.log('Connected to log server');
});
client.on('disconnect', (reason) => {
console.log('Disconnected:', reason);
});
client.on('error', (error) => {
console.error('Connection error:', error);
});
// Clean up on unmount
return () => {
client.destroy();
};
}, []);
const handleClick = async () => {
if (clientRef.current?.connected) {
await clientRef.current.info('Button clicked', {
timestamp: Date.now()
});
}
};
return <button onClick={handleClick}>Click me</button>;
}React Hook Example
import { useEffect, useState, useCallback, useRef } from 'react';
import { IngestClient, LogLevel, LogResult } from 'client.ingest';
export function useIngestLogger(url: string) {
const clientRef = useRef<IngestClient | null>(null);
const [connected, setConnected] = useState(false);
useEffect(() => {
const client = new IngestClient({ url });
clientRef.current = client;
client.on('connect', () => setConnected(true));
client.on('disconnect', () => setConnected(false));
return () => {
client.destroy();
};
}, [url]);
const log = useCallback(
async (level: LogLevel, message: string, meta?: Record<string, any>) => {
if (clientRef.current?.connected) {
return clientRef.current.log(level, message, meta);
}
return null;
},
[]
);
return {
connected,
log,
debug: (msg: string, meta?: Record<string, any>) => log('debug', msg, meta),
info: (msg: string, meta?: Record<string, any>) => log('info', msg, meta),
warn: (msg: string, meta?: Record<string, any>) => log('warn', msg, meta),
error: (msg: string, meta?: Record<string, any>) => log('error', msg, meta),
fatal: (msg: string, meta?: Record<string, any>) => log('fatal', msg, meta),
};
}
// Usage:
// const logger = useIngestLogger('http://localhost:3000');
// await logger.info('Something happened');Node.js Usage
import { IngestClient } from 'client.ingest';
const client = new IngestClient({
url: 'http://localhost:3000',
reconnection: true,
reconnectionAttempts: 10
});
// Set a default source for all logs
client.setSource('my-backend-service');
// Connect and send logs
await client.connect();
await client.info('Server started', { port: 3001 });
// Handle errors
client.on('error', (err) => {
console.error('Logger error:', err);
});Batch Logging
await client.batch([
{ level: 'info', message: 'Step 1 completed' },
{ level: 'info', message: 'Step 2 completed' },
{ level: 'info', message: 'Step 3 completed' }
]);Configuration Options
interface IngestClientOptions {
/** The URL of the service.ingest server (required) */
url: string;
/** Auto-connect on instantiation (default: true) */
autoConnect?: boolean;
/** Enable reconnection (default: true) */
reconnection?: boolean;
/** Max reconnection attempts (default: Infinity) */
reconnectionAttempts?: number;
/** Delay between reconnection attempts in ms (default: 1000) */
reconnectionDelay?: number;
/** Max delay between reconnection attempts in ms (default: 5000) */
reconnectionDelayMax?: number;
/** Connection timeout in ms (default: 20000) */
timeout?: number;
/** Authentication data to send with connection */
auth?: Record<string, any>;
}API Reference
Methods
| Method | Description |
|--------|-------------|
| connect() | Connect to the server (returns Promise) |
| disconnect() | Disconnect from the server |
| destroy() | Disconnect and clean up all resources |
| log(level, message, meta?) | Send a log with specified level |
| debug(message, meta?) | Send a debug log |
| info(message, meta?) | Send an info log |
| warn(message, meta?) | Send a warning log |
| error(message, meta?) | Send an error log |
| fatal(message, meta?) | Send a fatal log |
| batch(entries) | Send multiple log entries |
| sendLogEntry(entry) | Send a complete LogEntry object |
| setSource(source) | Set default source for all logs |
| setRequestTimeout(ms) | Set timeout for requests |
| on(event, listener) | Add event listener |
| off(event, listener?) | Remove event listener |
| once(event, listener) | Add one-time event listener |
| getSocket() | Get underlying Socket.IO socket |
Properties
| Property | Description |
|----------|-------------|
| connected | Boolean indicating connection status |
| id | Socket ID (undefined if not connected) |
Events
| Event | Description |
|-------|-------------|
| connect | Fired when connected to server |
| disconnect | Fired when disconnected (with reason) |
| error | Fired on connection error |
| reconnect | Fired on successful reconnection |
| reconnect_attempt | Fired on each reconnection attempt |
| reconnect_error | Fired on reconnection error |
| reconnect_failed | Fired when all reconnection attempts fail |
TypeScript Support
The package includes full TypeScript definitions. All types are exported:
import type {
IngestClientOptions,
IngestClientEvents,
LogLevel,
LogEntry,
LogResult,
JsonRpcRequest,
JsonRpcResponse,
JsonRpcError
} from 'client.ingest';License
ISC
