0.0.3 • Published 1 month ago
@team_posley/logging-sdk v0.0.3
@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-sdk
Features
- 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
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);
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_id: 1,
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']
});
}
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
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