@nendlabs/logst
v0.0.1
Published
an sdk for the nendlabs logst api
Readme
Logst SDK
A lightweight and flexible client for publishing events to the Logst API. The Logst SDK makes it easy to queue and send events—whether you need to publish them immediately or in batches on a configurable interval. It also features automatic event name sanitization, customizable logging, and error handling, making it a powerful tool for both client- and server-side applications.
Table of Contents
Features
- Immediate & Scheduled Publishing: Choose between firing events immediately or batching events for periodic publishing.
- Event Name Sanitization: Automatically cleans up event names by replacing invalid characters and removing duplicate or trailing dots.
- Customizable Logging: Use built-in console or noop loggers, or plug in your own custom logger implementing the Logger interface.
- Common Event Properties: Automatically append common properties to each event.
- Error Handling: Optionally throw errors for events that get sanitized unexpectedly.
Installation
You can install the Logst SDK via npm:
npm install @nendlabs/logstQuick Start
Below is a quick example demonstrating how to integrate and use the Logst SDK in your project:
// Example usage in your project
import { Logst } from "@nendlabs/logst";
const logst = new Logst({
api: {
baseUrl: "https://api.logst.nendlabs.com", // Replace with your Logst API endpoint
apiKey: "your-api-key", // Replace with your Logst API key
},
logging: {
// Use "console" for console logging, "noop" to disable, or provide a custom logger object.
logger: "console",
},
publishing: {
immediate: true, // Publish events as soon as they are queued.
intervalMs: 5000, // Interval (in ms) for batch publishing if immediate is false.
},
errors: {
shouldThrow: false, // Set to true if you want to throw errors for event sanitization issues.
},
events: {
properties: {
appVersion: "1.0.0",
environment: "production",
},
},
});
// Publish an event with additional properties
logst.event("user.login", { userId: "12345" });
// When the client is no longer needed, ensure a graceful shutdown:
logst.destroy();Configuration
The SDK requires a configuration object upon initialization with the following options:
- api: Configuration for the Logst API.
baseUrl: string– The endpoint of the Logst API.
- logging: Configure logging.
logger?: Logger | "noop" | "console"– Select a logging strategy:"console": Logs to the console."noop": Disables logging.- Custom Logger: An object that implements
info(),warn(), anderror()methods.
- publishing: Configure event publishing behavior.
immediate?: boolean– Publish events immediately if set totrue.intervalMs: number– Time interval (in milliseconds) for batching and publishing events.
- errors (optional): Error handling options.
shouldThrow?: boolean– Determines if errors should be thrown when an event is invalid.
- events (optional): Common event properties.
properties?: LogstEventProperties– An object of properties that will be automatically included with every event.
Usage
Event Publishing
The core functionality is provided by the event method, which queues events for sending. Before an event is queued, its name is sanitized to ensure it only contains valid characters:
- Sanitization Details:
- Replaces invalid characters with a dot (
.). - Removes duplicate dots.
- Trims any leading or trailing dots.
- Replaces invalid characters with a dot (
Should the sanitization alter the event name, a warning is logged—and if error throwing is enabled (errors.shouldThrow), an error is thrown immediately.
Logger Options
Choose between built-in loggers or a custom logger:
- Console Logger: Use
"console"to output log messages to the browser or Node.js console. - Noop Logger: Use
"noop"to disable logging completely. - Custom Logger: Supply your own logger that implements the standard logging methods:
const customLogger = {
info: (...args: Parameters<typeof console.info>) => {
/* Custom info handling */
},
warn: (...args: Parameters<typeof console.warn>) => {
/* Custom warning handling */
},
error: (...args: Parameters<typeof console.error>) => {
/* Custom error handling */
},
debug: (...args: Parameters<typeof console.debug>) => {
/* Custom debug handling */
},
};
const logst = new Logst({
api: { baseUrl: "https://logst.nendlabs.com", apiKey: "your-api-key" },
logging: { logger: customLogger },
publishing: { immediate: true, intervalMs: 5000 },
});Error Handling
If an event's name changes due to sanitization, the SDK logs a warning. When errors.shouldThrow is enabled, the SDK will throw an error for any invalid event name. This behavior helps surface issues during development or when strict event naming is required.
Destroying the Client
To avoid memory leaks or unintentional background tasks, ensure you destroy your Logst instance when it is no longer needed:
logst.destroy();This clears any pending timers and flushes the event queue.
Advanced Usage
Batch Publishing with Timer
If immediate publishing is disabled, the SDK batches events and publishes them at intervals defined by intervalMs. Each event enqueued while a timer is active will be sent as part of the next batch.
const logst = new Logst({
api: { baseUrl: "https://logst.nendlabs.com", apiKey: "your-api-key" },
logging: { logger: "console" },
publishing: { immediate: false, intervalMs: 3000 },
});
// Multiple events can be queued; they'll be sent every 3 seconds.
logst.event("user.signup", { userId: "user123" });
logst.event("user.update", { userId: "user123", change: "profile picture" });Custom Logger Implementation
For more control over logging output, implement your own logger:
// Custom logger implementation
const myCustomLogger = {
info: (message: string, ...args: Parameters<typeof console.info>) => {
// Custom logic for 'info' messages
console.log("[INFO]", message, ...args);
},
warn: (message: string, ...args: Parameters<typeof console.warn>) => {
// Custom logic for 'warn' messages
console.warn("[WARN]", message, ...args);
},
error: (message: string, ...args: Parameters<typeof console.error>) => {
// Custom logic for 'error' messages
console.error("[ERROR]", message, ...args);
},
debug: (message: string, ...args: Parameters<typeof console.debug>) => {
// Custom logic for 'debug' messages
console.debug("[DEBUG]", message, ...args);
},
};
const logst = new Logst({
api: { baseUrl: "https://logst.nendlabs.com", apiKey: "your-api-key" },
logging: { logger: myCustomLogger },
publishing: { immediate: true, intervalMs: 5000 },
});API Reference
LogstConfig
The configuration object for initializing the client.
- api.baseUrl:
string– Base URL of the Logst API. Usuallyhttps://logst.nendlabs.com. - api.apiKey:
string– API key for the Logst API. - logging.logger:
Logger | "noop" | "console"– Logger to use for output. - publishing.immediate:
boolean(optional) – Iftrue, events are published immediately. - publishing.intervalMs:
number– Milliseconds between event batch publishes. - errors.shouldThrow:
boolean(optional) – Iftrue, invalid events will throw errors. - events.properties:
LogstEventProperties(optional) – Common properties applied to every event.
Logst Class
Constructor
new Logst(config: LogstConfig)Creates a new Logst client instance. This configures the API parameters, logging options, event publishing behavior, error handling, and common event properties.
Methods
event(name: string, properties?: LogstEventProperties): void
Queues an event. The event name is sanitized automatically, and common properties are merged with any custom properties provided.destroy(): void
Clears scheduled publishing timers and flushes any pending events. Use this method to ensure your client is properly torn down to avoid memory leaks.
