fix(documentation): Update API reference and enhance README with detailed examples and usage instructions

This commit is contained in:
2025-05-19 22:51:17 +00:00
parent f80ec7ddfe
commit 6ef2d961a6
5 changed files with 545 additions and 82 deletions

264
readme.md
View File

@ -1,103 +1,215 @@
# @push.rocks/smartlog
minimalistic distributed and extensible logging tool
Minimalistic distributed and extensible logging tool for TypeScript and JavaScript applications.
## Install
You can install `@push.rocks/smartlog` using npm:
Install `@push.rocks/smartlog` using pnpm (recommended), npm, or yarn:
```sh
# Using pnpm (recommended)
pnpm add @push.rocks/smartlog
# Using npm
npm install @push.rocks/smartlog --save
# Using yarn
yarn add @push.rocks/smartlog
```
Ensure that you have TypeScript and node.js installed in your development environment, as this module is intended to be used with TypeScript.
Ensure you have TypeScript and Node.js installed for TypeScript projects.
## Package Exports
The package provides the following exports:
```javascript
// Main module
import { Smartlog, LogGroup, ConsoleLog } from '@push.rocks/smartlog';
// Type definitions and interfaces
import { ILogPackage, ILogDestination, TLogLevel } from '@push.rocks/smartlog/interfaces';
// Interactive console features (spinners, progress bars)
import { SmartlogSourceInteractive, SmartlogProgressBar } from '@push.rocks/smartlog/source-interactive';
// Context management
import { ... } from '@push.rocks/smartlog/context';
// Log destinations
import { SmartlogDestinationClickhouse } from '@push.rocks/smartlog/destination-clickhouse';
import { SmartlogDestinationDevtools } from '@push.rocks/smartlog/destination-devtools';
import { SmartlogDestinationFile } from '@push.rocks/smartlog/destination-file';
import { DestinationLocal } from '@push.rocks/smartlog/destination-local';
import { SmartlogDestinationReceiver } from '@push.rocks/smartlog/destination-receiver';
// Receiver functionality
import { SmartlogReceiver } from '@push.rocks/smartlog/receiver';
```
## Usage
`@push.rocks/smartlog` is a flexible and extensible logging tool designed to provide a minimalistic yet powerful logging solution across different environments, making it especially useful in distributed systems. This documentation aims to guide you through its capabilities, setup, and how to integrate it seamlessly into your TypeScript projects.
`@push.rocks/smartlog` is a flexible, extensible logging tool designed for distributed systems. It provides a consistent logging interface across different environments while being lightweight and customizable.
### Creating a Logger Instance
Start by importing `Smartlog` and create a logger instance by providing a context that describes your logging environment:
Start by importing `Smartlog` and create a logger instance:
```typescript
import { Smartlog } from '@push.rocks/smartlog';
const logger = new Smartlog({
logContext: {
company: 'My awesome company',
companyunit: 'my awesome cloud team',
containerName: 'awesome-container',
environment: 'kubernetes-production',
runtime: 'node',
zone: 'zone x',
company: 'My Company',
companyunit: 'Cloud Team',
containerName: 'api-service',
environment: 'production', // 'local', 'test', 'staging', 'production'
runtime: 'node', // 'node', 'chrome', 'rust', 'deno', 'cloudflare_workers'
zone: 'us-west',
},
minimumLogLevel: 'info', // Optional, defaults to 'silly'
});
// Enable console output
logger.enableConsole();
```
This context enriches your logs with valuable information, making them easier to filter and analyze in a distributed system.
The context enriches logs with valuable information for filtering and analysis across distributed systems.
### Logging Messages
Logging is straightforward; you can log messages at various levels such as `info`, `warn`, `error`, `silly`, etc.:
```typescript
logger.log('info', 'This is an info message');
logger.log('error', 'This is an error message with details', { errorCode: 123 });
// Basic logging
logger.log('info', 'User authenticated successfully');
logger.log('error', 'Database connection failed', { errorCode: 'DB_CONN_ERR', retryCount: 3 });
logger.log('warn', 'Rate limit approaching', { currentRate: 95, limit: 100 });
// Log levels: 'silly', 'info', 'debug', 'note', 'ok', 'success', 'warn', 'error', 'lifecycle'
```
The logging method accepts additional data as the third parameter, allowing you to attach more context to each log message, which is immensely useful for debugging.
The third parameter accepts any additional data to attach to the log entry.
### Using the Default Logger
### Default Logger
For convenience, `@push.rocks/smartlog` provides a default logger that you can use out of the box:
For simple cases, use the built-in default logger:
```typescript
import { defaultLogger } from '@push.rocks/smartlog';
defaultLogger.log('warn', 'This is a warning message using the default logger');
defaultLogger.log('info', 'Application started');
```
This is particularly helpful for simple applications or for initial project setup.
### Log Groups
Group related logs for better traceability:
```typescript
// Create a log group with optional transaction ID
const requestGroup = logger.createLogGroup('tx-123456');
// Logs within this group will be correlated
requestGroup.log('info', 'Processing payment request');
requestGroup.log('debug', 'Validating payment details');
requestGroup.log('success', 'Payment processed successfully');
```
### Custom Log Destinations
Extend logging capabilities by adding custom destinations:
```typescript
import { Smartlog, ILogDestination } from '@push.rocks/smartlog';
class DatabaseLogDestination implements ILogDestination {
async handleLog(logPackage) {
// Store log in database
await db.logs.insert({
timestamp: new Date(logPackage.timestamp),
level: logPackage.level,
message: logPackage.message,
data: logPackage.data,
context: logPackage.context
});
}
}
// Add the custom destination to your logger
logger.addLogDestination(new DatabaseLogDestination());
```
### Built-in Destinations
SmartLog comes with several built-in destinations for various logging needs:
```typescript
// Log to a file
import { SmartlogDestinationFile } from '@push.rocks/smartlog/destination-file';
logger.addLogDestination(new SmartlogDestinationFile('/path/to/logfile.log'));
// Colorful local console logging
import { DestinationLocal } from '@push.rocks/smartlog/destination-local';
logger.addLogDestination(new DestinationLocal());
// Browser DevTools with colored formatting
import { SmartlogDestinationDevtools } from '@push.rocks/smartlog/destination-devtools';
logger.addLogDestination(new SmartlogDestinationDevtools());
// ClickHouse database logging
import { SmartlogDestinationClickhouse } from '@push.rocks/smartlog/destination-clickhouse';
const clickhouse = await SmartlogDestinationClickhouse.createAndStart({
host: 'clickhouse.example.com',
port: 8123,
user: 'username',
password: 'password',
database: 'logs_db'
});
logger.addLogDestination(clickhouse);
// Remote receiver logging
import { SmartlogDestinationReceiver } from '@push.rocks/smartlog/destination-receiver';
logger.addLogDestination(new SmartlogDestinationReceiver({
endpoint: 'https://logs.example.com/api/logs'
}));
```
### Interactive Console Features
Smartlog provides interactive console features through the `@push.rocks/smartlog/source-interactive` module:
For CLI applications, use the interactive console features:
```typescript
import { SmartlogSourceInteractive, SmartlogProgressBar } from '@push.rocks/smartlog/source-interactive';
```
#### Spinners
Use spinners to show progress for operations:
```typescript
import { SmartlogSourceInteractive } from '@push.rocks/smartlog/source-interactive';
const spinner = new SmartlogSourceInteractive();
// Start a spinner with text
spinner.text('Loading data...');
// Later, when the operation completes:
// Customize appearance
spinner.setSpinnerStyle('dots'); // 'dots', 'line', 'star', 'simple'
spinner.setColor('blue'); // 'red', 'green', 'yellow', 'blue', etc.
spinner.setSpeed(80); // Animation speed in milliseconds
// Update spinner status
spinner.text('Processing records...');
// Complete with success or failure
spinner.finishSuccess('Data loaded successfully!');
// Or if it fails:
spinner.finishFail('Failed to load data');
spinner.finishFail('Failed to load data!');
// You can chain operations:
spinner.text('Connecting to server');
spinner.successAndNext('Fetching records');
spinner.successAndNext('Processing data');
spinner.finishSuccess('All done!');
// Customize appearance:
spinner.setSpinnerStyle('line'); // 'dots', 'line', 'star', or 'simple'
spinner.setColor('green'); // 'red', 'green', 'yellow', 'blue', etc.
spinner.setSpeed(100); // Animation speed in milliseconds
// Chain operations
spinner.text('Connecting to server')
.successAndNext('Fetching records')
.successAndNext('Processing data')
.finishSuccess('All done!');
```
#### Progress Bars
Create progress bars for tracking operation progress:
```typescript
import { SmartlogProgressBar } from '@push.rocks/smartlog/source-interactive';
const progressBar = new SmartlogProgressBar({
total: 100, // Total number of items
width: 40, // Width of the progress bar
@ -109,72 +221,64 @@ const progressBar = new SmartlogProgressBar({
});
// Update progress
progressBar.update(50); // Set to 50% progress
progressBar.update(25); // Set to 25% progress
// Or increment
progressBar.increment(10); // Increase by 10 units
// Increment progress
progressBar.increment(5); // Increase by 5 units
// Change color
progressBar.setColor('blue');
// Complete the progress bar
progressBar.update(100); // or progressBar.complete();
progressBar.complete();
```
#### Non-Interactive Environments
Both spinners and progress bars automatically detect non-interactive environments (CI/CD, piped output, non-TTY) and provide fallback text-based output:
Both spinners and progress bars automatically detect non-interactive environments (CI/CD, piped output) and fallback to plain text logging:
```
[Loading] Loading data...
[Loading] Connecting to server
[Success] Connected to server
[Loading] Fetching records
Progress: 50% (50/100)
Progress: 100% (100/100)
[Success] Data loaded successfully!
[Success] Fetching complete
```
### Extending With Log Destinations
## Advanced Usage
One of the core strengths of `@push.rocks/smartlog` is its ability to work with multiple log destinations, enabling you to log messages not just to the console but also to external logging services or custom destinations.
### Capturing All Console Output
To add a log destination, you create a class that implements the `ILogDestination` interface and then add it to the logger:
Capture all `console.log` and `console.error` output through Smartlog:
```typescript
import { Smartlog, ILogDestination } from '@push.rocks/smartlog';
class MyCustomLogDestination implements ILogDestination {
async handleLog(logPackage) {
// Implement your custom logging logic here
console.log(`Custom log: ${logPackage.message}`);
}
}
const logger = new Smartlog({
logContext: {
/* your context */
},
});
logger.addLogDestination(new MyCustomLogDestination());
logger.enableConsole({ captureAll: true });
```
After adding your custom log destination(s), every log message sent through `Smartlog` will also be routed to them according to their implementation.
### Increment Logging
### Integration with Logging Services
For metrics and counters:
`@push.rocks/smartlog` is designed to be extensible; you can integrate it with various logging services like Scalyr, Elasticsearch, LogDNA, etc., by developing or using existing log destinations conforming to those services.
```typescript
logger.increment('info', 'api_requests', { endpoint: '/users' });
```
Check the npm registry or GitHub for community-contributed log destinations that can seamlessly integrate `@push.rocks/smartlog` into your preferred logging infrastructure.
### Log Correlation
### Advanced Usage
Correlate logs across services with correlation IDs:
- **Log Groups**: You can use log groups to associate related log messages, which is especially handy for tracking logs across distributed systems.
- **Custom Log Levels**: Beyond the standard log levels, you can define custom log levels that suit your project needs.
- **Dynamic Log Contexts**: The log context can be dynamically adjusted to reflect different stages or aspects of your application logic.
```typescript
logger.log('info', 'Request received', { userId: 'user-123' }, {
id: 'req-abc-123',
type: 'service',
transaction: 'tx-payment-456'
});
```
### Conclusion
## API Documentation
`@push.rocks/smartlog` empowers you to implement a robust logging solution tailored to your needs with minimal effort. Its design promotes clarity, flexibility, and integration ease, making it an excellent choice for projects of any scale.
Remember to refer to the official documentation and the type definitions for detailed information on all available methods and configurations. Happy logging!
For detailed API documentation, see the [API.md](API.md) file.
## License and Legal Information