@angsana_consulting/logger-service
v1.0.1
Published
Universal logging service for Angsana platform - handles error, system, and usage logs
Maintainers
Readme
@angsana_consulting/logger-service
Universal logging service for Angsana platform projects. Provides handlers for error, system, and usage logging with automatic TTL management, validation, and retry logic.
Installation
npm install @angsana_consulting/logger-serviceFeatures
- Multi-collection logging: Automatically routes logs to ErrorLogs, SystemLogs, or UsageLogs collections
- Automatic TTL management: Configurable retention periods with automatic cleanup
- Built-in validation: Validates payloads before writing to Firestore
- Retry logic: Automatic retry with exponential backoff for transient failures
- Backward compatibility: Works with existing errorLogger implementations
- Type safety: Full TypeScript support with exported types
Usage
1. Import in your Cloud Function
// In your main functions file (e.g., functions/src/index.ts)
import { universalLoggerHandler } from '@angsana_consulting/logger-service';
// Export as a Cloud Function
export const errorLogger = onRequest(
{ region: 'europe-west2', timeoutSeconds: 10 },
universalLoggerHandler
);2. Register with your proxy (if using one)
// In your proxy handler (e.g., functions/src/proxy/proxy.ts)
import { universalLoggerHandler } from '@angsana_consulting/logger-service';
// Register the handler
handlers.set('errorLogger', universalLoggerHandler);3. Call from Retool or other clients
Error Logging
// Retool JS Query: logError
const payload = {
type: 'error', // Optional - defaults to 'error' if not specified
service: 'retool',
operation: 'submitRequestedNumbers',
level: 'error',
message: error.message,
errorMessage: error.message,
errorStack: error.stack,
errorCode: error.code,
context: {
component: 'SubmitButton',
userId: current_user.email,
payload: formData
}
};
await fetch(
'https://your-project.cloudfunctions.net/proxyFn?target=errorLogger',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': globals.api_key
},
body: JSON.stringify(payload)
}
);System Logging
// Log a system event
const payload = {
type: 'system',
service: 'retool',
operation: 'configUpdate',
level: 'info',
message: 'User updated configuration settings',
context: {
userId: current_user.email,
changes: changedFields
}
};
await fetch('https://your-project.cloudfunctions.net/proxyFn?target=errorLogger', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': globals.api_key
},
body: JSON.stringify(payload)
});Usage Logging
// Log user activity
const payload = {
type: 'usage',
service: 'retool',
operation: 'powerDial',
userId: current_user.email,
clientId: selectedClient.value,
clientName: selectedClient.label,
sessionId: sessionId.value,
action: 'power_dial',
dialCount: selectedNumbers.length,
successfulConnect: true,
duration: callDuration,
countries: ['GB', 'US'],
metadata: {
campaign: campaignId,
callType: 'sales'
}
};
await fetch('https://your-project.cloudfunctions.net/proxyFn?target=errorLogger', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': globals.api_key
},
body: JSON.stringify(payload)
});4. Direct usage in Cloud Functions
import {
universalLoggerHandler,
createLogPayload,
ErrorLogPayload,
SystemLogPayload,
UsageLogPayload
} from '@angsana_consulting/logger-service';
// In your function handlers
export async function myFunctionHandler(req: Request, res: Response) {
try {
// Your function logic here
// Log success
const logReq = {
body: createLogPayload('system', 'myFunction', 'process', {
message: 'Processing completed successfully',
level: 'info',
context: { recordsProcessed: 100 }
})
} as Request;
// Call the logger directly
await universalLoggerHandler(logReq, res);
} catch (error) {
// Log error
const logReq = {
body: createLogPayload('error', 'myFunction', 'process', {
errorMessage: error.message,
errorStack: error.stack,
level: 'error'
})
} as Request;
await universalLoggerHandler(logReq, res);
}
}Log Types
Error Logs (type: 'error')
Written to ErrorLogs collection. Use for:
- Application errors
- API failures
- Validation errors
- System exceptions
System Logs (type: 'system')
Written to SystemLogs collection. Use for:
- Service lifecycle events
- Configuration changes
- Performance metrics
- Debug information
Usage Logs (type: 'usage')
Written to UsageLogs collection. Use for:
- User activity tracking
- Feature usage metrics
- Call/dial statistics
- Business analytics
Auto-detection
If type is not specified, the logger will auto-detect based on fields:
- Contains
userId+ (actionordialCount) → Usage log - Contains
errorMessage,errorStack, orlevel: 'error'→ Error log - Otherwise → Error log (for backward compatibility)
Response Format
// Success response
{
"success": true,
"logType": "error" | "system" | "usage",
"message": "Log written to [collection] collection"
}
// Error response
{
"error": "Error message",
"errors": [...], // Validation errors if any
"logType": "error" | "system" | "usage"
}Configuration
The logger uses settings from your Firestore Settings collection for:
- TTL/retention periods for each collection
- Validation rules
- Retry configuration
TypeScript Types
import {
LogType,
LogLevel,
LogPayload,
ErrorLogPayload,
SystemLogPayload,
UsageLogPayload,
LoggerResponse,
SystemEventType,
UsageActionType
} from '@angsana_consulting/logger-service';Migration from errorLogger
Existing errorLogger calls will continue to work without changes. The handler is backward compatible and will:
- Accept payloads without a
typefield - Auto-detect the appropriate collection
- Default to ErrorLogs for backward compatibility
License
MIT
