300 lines
9.3 KiB
Markdown
300 lines
9.3 KiB
Markdown
# @push.rocks/smartlog
|
|
|
|
Minimalistic distributed and extensible logging tool for TypeScript and JavaScript applications.
|
|
|
|
## Install
|
|
|
|
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 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, 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:
|
|
|
|
```typescript
|
|
import { Smartlog } from '@push.rocks/smartlog';
|
|
|
|
const logger = new Smartlog({
|
|
logContext: {
|
|
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();
|
|
```
|
|
|
|
The context enriches logs with valuable information for filtering and analysis across distributed systems.
|
|
|
|
### Logging Messages
|
|
|
|
```typescript
|
|
// 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 third parameter accepts any additional data to attach to the log entry.
|
|
|
|
### Default Logger
|
|
|
|
For simple cases, use the built-in default logger:
|
|
|
|
```typescript
|
|
import { defaultLogger } from '@push.rocks/smartlog';
|
|
|
|
defaultLogger.log('info', 'Application started');
|
|
```
|
|
|
|
### 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
|
|
|
|
For CLI applications, use the interactive console features:
|
|
|
|
```typescript
|
|
import { SmartlogSourceInteractive, SmartlogProgressBar } from '@push.rocks/smartlog/source-interactive';
|
|
```
|
|
|
|
#### Spinners
|
|
|
|
```typescript
|
|
const spinner = new SmartlogSourceInteractive();
|
|
|
|
// Start a spinner with text
|
|
spinner.text('Loading data...');
|
|
|
|
// 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!');
|
|
spinner.finishFail('Failed to load data!');
|
|
|
|
// Chain operations
|
|
spinner.text('Connecting to server')
|
|
.successAndNext('Fetching records')
|
|
.successAndNext('Processing data')
|
|
.finishSuccess('All done!');
|
|
```
|
|
|
|
#### Progress Bars
|
|
|
|
```typescript
|
|
const progressBar = new SmartlogProgressBar({
|
|
total: 100, // Total number of items
|
|
width: 40, // Width of the progress bar
|
|
complete: '█', // Character for completed section
|
|
incomplete: '░', // Character for incomplete section
|
|
showEta: true, // Show estimated time remaining
|
|
showPercent: true, // Show percentage
|
|
showCount: true // Show count (e.g., "50/100")
|
|
});
|
|
|
|
// Update progress
|
|
progressBar.update(25); // Set to 25% progress
|
|
|
|
// Increment progress
|
|
progressBar.increment(5); // Increase by 5 units
|
|
|
|
// Change color
|
|
progressBar.setColor('blue');
|
|
|
|
// Complete the progress bar
|
|
progressBar.complete();
|
|
```
|
|
|
|
#### Non-Interactive Environments
|
|
|
|
Both spinners and progress bars automatically detect non-interactive environments (CI/CD, piped output) and fallback to plain text logging:
|
|
|
|
```
|
|
[Loading] Connecting to server
|
|
[Success] Connected to server
|
|
[Loading] Fetching records
|
|
Progress: 50% (50/100)
|
|
Progress: 100% (100/100)
|
|
[Success] Fetching complete
|
|
```
|
|
|
|
## Advanced Usage
|
|
|
|
### Capturing All Console Output
|
|
|
|
Capture all `console.log` and `console.error` output through Smartlog:
|
|
|
|
```typescript
|
|
logger.enableConsole({ captureAll: true });
|
|
```
|
|
|
|
### Increment Logging
|
|
|
|
For metrics and counters:
|
|
|
|
```typescript
|
|
logger.increment('info', 'api_requests', { endpoint: '/users' });
|
|
```
|
|
|
|
### Log Correlation
|
|
|
|
Correlate logs across services with correlation IDs:
|
|
|
|
```typescript
|
|
logger.log('info', 'Request received', { userId: 'user-123' }, {
|
|
id: 'req-abc-123',
|
|
type: 'service',
|
|
transaction: 'tx-payment-456'
|
|
});
|
|
```
|
|
|
|
## API Documentation
|
|
|
|
For detailed API documentation, see the [API.md](API.md) file.
|
|
|
|
## License and Legal Information
|
|
|
|
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
|
|
|
|
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
|
|
|
|
### Trademarks
|
|
|
|
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
|
|
|
|
### Company Information
|
|
|
|
Task Venture Capital GmbH
|
|
Registered at District court Bremen HRB 35230 HB, Germany
|
|
|
|
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
|
|
|
|
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works. |