lazydev-logger
v1.0.0
Published
TypeScript library for structured JSON logging with data masking and compliance features
Maintainers
Readme
lazy-logger
A TypeScript library for structured JSON logging with built-in data masking, field validation, and compliance features. Designed for observability, PDPA compliance, and audit requirements in API and application environments.
Features
- 7 Standardized Log Types: API requests/responses, external API calls, transactions, access logs, and activity logs
- Automatic Data Masking: Built-in Thai-specific masking rules for PII (names, IDs, phone numbers, etc.)
- Request Correlation: UUID-based request tracking across service boundaries
- Severity-Based Field Filtering: Different field sets per severity level to minimize data exposure
- Size Management: Automatic truncation with configurable 256KB per-record limit
- Transport Flexibility: Console, file, and network (HTTP/HTTPS) output with exponential-backoff retry
- Full TypeScript Support: Comprehensive interfaces and type safety
- PDPA Compliance Ready: Sensitive fields auto-masked and auto-filtered out of the box
Installation
npm install lazy-loggerRequirements
- Node.js >= 18.0.0
- TypeScript >= 5.0.0 (for TypeScript projects)
Quick Start
import { StructuredLogger, SeverityLevel } from 'lazy-logger';
const logger = new StructuredLogger({
service: 'production/ecommerce/api', // {env}/{domain}/{service}
defaultSeverity: SeverityLevel.INFO,
maskingRules: { enableMasking: true },
transport: { type: 'console' }
});
// Log an incoming request
logger.logApiIncomingRequest({
http_method: 'POST',
url: '/api/v1/users',
user_id: 'user_123'
});
// Log a response — severity is auto-detected from the status code
logger.logApiOutgoingResponse({
http_method: 'POST',
url: '/api/v1/users',
response_status: 201 // → INFO
});Log Types
1. API Incoming Request
logger.logApiIncomingRequest({
http_method: 'POST',
url: '/api/v1/users/profile',
request_headers: logger.filterHeaders(req.headers),
query_params: logger.filterParameters(req.query),
request_body: JSON.stringify(req.body),
user_id: 'user_123'
}, SeverityLevel.DEBUG);2. API Outgoing Response
logger.logApiOutgoingResponse({
http_method: 'POST',
url: '/api/v1/users/profile',
response_status: 200,
response_body: JSON.stringify(responseBody)
}); // severity and status auto-determined from response_status3. API External Request
logger.logApiExternalRequest({
endpoint: 'https://payment-gateway.com/api/charge',
http_method: 'POST',
request_body: JSON.stringify(paymentData)
}, SeverityLevel.INFO);4. API External Response
logger.logApiExternalResponse({
endpoint: 'https://payment-gateway.com/api/charge',
response_status: 201,
response_body: JSON.stringify(response)
});5. Application Transaction
logger.logTransaction({
action: 'user_profile_update',
user_id: 'user_123',
transaction_before: JSON.stringify(oldData),
transaction_after: JSON.stringify(newData)
}, SeverityLevel.INFO);6. Application Access
logger.logAccess({
action: 'user_login',
ip_address: '192.168.1.100',
username: 'john.doe',
auth_result: 'success',
auth_method: 'password'
}, SeverityLevel.INFO);7. Application Activity
logger.logActivity({
action: 'product_view',
reference_key: 'product_123',
user_id: 'user_456'
}, SeverityLevel.INFO);Configuration
The service name must follow the {env}/{domain}/{service} format (e.g., production/payments/api).
Development
const logger = new StructuredLogger({
service: 'development/myapp/api',
defaultSeverity: SeverityLevel.DEBUG,
maskingRules: { enableMasking: false },
transport: { type: 'console' }
});Production — File Transport
const logger = new StructuredLogger({
service: 'production/myapp/api',
defaultSeverity: SeverityLevel.INFO,
maskingRules: { enableMasking: true },
transport: {
type: 'file',
options: { filePath: '/var/log/app/structured.log' },
enableRetry: true,
maxRetries: 5,
retryDelay: 1000
},
retention: {
defaultRetentionDays: 90,
enableArchival: true
}
});Production — Network Transport
const logger = new StructuredLogger({
service: 'production/myapp/api',
defaultSeverity: SeverityLevel.INFO,
maskingRules: { enableMasking: true },
transport: {
type: 'network',
options: {
endpoint: 'https://log-collector.example.com/logs',
headers: { 'Authorization': 'Bearer <token>' },
timeout: 5000
},
enableRetry: true,
maxRetries: 3,
retryDelay: 1000
}
});Severity Levels
| Level | Field Coverage | Auto-trigger |
|---------|--------------------------------------------------|------------------------|
| DEBUG | Full — headers, bodies, params included | Manual |
| INFO | Essential — method, URL, status, user_id | 2xx status codes |
| WARN | Info fields + error_details | 4xx status codes |
| ERROR | Info fields + error_details | 5xx status codes |
| FATAL | Info fields + error_details | Manual |
Methods that accept a response_status (logApiOutgoingResponse, logApiExternalResponse) automatically select the severity and status field if you don't provide them.
Data Masking
Masking is applied automatically to all log fields. Built-in rules follow Thai data protection standards (PDPA):
| Field Type | Example Input | Masked Output |
|----------------|----------------------------|--------------------------|
| Full name | สมชาย ใจดี | สมชาย xxxxx |
| National ID | 1-1234-56789-01-2 | 1-1234-5678xx-x |
| Passport | AA1234567 | AA12xxx67 |
| Phone | 0812345678 | xxxxxx5678 |
| Email | [email protected] | [email protected] |
| Bank account | 123-4-56789-0 | 123-4-567xx-0 |
| Credit card | 1234-5678-9012-3456 | 123456xxxxxx3456 |
Fields matching sensitive names (nationality, hiv_status, disability, etc.) are completely removed.
Custom Masking Rules
const logger = new StructuredLogger({
service: 'production/myapp/api',
maskingRules: {
enableMasking: true,
customPatterns: {
employeeId: {
pattern: /^(\w{2})\d{4}(\w{2})$/,
replacement: '$1xxxx$2'
}
}
},
transport: { type: 'console' }
});Request Correlation
// Set a request ID at the start of a request (e.g., from an incoming header)
const requestId = logger.generateRequestId();
logger.setRequestId(requestId);
// All subsequent log calls within this request will carry the same request_id
logger.logApiIncomingRequest({ http_method: 'GET', url: '/api/items' });
// Create a child ID when calling downstream services
const { parent_request_id, child_request_id } = logger.createChildRequestId();
logger.logApiExternalRequest({
endpoint: 'https://inventory.internal/items',
http_method: 'GET',
request_id: child_request_id
});
// Clear at the end of the request
logger.clearRequestId();Header and Parameter Filtering
// filterHeaders keeps safe headers and removes sensitive ones (Authorization, Cookie, etc.)
const safeHeaders = logger.filterHeaders(req.headers);
// filterParameters removes sensitive keys (password, token, api_key, etc.) and masks the rest
const safeParams = logger.filterParameters(req.query);
logger.logApiIncomingRequest({
http_method: 'GET',
url: '/api/search',
request_headers: safeHeaders,
query_params: safeParams
});Default blocked headers: Authorization, Cookie, Set-Cookie, X-API-Key, client_secret, access_token, refresh_token, session
Default allowed headers: Content-Type, Cache-Control, X-Request-ID, X-Correlation-ID, User-Agent, Accept
Error Handling
The logger handles errors internally and falls back to console.error if the transport fails. Custom error classes are exported for cases where you need to catch them explicitly:
import { ValidationError, SizeExceededError, TransportError } from 'lazy-logger';
try {
logger.logApiIncomingRequest({ /* ... */ });
} catch (error) {
if (error instanceof ValidationError) {
console.error('Validation failed:', error.field, error.message);
} else if (error instanceof SizeExceededError) {
console.error(`Record too large: ${error.actualSize} bytes (limit: ${error.sizeLimit})`);
} else if (error instanceof TransportError) {
console.error('Transport failed:', error.message);
}
}API Reference
new StructuredLogger(config)
| Option | Type | Default | Description |
|-------------------|------------------|--------------------|------------------------------------------|
| service | string | required | {env}/{domain}/{service} identifier |
| defaultSeverity | SeverityLevel | SeverityLevel.INFO | Fallback severity when not specified |
| maxRecordSize | number | 262144 (256KB) | Max log record size in bytes |
| maskingRules | MaskingConfig | masking enabled | PII masking configuration |
| transport | TransportConfig| console | Output transport configuration |
| retention | RetentionConfig| 30 days | Log retention policy |
Log methods
logger.logApiIncomingRequest(data, severity?)
logger.logApiOutgoingResponse(data, severity?) // auto-detects severity from response_status
logger.logApiExternalRequest(data, severity?)
logger.logApiExternalResponse(data, severity?) // auto-detects severity from response_status
logger.logTransaction(data, severity?)
logger.logAccess(data, severity?)
logger.logActivity(data, severity?)Utility methods
logger.generateRequestId(): string
logger.setRequestId(id: string): void
logger.getCurrentRequestId(): string | null
logger.clearRequestId(): void
logger.createChildRequestId(parentId?): { parent_request_id: string; child_request_id: string }
logger.filterHeaders(headers, options?): string // returns JSON string
logger.filterParameters(params, options?): string // returns JSON string
logger.getSeverityFromStatusCode(statusCode): SeverityLevel
logger.getStatusFromStatusCode(statusCode): Status
logger.getConfig(): LoggerConfig
logger.updateConfig(partial): voidLicense
MIT — see LICENSE for details.
Support
- Issues: GitLab Issues
- Repository: gitlab.com/lazy-playgroud/logger
Changelog
v1.0.0
- Initial release
- 7 structured log types
- Thai PDPA-compliant data masking
- Request correlation with UUID and child-request support
- Console, file, and network transports with retry logic
- Full TypeScript declarations
