@breadstone/ziegel-platform-logging
Enterprise logging and diagnostics infrastructure for the ziegel platform. Provides decorator-based logging, multiple logger providers, structured logging, and comprehensive logging capabilities for enterprise applications.
Logging: Enterprise-grade logging with decorators, multiple providers, and structured output for comprehensive application diagnostics.
🚀 Overview
@breadstone/ziegel-platform-logging provides:
- Decorator-Based Logging: Automatic logging with method, class, and parameter decorators
- Multiple Logger Providers: Console, callback, and empty logger implementations
- Logger Factory: Centralized logger creation and management
- Structured Formatters: Array, object, and error formatters for structured output
- Log Levels: Configurable logging levels and filtering
- Logger Extensions: Enhanced logging capabilities and utilities
- Performance Logging: Method execution time tracking
📦 Installation
npm install @breadstone/ziegel-platform-logging
# or
yarn add @breadstone/ziegel-platform-logging🧩 Features & Usage Examples
Basic Logging
import { Logger, LoggerFactory, LogLevel } from '@breadstone/ziegel-platform-logging';
// Create logger via factory
const logger = LoggerFactory.createLogger('MyService');
// Log at different levels
logger.log(LogLevel.Debug, 'Debug information', { userId: '123' });
logger.log(LogLevel.Info, 'User logged in', { userId: '123', ip: '192.168.1.1' });
logger.log(LogLevel.Warning, 'Rate limit exceeded', { userId: '123', attempts: 5 });
logger.log(LogLevel.Error, 'Database connection failed', new Error('Connection timeout'));Logger Factory and Management
import { LoggerFactory, LoggerManager, ConsoleLoggerProvider } from '@breadstone/ziegel-platform-logging';
// Setup logger with provider
const consoleProvider = new ConsoleLoggerProvider();
LoggerFactory.setProvider(consoleProvider);
// Create loggers
const serviceLogger = LoggerFactory.createLogger('UserService');
const dbLogger = LoggerFactory.createLogger('DatabaseService');
// Manage loggers centrally
const loggerManager = new LoggerManager();
loggerManager.addLogger('user', serviceLogger);
loggerManager.addLogger('db', dbLogger);Decorator-Based Logging
import { LogClass, LogMethod, LogParameter, LogProperty } from '@breadstone/ziegel-platform-logging';
@LogClass('UserService')
class UserService {
@LogProperty
private connectionString: string = 'server=localhost';
@LogMethod
async getUser(@LogParameter id: string): Promise<User> {
// Method entry, parameters, and exit are automatically logged
const user = await this.userRepository.findById(id);
return user;
}
@LogMethod({ logLevel: LogLevel.Warning })
async deleteUser(@LogParameter id: string): Promise<void> {
// Custom log level for sensitive operations
await this.userRepository.delete(id);
}
}Custom Logger Providers
import { ILoggerProvider, ILogger, LogLevel } from '@breadstone/ziegel-platform-logging';
class DatabaseLoggerProvider implements ILoggerProvider {
constructor(private db: Database) {}
createLogger(name: string): ILogger {
return new DatabaseLogger(name, this.db);
}
}
class DatabaseLogger implements ILogger {
constructor(private name: string, private db: Database) {}
log(level: LogLevel, message: string, data?: any): void {
const logEntry = {
timestamp: new Date(),
level: LogLevel[level],
logger: this.name,
message,
data: data ? JSON.stringify(data) : null
};
this.db.query(
'INSERT INTO logs (timestamp, level, logger, message, data) VALUES (?, ?, ?, ?, ?)',
[logEntry.timestamp, logEntry.level, logEntry.logger, logEntry.message, logEntry.data]
);
}
}
// Register custom provider
LoggerFactory.setProvider(new DatabaseLoggerProvider(database));Callback-Based Logging
import { CallbackLoggerProvider, LogCallback, LogLevel } from '@breadstone/ziegel-platform-logging';
// Define callback for log handling
const logCallback: LogCallback = (level: LogLevel, message: string, data?: any) => {
// Send to multiple destinations
console.log(`[${LogLevel[level]}] ${message}`, data);
// Send to external service
fetch('/api/logs', {
method: 'POST',
body: JSON.stringify({
level: LogLevel[level],
message,
data,
timestamp: new Date().toISOString()
})
});
// Send to monitoring service
if (level >= LogLevel.Error) {
notificationService.sendAlert(message, data);
}
};
const callbackProvider = new CallbackLoggerProvider(logCallback);
LoggerFactory.setProvider(callbackProvider);Structured Logging with Formatters
import {
LogFormatters,
ArrayFormatter,
ObjectFormatter,
ErrorFormatter
} from '@breadstone/ziegel-platform-logging';
const logger = LoggerFactory.createLogger('StructuredService');
// Array formatting
const arrayFormatter = new ArrayFormatter();
logger.log(LogLevel.Info, 'Processing items', arrayFormatter.format([
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' }
]));
// Object formatting
const objectFormatter = new ObjectFormatter();
logger.log(LogLevel.Info, 'User data', objectFormatter.format({
user: { id: '123', name: 'John Doe' },
preferences: { theme: 'dark', notifications: true }
}));
// Error formatting
const errorFormatter = new ErrorFormatter();
try {
throw new Error('Something went wrong');
} catch (error) {
logger.log(LogLevel.Error, 'Operation failed', errorFormatter.format(error));
}
// Use built-in formatters
logger.log(LogLevel.Info, 'Formatted data', LogFormatters.formatObject(complexData));Logger Extensions
import { LoggerExtensions, Logger } from '@breadstone/ziegel-platform-logging';
const logger = LoggerFactory.createLogger('ExtendedService');
// Use extensions for enhanced logging
class EnhancedService {
private logger = LoggerFactory.createLogger('EnhancedService');
async processData(data: any[]): Promise<void> {
// Start timing
const timer = LoggerExtensions.startTimer(this.logger, 'Processing data');
try {
// Process data
for (const item of data) {
await this.processItem(item);
}
// Log success with timing
timer.end('Data processing completed successfully');
} catch (error) {
// Log error with timing
timer.end('Data processing failed', error);
throw error;
}
}
private async processItem(item: any): Promise<void> {
LoggerExtensions.logMethodEntry(this.logger, 'processItem', item);
// Process item logic
await new Promise(resolve => setTimeout(resolve, 100));
LoggerExtensions.logMethodExit(this.logger, 'processItem');
}
}📚 Package Exports
import {
// Decorators
LogClass,
Log,
LogMethod,
LogParameter,
LogProperty,
// Core Logging
Logger,
ILogger,
LogLevel,
LogCallback,
// Factory & Management
LoggerFactory,
ILoggerFactory,
LoggerManager,
// Logger Providers
ILoggerProvider,
CallbackLoggerProvider,
ConsoleLoggerProvider,
EmptyLoggerProvider,
// Logger Implementations
CallbackLogger,
ConsoleLogger,
EmptyLogger,
// Formatters
ILogFormatter,
LogFormatters,
ArrayFormatter,
ObjectFormatter,
ErrorFormatter,
// Extensions & Utilities
LoggerExtensions,
// Scopes
ConsoleLoggerScope,
EmptyLoggerScope
} from '@breadstone/ziegel-platform-logging';🔧 Advanced Usage
Performance Monitoring
import { LogMethod, LogClass, LogLevel } from '@breadstone/ziegel-platform-logging';
@LogClass('PerformanceService')
class PerformanceService {
@LogMethod({
logLevel: LogLevel.Info,
logExecutionTime: true,
logParameters: true,
logReturnValue: false
})
async heavyComputation(data: any[]): Promise<number> {
// Long running computation
return data.reduce((sum, item) => sum + item.value, 0);
}
@LogMethod({ logExecutionTime: true })
async databaseQuery(query: string): Promise<any[]> {
// Database operation with automatic timing
return await this.db.query(query);
}
}Conditional Logging
import { LoggerFactory, LogLevel } from '@breadstone/ziegel-platform-logging';
class ConditionalLoggingService {
private logger = LoggerFactory.createLogger('ConditionalService');
processUser(user: User): void {
// Only log debug info in development
if (process.env.NODE_ENV === 'development') {
this.logger.log(LogLevel.Debug, 'Processing user', { userId: user.id });
}
// Always log important operations
this.logger.log(LogLevel.Info, 'User processed', { userId: user.id });
// Log warnings for specific conditions
if (user.isExpired()) {
this.logger.log(LogLevel.Warning, 'Processing expired user', { userId: user.id });
}
}
}Multi-Provider Logging
import {
LoggerFactory,
ConsoleLoggerProvider,
CallbackLoggerProvider,
LogLevel
} from '@breadstone/ziegel-platform-logging';
class MultiProviderLogger implements ILogger {
private providers: ILogger[] = [];
constructor() {
// Add multiple providers
this.providers.push(
new ConsoleLoggerProvider().createLogger('MultiLogger'),
new CallbackLoggerProvider(this.sendToExternalService).createLogger('MultiLogger')
);
}
log(level: LogLevel, message: string, data?: any): void {
// Send to all providers
this.providers.forEach(provider => {
provider.log(level, message, data);
});
}
private sendToExternalService = (level: LogLevel, message: string, data?: any) => {
// Send to external logging service
fetch('/api/external-logs', {
method: 'POST',
body: JSON.stringify({ level: LogLevel[level], message, data })
});
};
}🎯 Integration Examples
Express.js Middleware
import express from 'express';
import { LoggerFactory, LogLevel } from '@breadstone/ziegel-platform-logging';
const logger = LoggerFactory.createLogger('ExpressApp');
// Logging middleware
const loggingMiddleware = (req: express.Request, res: express.Response, next: express.NextFunction) => {
const start = Date.now();
logger.log(LogLevel.Info, 'Request started', {
method: req.method,
url: req.url,
userAgent: req.get('User-Agent'),
ip: req.ip
});
res.on('finish', () => {
const duration = Date.now() - start;
logger.log(LogLevel.Info, 'Request completed', {
method: req.method,
url: req.url,
statusCode: res.statusCode,
duration: `${duration}ms`
});
});
next();
};
app.use(loggingMiddleware);React Error Boundary
import React, { Component, ErrorInfo, ReactNode } from 'react';
import { LoggerFactory, LogLevel } from '@breadstone/ziegel-platform-logging';
interface Props {
children: ReactNode;
}
interface State {
hasError: boolean;
}
class ErrorBoundary extends Component<Props, State> {
private logger = LoggerFactory.createLogger('ErrorBoundary');
constructor(props: Props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(_: Error): State {
return { hasError: true };
}
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
this.logger.log(LogLevel.Error, 'React component error', {
error: error.message,
stack: error.stack,
componentStack: errorInfo.componentStack,
timestamp: new Date().toISOString()
});
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}📚 API Documentation
For detailed API documentation, visit: API Docs
Related Packages
- @breadstone/ziegel-platform: Core platform services
- @breadstone/ziegel-core: Foundation utilities
- @breadstone/ziegel-platform-analytics: Analytics and tracking
License
MIT
Issues
Please report bugs and feature requests in the Issue Tracker
Part of the ziegel Enterprise TypeScript Framework import { CorrelationLogger, RequestContext } from '@ziegel/platform-logging';
const correlationLogger = new CorrelationLogger();
// Middleware for Express.js app.use((req, res, next) => { const correlationId = req.headers['x-correlation-id'] || generateId();
RequestContext.run({ correlationId, requestId: generateId() }, () => { correlationLogger.info('Request started', { method: req.method, path: req.path, correlationId });
next();
}); });
// All logs within request context automatically include correlation ID function processUser(userData) { correlationLogger.info('Processing user data', { userId: userData.id }); // This log will include the correlation ID from the request context }
### Performance Profiling
```typescript
import { PerformanceLogger, ProfiledLogger } from '@ziegel/platform-logging';
const perfLogger = new PerformanceLogger();
// Automatic timing
const timedOperation = perfLogger.time('database-query');
const result = await database.query('SELECT * FROM users');
timedOperation.end({ rowCount: result.length });
// Method profiling
class UserService {
@ProfiledLogger('user-service')
async getUser(id: string): Promise<User> {
// Method execution time is automatically logged
return await this.userRepository.findById(id);
}
}
// Memory usage tracking
perfLogger.trackMemory('application-start', {
heapUsed: process.memoryUsage().heapUsed,
heapTotal: process.memoryUsage().heapTotal
});Distributed Tracing Integration
import { TracingLogger, TraceContext } from '@ziegel/platform-logging';
const tracingLogger = new TracingLogger({
serviceName: 'user-service',
traceIdHeader: 'x-trace-id',
spanIdHeader: 'x-span-id'
});
// Integrate with OpenTelemetry or similar
function processRequest(req, res) {
const traceContext = TraceContext.fromHeaders(req.headers);
tracingLogger.startSpan('process-request', traceContext, () => {
tracingLogger.info('Request processing started');
// Nested spans
tracingLogger.startSpan('database-call', () => {
database.query('SELECT ...');
});
tracingLogger.startSpan('external-api-call', () => {
externalAPI.call();
});
});
}Error Aggregation and Alerting
import { ErrorLogger, AlertManager } from '@ziegel/platform-logging';
const errorLogger = new ErrorLogger();
const alertManager = new AlertManager({
thresholds: {
errorRate: 0.05, // 5% error rate
criticalErrors: 1, // Any critical error
responseTime: 5000 // 5 second response time
},
notificationChannels: ['email', 'slack', 'pagerduty']
});
// Enhanced error logging
errorLogger.error('Database connection failed', {
error: dbError,
severity: 'critical',
category: 'infrastructure',
tags: ['database', 'connection'],
context: {
operation: 'user-fetch',
retryAttempt: 3,
lastSuccessfulConnection: lastConnTime
}
});
// Automatic alerting based on error patterns
errorLogger.onErrorPattern({
pattern: { category: 'critical', count: 1 },
timeWindow: '5m',
action: (errors) => {
alertManager.sendAlert('critical-error', {
errors,
service: 'user-service'
});
}
});Multiple Transports
File Transport
import { FileTransport, RotatingFileTransport } from '@ziegel/platform-logging';
// Basic file logging
const fileTransport = new FileTransport({
filename: './logs/application.log',
maxFileSize: '50MB',
format: 'json'
});
// Rotating file logs
const rotatingTransport = new RotatingFileTransport({
filename: './logs/app-%DATE%.log',
datePattern: 'YYYY-MM-DD',
maxFiles: 30,
maxSize: '100MB',
compress: true
});
logger.addTransport(fileTransport);
logger.addTransport(rotatingTransport);Database Transport
import { DatabaseTransport } from '@ziegel/platform-logging';
const dbTransport = new DatabaseTransport({
connectionString: 'postgresql://...',
tableName: 'application_logs',
batchSize: 100,
flushInterval: 5000,
schema: {
timestamp: 'TIMESTAMP',
level: 'VARCHAR(10)',
message: 'TEXT',
metadata: 'JSONB',
correlationId: 'VARCHAR(36)'
}
});
logger.addTransport(dbTransport);Remote Transport
import { HTTPTransport, ElasticsearchTransport } from '@ziegel/platform-logging';
// HTTP endpoint
const httpTransport = new HTTPTransport({
url: 'https://logs.yourcompany.com/api/logs',
headers: {
'Authorization': 'Bearer your-token',
'Content-Type': 'application/json'
},
batchSize: 50,
retryAttempts: 3
});
// Elasticsearch
const elasticTransport = new ElasticsearchTransport({
node: 'https://elasticsearch.yourcompany.com',
index: 'application-logs',
auth: {
username: 'elastic',
password: 'password'
},
mappings: {
properties: {
timestamp: { type: 'date' },
level: { type: 'keyword' },
message: { type: 'text' },
metadata: { type: 'object' }
}
}
});
logger.addTransport(httpTransport);
logger.addTransport(elasticTransport);Custom Transport
import { BaseTransport, LogEntry } from '@ziegel/platform-logging';
class SlackTransport extends BaseTransport {
constructor(private webhookUrl: string) {
super();
}
async write(entry: LogEntry): Promise<void> {
if (entry.level === 'error' || entry.level === 'fatal') {
const slackMessage = {
text: `🚨 ${entry.level.toUpperCase()}: ${entry.message}`,
attachments: [{
color: 'danger',
fields: [{
title: 'Metadata',
value: JSON.stringify(entry.metadata, null, 2)
}]
}]
};
await fetch(this.webhookUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(slackMessage)
});
}
}
}
logger.addTransport(new SlackTransport('https://hooks.slack.com/...'));Structured Logging
Log Formatting
import { JsonFormatter, TextFormatter, CustomFormatter } from '@ziegel/platform-logging';
// JSON formatter
const jsonFormatter = new JsonFormatter({
timestamp: true,
prettyPrint: false,
includeStack: true
});
// Text formatter
const textFormatter = new TextFormatter({
template: '${timestamp} [${level}] ${service}: ${message} ${metadata}',
colorize: true,
timestamp: 'YYYY-MM-DD HH:mm:ss'
});
// Custom formatter
const customFormatter = new CustomFormatter((entry) => {
return `${entry.timestamp} | ${entry.level.toUpperCase()} | ${entry.message}` +
(entry.metadata ? ` | ${JSON.stringify(entry.metadata)}` : '');
});
logger.setFormatter(jsonFormatter);Log Enrichment
import { LogEnricher } from '@ziegel/platform-logging';
const enricher = new LogEnricher({
enrichers: [
// Add system information
(entry) => ({
...entry,
hostname: os.hostname(),
pid: process.pid,
nodeVersion: process.version
}),
// Add request information (if available)
(entry) => {
const requestContext = RequestContext.get();
if (requestContext) {
return {
...entry,
correlationId: requestContext.correlationId,
requestId: requestContext.requestId,
userId: requestContext.userId
};
}
return entry;
},
// Add application version
(entry) => ({
...entry,
appVersion: process.env.APP_VERSION || 'unknown'
})
]
});
logger.addEnricher(enricher);Security and Compliance
Sensitive Data Filtering
import { SensitiveDataFilter } from '@ziegel/platform-logging';
const sensitiveFilter = new SensitiveDataFilter({
patterns: [
/\b\d{4}\s?\d{4}\s?\d{4}\s?\d{4}\b/, // Credit card numbers
/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/, // Email addresses
/\b\d{3}-\d{2}-\d{4}\b/, // SSN
/password|secret|token|key/i // Common sensitive field names
],
replacement: '[REDACTED]',
preserveStructure: true
});
logger.addFilter(sensitiveFilter);
// Logs will automatically redact sensitive information
log.info('User payment', {
userId: '123',
creditCard: '4111 1111 1111 1111', // Will be redacted
email: 'user@example.com' // Will be redacted
});Audit Logging
import { AuditLogger } from '@ziegel/platform-logging';
const auditLogger = new AuditLogger({
requiredFields: ['userId', 'action', 'resource', 'timestamp'],
immutable: true, // Prevent log modification
signing: {
enabled: true,
algorithm: 'RS256',
privateKey: privateKey
}
});
// Audit trail logging
auditLogger.audit('user.login', {
userId: '123',
action: 'login',
resource: 'authentication',
result: 'success',
metadata: {
ipAddress: '192.168.1.1',
userAgent: 'Mozilla/5.0...'
}
});
auditLogger.audit('data.access', {
userId: '123',
action: 'read',
resource: 'customer-data',
resourceId: 'customer-456',
result: 'success'
});Performance Optimization
Asynchronous Logging
import { AsyncLogger } from '@ziegel/platform-logging';
const asyncLogger = new AsyncLogger({
bufferSize: 1000,
flushInterval: 5000,
backpressureThreshold: 10000,
onBackpressure: 'drop-oldest' // or 'block', 'drop-newest'
});
// Non-blocking log operations
asyncLogger.info('High-frequency log message');
// Returns immediately, actual logging happens asynchronouslyLog Sampling
import { SamplingLogger } from '@ziegel/platform-logging';
const samplingLogger = new SamplingLogger({
sampleRate: 0.1, // Log 10% of messages
priorityLevels: ['error', 'fatal'], // Always log errors
adaptiveSampling: {
enabled: true,
increaseOnErrors: true,
maxSampleRate: 1.0
}
});
// Reduces log volume while maintaining error visibility
samplingLogger.info('Debug information'); // May be sampled
samplingLogger.error('Critical error'); // Always loggedConditional Logging
import { ConditionalLogger } from '@ziegel/platform-logging';
const conditionalLogger = new ConditionalLogger({
conditions: [
{
name: 'debug-mode',
condition: () => process.env.NODE_ENV === 'development',
levels: ['debug', 'trace']
},
{
name: 'production-errors',
condition: () => process.env.NODE_ENV === 'production',
levels: ['error', 'fatal']
}
]
});
// Only logs based on environment and conditions
conditionalLogger.debug('Development debug info'); // Only in development
conditionalLogger.error('Production error'); // Always loggedIntegration Examples
Express.js Middleware
import { createLoggingMiddleware } from '@ziegel/platform-logging/express';
const loggingMiddleware = createLoggingMiddleware({
logger: logger,
logRequests: true,
logResponses: true,
logBody: false, // Don't log request body for security
excludePaths: ['/health', '/metrics'],
enrichRequest: (req) => ({
userAgent: req.get('user-agent'),
realIp: req.get('x-real-ip') || req.ip
})
});
app.use(loggingMiddleware);Error Handling Integration
import { ErrorLoggingHandler } from '@ziegel/platform-logging';
const errorHandler = new ErrorLoggingHandler({
logger: logger,
includeStackTrace: true,
logUncaughtExceptions: true,
logUnhandledRejections: true
});
// Global error handlers
process.on('uncaughtException', errorHandler.handleUncaughtException);
process.on('unhandledRejection', errorHandler.handleUnhandledRejection);
// Express error middleware
app.use(errorHandler.expressMiddleware());Microservice Communication
import { ServiceLogger } from '@ziegel/platform-logging';
class UserService {
private logger = new ServiceLogger('user-service');
async createUser(userData: CreateUserRequest): Promise<User> {
const operationId = generateId();
this.logger.info('User creation started', {
operationId,
userData: { email: userData.email } // Don't log sensitive data
});
try {
const user = await this.userRepository.create(userData);
this.logger.info('User creation completed', {
operationId,
userId: user.id,
duration: performance.now() - startTime
});
return user;
} catch (error) {
this.logger.error('User creation failed', {
operationId,
error,
userData: { email: userData.email }
});
throw error;
}
}
}Configuration
Logger Configuration
interface LoggerConfig {
level: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';
format: 'json' | 'text' | 'combined';
transports: TransportConfig[];
enrichers: EnricherConfig[];
filters: FilterConfig[];
performance: {
async: boolean;
bufferSize: number;
flushInterval: number;
};
security: {
enableSensitiveDataFiltering: boolean;
auditMode: boolean;
signLogs: boolean;
};
}Production Configuration
const productionConfig: LoggerConfig = {
level: 'info',
format: 'json',
transports: [
{
type: 'rotating-file',
filename: './logs/app-%DATE%.log',
maxFiles: 30,
maxSize: '100MB'
},
{
type: 'elasticsearch',
node: process.env.ELASTICSEARCH_URL,
index: 'application-logs'
}
],
enrichers: [
'system-info',
'request-context',
'application-version'
],
filters: [
'sensitive-data'
],
performance: {
async: true,
bufferSize: 1000,
flushInterval: 5000
},
security: {
enableSensitiveDataFiltering: true,
auditMode: true,
signLogs: false
}
};Best Practices
Structured Logging Best Practices
// Good: Structured data with consistent fields
log.info('User action completed', {
userId: '123',
action: 'purchase',
productId: 'prod-456',
amount: 29.99,
currency: 'USD',
timestamp: new Date().toISOString()
});
// Avoid: String concatenation
log.info(`User ${userId} purchased product ${productId} for $${amount}`);Error Logging Best Practices
// Good: Include context and error details
try {
await processPayment(paymentData);
} catch (error) {
log.error('Payment processing failed', {
error: {
message: error.message,
stack: error.stack,
code: error.code
},
context: {
userId: paymentData.userId,
amount: paymentData.amount,
paymentMethod: paymentData.method
},
correlation: {
requestId: getCurrentRequestId(),
sessionId: getCurrentSessionId()
}
});
throw error;
}Performance Considerations
// Use appropriate log levels
log.debug('Detailed debug information'); // Development only
log.info('Important business events'); // Production
log.warn('Potential issues'); // Always important
log.error('Actual errors'); // Critical for monitoring
// Avoid expensive operations in log statements
log.debug('User data', {
user: expensiveUserDataComputation() // ❌ Computed even if debug disabled
});
// Use lazy evaluation
log.debug('User data', () => ({
user: expensiveUserDataComputation() // ✅ Only computed if debug enabled
}));Migration Guide
From winston
// Before (winston)
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
// After (ziegel-platform-logging)
import { Logger } from '@ziegel/platform-logging';
const logger = new Logger({
level: 'info',
format: 'json',
transports: [
{ type: 'file', filename: 'error.log', level: 'error' },
{ type: 'file', filename: 'combined.log' }
]
});From console.log
// Before
console.log('User logged in:', { userId: '123', email: 'user@example.com' });
console.error('Error occurred:', error);
// After
import { log } from '@ziegel/platform-logging';
log.info('User logged in', { userId: '123', email: 'user@example.com' });
log.error('Error occurred', { error });API Reference
For complete API documentation, see the API Reference.
Related Packages
ziegel-platform- Core platform servicesziegel-platform-analytics- Analytics and monitoring