@team_posley/logging-sdk
v0.0.14
Published
Logging SDK for Posley - A comprehensive logging and monitoring solution
Downloads
14
Maintainers
Readme
@team_posley/logging-sdk
A powerful and flexible logging package for Posley services with built-in error handling, retry mechanisms, and structured logging.
Installation
npm install @team_posley/logging-sdkFeatures
- Multiple severity levels (DEBUG, INFO, WARN, ERROR, FATAL)
- Structured logging with context and tags
- Automatic retry mechanism for network issues
- Default values management (component, tags, context)
- Console logging with configurable levels and colors
- TypeScript support
- Rebalancing-specific logging
- Request size validation
- Comprehensive error handling
- Batch logging support
Quick Start
import { LoggingClient } from '@team_posley/logging-sdk';
// Initialize the client
const logger = new LoggingClient({
logServer: process.env.LOG_SERVER,
logServerApiKey: process.env.LOG_SERVICE_API_KEY,
defaultComponent: 'UserService',
defaultTags: ['production'],
defaultContext: {
environment: process.env.NODE_ENV,
version: '1.0.0'
},
// Enable console logging
console: {
minLevel: 'INFO', // Only log INFO and above to console
detailed: true // Include context in console output
}
});
// Log at different severity levels
await logger.info('User logged in', {
context: { userId: '123' },
tags: ['auth']
});
// Console: INFO: 2024-01-20T12:34:56.789Z [UserService] (auth, production) User logged in
// Context: { userId: '123', environment: 'production', version: '1.0.0' }
await logger.error('Payment failed', {
context: {
orderId: 'order_123',
error: new Error('Insufficient funds')
}
});
// Console: ERROR: 2024-01-20T12:34:57.123Z [UserService] (production) Payment failed
// Context: { orderId: 'order_123', error: {...}, environment: 'production', version: '1.0.0' }
// Use with try/catch
try {
throw new Error('Database connection failed');
} catch (error) {
await logger.error('Database error', {
context: {
error: error instanceof Error ? {
message: error.message,
stack: error.stack
} : 'Unknown error'
},
tags: ['database']
});
}API Reference
Initialization
const logger = new LoggingClient({
// Required
logServer: string; // Log server URL
logServerApiKey: string; // API key for authentication
// Optional
logServerTimeout?: number; // Request timeout (default: 5000ms)
defaultComponent?: string; // Default component name
defaultTags?: string[]; // Default tags for all logs
defaultContext?: Record<string, unknown>; // Default context
// Console logging configuration (optional)
console?: {
minLevel: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'FATAL'; // Minimum level to log
detailed?: boolean; // Include context in console output
}
});Logging Methods
Severity-based Logging
// Debug level
await logger.debug(message: string, options?: LogOptions);
// Info level
await logger.info(message: string, options?: LogOptions);
// Warning level
await logger.warn(message: string, options?: LogOptions);
// Error level
await logger.error(message: string, options?: LogOptions);
// Fatal level
await logger.fatal(message: string, options?: LogOptions);
// Custom Log
await logger.logCustom(message: string, options?: LogOptions, severity?: LogSeverity);Batch Logging
// Example 1: Batch logging with same severity
const logs: GeneralLog[] = [
{
logType: 'CUSTOM',
component: 'BatchProcessor',
message: 'Processing item 1',
severity: 'INFO',
context: { itemId: '1' },
tags: ['batch', 'processing']
},
{
logType: 'CUSTOM',
component: 'BatchProcessor',
message: 'Processing item 2',
severity: 'INFO',
context: { itemId: '2' },
tags: ['batch', 'processing']
}
];
await logger.batchPublishGeneralLogs(logs);
// Example 2: Batch logging with different severities
const mixedLogs: GeneralLog[] = [
{
logType: 'CUSTOM',
component: 'BatchProcessor',
message: 'Starting batch process',
severity: 'INFO',
context: { batchId: '123' },
tags: ['batch', 'start']
},
{
logType: 'ERROR',
component: 'BatchProcessor',
message: 'Item validation failed',
severity: 'ERROR',
context: { itemId: '456' },
tags: ['batch', 'error']
}
];
await logger.batchPublishGeneralLogs(mixedLogs);
// Example 3: Batch logging with default values
logger.setDefaultComponent('BatchProcessor');
logger.addDefaultTags('batch', 'processing');
const batchLogs: GeneralLog[] = [
{
logType: 'CUSTOM',
component: 'BatchProcessor',
message: 'Batch started',
severity: 'INFO',
timestamp: new Date().toISOString()
},
{
logType: 'CUSTOM',
component: 'BatchProcessor',
message: 'Processing items',
severity: 'INFO',
context: { count: 100 }
},
{
logType: 'CUSTOM',
component: 'BatchProcessor',
message: 'Batch completed',
severity: 'INFO',
context: { duration: '1s' }
}
];
try {
await logger.batchPublishGeneralLogs(batchLogs);
} finally {
logger.clearDefaults();
}LogOptions Interface
interface LogOptions {
component?: string; // Override default component
context?: Record<string, unknown>; // Additional context
tags?: string[]; // Additional tags
timestamp?: Date; // Custom timestamp
}Default Values Management
// Set default component
logger.setDefaultComponent('PaymentService');
// Add default tags
logger.addDefaultTags('payment', 'production');
// Set default context
logger.setDefaultContext({
environment: 'production',
version: '1.0.0'
});
// Add to default context
logger.addDefaultContext({
region: 'us-east-1'
});
// Clear all defaults
logger.clearDefaults();Specialized Logging
SDK Error Logging
await logger.logSDKError(
'APIClient',
new Error('API request failed'),
{
endpoint: '/api/v1/users',
statusCode: 500
}
);Rebalancing Log
await logger.publishRebalancingLog({
amount_usd: 1000.00,
amount: 0.05,
asset: 'USD',
start_time: new Date().toISOString(),
end_time: new Date().toISOString(),
from_account_id: 123,
to_account_id: 456,
strategy: 'periodic_rebalance',
transaction_id: ['123', '234']
fee: 0.001
});Best Practices
1. Use Appropriate Severity Levels
// Debug: Detailed information for debugging
logger.debug('Processing order items', { context: { items: [] } });
// Info: General operational information
logger.info('Order processed successfully');
// Warning: Warning messages for potential issues
logger.warn('High API latency detected');
// Error: Error conditions that should be addressed
logger.error('Payment processing failed');
// Fatal: Severe errors that might lead to system failure
logger.fatal('Database connection lost');2. Structured Context
// Good: Structured, searchable context
await logger.error('Payment failed', {
context: {
orderId: 'order_123',
userId: 'user_456',
amount: 100.00,
currency: 'USD',
error: {
code: 'INSUFFICIENT_FUNDS',
message: 'Not enough balance'
}
}
});
// Bad: Unstructured context
await logger.error('Payment failed: order_123, user_456, $100');3. Resource Cleanup
try {
// Your operations here
} finally {
// Always clean up defaults when done
logger.clearDefaults();
}4. Component Organization
// Set component for a group of related operations
logger.setDefaultComponent('PaymentProcessor');
try {
// Payment processing operations
await logger.info('Starting payment processing');
await processPayment();
await logger.info('Payment completed');
} finally {
logger.clearDefaults();
}5. Error Context
try {
await someOperation();
} catch (error) {
await logger.error('Operation failed', {
context: {
error: error instanceof Error ? {
name: error.name,
message: error.message,
stack: error.stack
} : 'Unknown error',
operationId: 'op_123'
},
tags: ['operation', 'error']
});
}6. Batch Logging Best Practices
// Good: Use batch logging for related operations
const processLogs: GeneralLog[] = [
{
logType: 'CUSTOM',
component: 'BatchProcessor',
message: 'Starting batch process',
severity: 'INFO',
context: { batchId: '123' },
tags: ['batch', 'start']
},
{
logType: 'CUSTOM',
component: 'BatchProcessor',
message: 'Processing items',
severity: 'INFO',
context: { count: 100 },
tags: ['batch', 'process']
},
{
logType: 'CUSTOM',
component: 'BatchProcessor',
message: 'Batch completed',
severity: 'INFO',
context: { duration: '1s' },
tags: ['batch', 'complete']
}
];
await logger.batchPublishGeneralLogs(processLogs);
// Good: Use default values for batch operations
logger.setDefaultComponent('BatchProcessor');
logger.addDefaultTags('batch', 'processing');
try {
const batchLogs: GeneralLog[] = [
{
logType: 'CUSTOM',
component: 'BatchProcessor',
message: 'Batch started',
severity: 'INFO'
},
{
logType: 'CUSTOM',
component: 'BatchProcessor',
message: 'Processing items',
severity: 'INFO'
},
{
logType: 'CUSTOM',
component: 'BatchProcessor',
message: 'Batch completed',
severity: 'INFO'
}
];
await logger.batchPublishGeneralLogs(batchLogs);
} finally {
logger.clearDefaults();
}
## Error Handling
The client includes built-in error handling:
- Automatic retries for network issues (3 attempts with exponential backoff)
- Request size validation (10KB limit)
- Proper error wrapping with SDKError
- Comprehensive error context
## TypeScript Support
The package is written in TypeScript and includes type definitions for all APIs.
## Console Logging
The logger supports colorized console output alongside server logging. Console output can be configured with different severity levels and detail options.
### Configuration
```typescript
const logger = new LoggingClient({
// ... other config ...
console: {
minLevel: 'INFO', // Only log INFO and above
detailed: true // Include context details
}
});Severity Colors
Console output is color-coded by severity:
- DEBUG: Gray
- INFO: Blue
- WARN: Yellow
- ERROR: Red
- FATAL: White on Red background
Output Format
// Basic format
await logger.info('User logged in');
// INFO: 2024-01-20T12:34:56.789Z [Component] (tags) Message
// With context (detailed: true)
await logger.error('Operation failed', {
context: { operationId: '123' }
});
// ERROR: 2024-01-20T12:34:56.789Z [Component] (tags) Operation failed
// Context: { operationId: '123' }Best Practices
- Development vs Production
const logger = new LoggingClient({
// ... other config ...
console: {
// More verbose logging in development
minLevel: process.env.NODE_ENV === 'development' ? 'DEBUG' : 'INFO',
detailed: process.env.NODE_ENV === 'development'
}
});License
MIT
