eap-standard-logger
v2.0.0
Published
Standard logging library for EAP (Enterprise Application Platform)
Maintainers
Readme
EAP Internal Library Template
Enterprise Application Platform (EAP) standardized logging implementation.
🚀 Quick Installation
Option 1: CLI Installer (Easiest)
# Complete installation (all files + dependencies)
npx eap-standard-logger install
# Or using npm scripts (if in this repo)
npm run eap-logger:installSee CLI_GUIDE.md for complete CLI documentation.
Option 2: Manual Installation
# 1. Copy the logger
cp src/utils/logger.ts your-project/src/utils/
# 2. Install dependencies
npm install pino pino-prettyHow to Log
This project uses Pino as the standard logging library, wrapped in a consistent interface for all EAP services.
Why Pino?
- Performance: 5x faster than Winston (50,000+ logs/second)
- JSON-First: Structured logging by default
- Low Overhead: 2-4% CPU usage, minimal memory footprint
- Production-Ready: Used by major companies, excellent observability integration
Quick Start
1. Install Dependencies
npm install pino
# For development (pretty printing)
npm install --save-dev pino-pretty
# Optional: For Express.js example
npm install express uuid
npm install --save-dev @types/express @types/uuid2. Import and Use
import { createLogger } from './src/utils/logger';
// Create a logger for your service
const logger = createLogger({
service: 'user-service',
env: process.env.NODE_ENV,
version: process.env.SERVICE_VERSION,
});
// Log messages
logger.info('Service started');
logger.info({ port: 3000 }, 'Server listening on port');Basic Usage
Simple Logging
// String only
logger.info('User logged in');
// Object with message
logger.info({ userId: '123', action: 'login' }, 'User logged in');
// Different log levels
logger.debug('Debugging information');
logger.info('General information');
logger.warn('Warning condition');
logger.error('Error occurred');
logger.fatal('Fatal error - process should terminate');Error Logging
try {
// some operation
} catch (error) {
// Always include error object
logger.error({ err: error }, 'Operation failed');
// Pino automatically extracts stack trace
}Performance Logging
const start = Date.now();
await someOperation();
logger.info({ duration: Date.now() - start }, 'Operation completed');Child Loggers with TraceId
Create child loggers to automatically include context (like traceId) in all logs:
Express Middleware Example
import { v4 as uuidv4 } from 'uuid';
// Add logger to request
app.use((req, res, next) => {
const traceId = req.headers['x-trace-id'] || uuidv4();
// Create child logger with traceId
req.logger = logger.createChild({
traceId,
method: req.method,
path: req.path,
});
req.logger.info('Request received');
next();
});
// Use in route handlers
app.get('/users/:id', async (req, res) => {
req.logger.info({ userId: req.params.id }, 'Fetching user');
try {
const user = await getUser(req.params.id);
req.logger.info({ userId: user.id }, 'User fetched successfully');
res.json(user);
} catch (error) {
req.logger.error({ err: error }, 'Failed to fetch user');
res.status(500).json({ error: 'Internal server error' });
}
});All logs within that request will automatically include the traceId, making it easy to trace requests across services.
Configuration
Environment Variables
# Set log level
LOG_LEVEL=info # Options: trace, debug, info, warn, error, fatal
# Service information
SERVICE_NAME=user-service
SERVICE_VERSION=1.2.3
NODE_ENV=production # 'development' enables pretty printingCustom Configuration
const logger = createLogger({
service: 'payment-service',
env: 'production',
version: '2.1.0',
level: 'info',
// Redact sensitive fields
redact: ['password', 'creditCard', 'ssn'],
// Add custom fields to all logs
customFields: {
region: 'us-east-1',
datacenter: 'dc1',
},
});Log Levels
| Level | Value | Description | When to Use |
|-------|-------|-------------|-------------|
| fatal | 60 | Process cannot continue | Unrecoverable errors, process should exit |
| error | 50 | Error occurred | Errors that are handled but need attention |
| warn | 40 | Warning condition | Deprecated features, unusual but not errors |
| info | 30 | General information | Default - Normal app behavior, important events |
| debug | 20 | Debug information | Development debugging, detailed flow |
| trace | 10 | Very detailed | Very verbose, trace execution path |
Production Recommendation: Use info or higher. Enable debug only when investigating issues.
Output Format
Development (Pretty Printed)
When NODE_ENV=development:
[14:23:45.123] INFO [user-service]: User logged in
userId: "123"
action: "login"Production (JSON)
When NODE_ENV=production:
{
"level": 30,
"time": "2026-02-02T14:23:45.123Z",
"pid": 12345,
"hostname": "server-01",
"service": "user-service",
"env": "production",
"version": "1.2.3",
"userId": "123",
"action": "login",
"msg": "User logged in"
}Best Practices
✅ DO
// Use structured logging
logger.info({ userId, orderId, amount }, 'Order created');
// Include error objects
logger.error({ err: error }, 'Payment processing failed');
// Use child loggers for context
const requestLogger = logger.createChild({ traceId: req.id });
// Log operation metrics
logger.info({ duration: 234, status: 'success' }, 'API call completed');
// Use appropriate log levels
logger.warn('API rate limit approaching');❌ DON'T
// Don't use console.log
console.log('User logged in'); // ❌
// Don't concatenate strings
logger.info('User ' + userId + ' logged in'); // ❌
// Don't log sensitive data without redaction
logger.info({ password: 'secret123' }, 'Login attempt'); // ❌
// Don't overuse debug/trace in production
logger.debug('Variable x is now ' + x); // ❌ in productionIntegration with Observability Tools
The JSON output integrates seamlessly with:
- Elasticsearch + Kibana: Direct JSON ingestion and querying
- Grafana Loki: Log aggregation and visualization
- Datadog: APM and log correlation
- AWS CloudWatch: Native AWS integration
- Splunk: Enterprise log management
Testing Logs
import { createLogger } from './logger';
describe('Logger', () => {
it('should create logger with service name', () => {
const logger = createLogger({
service: 'test-service',
env: 'test',
});
// Capture logs for testing
const logs: any[] = [];
logger.getPinoInstance().on('data', (log) => logs.push(log));
logger.info({ userId: '123' }, 'Test message');
expect(logs[0].service).toBe('test-service');
expect(logs[0].msg).toBe('Test message');
});
});Troubleshooting
Logs not appearing
- Check
LOG_LEVELenvironment variable - Verify logger is configured correctly
- Check stdout redirection
Pretty printing not working in development
npm install --save-dev pino-prettyToo many logs in production
- Increase log level:
LOG_LEVEL=warn - Review debug/trace usage
- Use log sampling for high-frequency events
Advanced Usage
Custom Serializers
const logger = createLogger({
service: 'my-service',
customFields: {
// Custom serializer for BigInt
serializers: {
bigint: (value: bigint) => value.toString(),
},
},
});Multiple Destinations (Advanced)
For advanced use cases requiring multiple destinations, use Pino transports:
import pino from 'pino';
const logger = pino({
transport: {
targets: [
{ target: 'pino-pretty', level: 'info' },
{ target: 'pino/file', options: { destination: './app.log' }, level: 'error' },
],
},
});Migration from Console.log
Replace all console.log, console.error, etc. with the logger:
// Before
console.log('User logged in:', userId);
console.error('Error:', error);
// After
logger.info({ userId }, 'User logged in');
logger.error({ err: error }, 'Error occurred');Support
For questions or issues with the logging implementation:
- Check this README
- Review Pino documentation
- Consult the research document:
LOGGING_RESEARCH.md - Contact the Platform Team
Package.json Scripts
Add these helpful scripts:
{
"scripts": {
"dev": "NODE_ENV=development ts-node src/index.ts",
"start": "NODE_ENV=production node dist/index.js",
"logs:pretty": "pino-pretty < logs/app.log"
}
}Last Updated: February 2, 2026
Library: Pino v9.x
Maintained By: Platform Team
