Complete guide to configuring and using log levels in the DeployStack backend for development and production environments.
The DeployStack backend uses Pino logger with Fastify for high-performance, structured logging. This guide covers everything you need to know about configuring and using log levels effectively.
Overview
DeployStack’s logging system is built on industry best practices:
Pino Logger: Ultra-fast JSON logger for Node.js
Fastify Integration: Native logging support with request correlation
Environment-based Configuration: Automatic log level adjustment based on NODE_ENV
Structured Logging: JSON output for production, pretty-printed for development
Available Log Levels
Log levels are ordered by severity (lowest to highest):
Level
Numeric Value
Description
When to Use
trace
10
Very detailed debugging
Tracing function calls, variable states
debug
20
Debugging information
Development debugging, detailed flow
info
30
General information
Important events, startup messages
warn
40
Warning messages
Recoverable errors, deprecation notices
error
50
Error conditions
Caught exceptions, failed operations
fatal
60
Fatal errors
Unrecoverable errors, application crashes
Configuration
Environment Variables
Set the log level using the LOG_LEVEL environment variable:
# Development - show debug informationLOG_LEVEL=debug npm run dev# Production - show info and aboveLOG_LEVEL=info npm run start# Troubleshooting - show everythingLOG_LEVEL=trace npm run dev# Quiet mode - only errors and fatalLOG_LEVEL=error npm run start
Default Behavior
The logger automatically adjusts based on your environment:
[2025-07-03 10:48:06.636 +0200] INFO: ✅ Database initialization completed[2025-07-03 10:48:06.640 +0200] DEBUG: 🔄 Starting global settings initialization...[2025-07-03 10:48:06.645 +0200] ERROR: ❌ Failed to connect to external service
Production Format (JSON)
{"level":30,"time":"2025-07-03T08:48:06.636Z","pid":1234,"hostname":"server","msg":"Database initialization completed"}{"level":20,"time":"2025-07-03T08:48:06.640Z","pid":1234,"hostname":"server","msg":"Starting global settings initialization..."}{"level":50,"time":"2025-07-03T08:48:06.645Z","pid":1234,"hostname":"server","msg":"Failed to connect to external service"}
Logger Parameter Injection Pattern
DeployStack follows a consistent pattern for passing logger instances to services and utilities. This ensures proper structured logging throughout the application while maintaining the Fastify logger chain for request correlation.
// ✅ Good - Pass logger from server contextawait initializeDatabase(server.log);// ✅ Good - Pass logger from request context in routesserver.post('/api/send-email', async (request, reply) => { const result = await EmailService.sendEmail(emailOptions, request.log); return result;});// ✅ Good - Pass logger in plugin initializationawait pluginManager.initializePlugins(server.log);
✅ DO: Use Child Loggers for Persistent Context
// ✅ Good - Create child logger with persistent contextclass UserService { static async processUser(userId: string, logger: FastifyBaseLogger) { const childLogger = logger.child({ userId, service: 'UserService' }); childLogger.debug('Starting user processing'); childLogger.info('User data retrieved'); childLogger.debug('Processing completed'); }}
❌ DON’T: Create Separate Logger Utilities
// ❌ Bad - Don't create separate logger utility files// utils/logger.tsexport const logger = createLogger();// ❌ Bad - Don't import logger utilities in servicesimport { logger } from '../utils/logger';class SomeService { static async doSomething() { logger.info('This bypasses the Fastify logger chain'); }}
❌ DON’T: Use console.* in Services
// ❌ Bad - console.* bypasses the logging systemclass DatabaseService { static async connect() { console.log('Connecting to database...'); // No structured logging console.error('Connection failed:', error); // No context objects }}// ✅ Good - Use passed logger parameterclass DatabaseService { static async connect(logger: FastifyBaseLogger) { logger.info({ operation: 'database_connect' }, 'Connecting to database...'); logger.error({ operation: 'database_connect', error, connectionString: config.url }, 'Connection failed'); }}
Developer Best Practices
✅ DO: Use Proper Log Levels
// ✅ Good - Use appropriate log levelsserver.log.debug('🔄 Starting database initialization...');server.log.info('✅ Database connection established');server.log.warn('⚠️ Using fallback configuration');server.log.error('❌ Failed to process request:', error);server.log.fatal('💀 Critical system failure:', error);
❌ DON’T: Use Manual Prefixes
// ❌ Bad - Manual prefixes defeat the purposeserver.log.info('🔄 [DEBUG] Starting database initialization...');server.log.info('✅ [INFO] Database connection established');// ✅ Good - Use proper log levels insteadserver.log.debug('🔄 Starting database initialization...');server.log.info('✅ Database connection established');
✅ DO: Use the Fastify Logger
// ✅ Good - Use server.log for consistent formattingserver.log.info('User authenticated successfully');// ❌ Bad - console.log bypasses the logging systemconsole.log('User authenticated successfully');
✅ DO: Add Context Objects
Context objects make your logs searchable, filterable, and much more useful for debugging. Always include relevant context that helps identify what happened, where, and to whom.
// ✅ Good - Structured logging with contextserver.log.info({ userId: 'user123', action: 'login', ipAddress: '192.168.1.1', userAgent: 'Mozilla/5.0...', operation: 'user_authentication'}, 'User login successful');// ✅ Good - Error logging with full contextserver.log.error({ error: err, userId: 'user123', operation: 'database_query', table: 'users', queryType: 'SELECT'}, 'Database operation failed');// ✅ Good - Service operations with contextserver.log.debug({ recipient: 'user@example.com', template: 'welcome', messageId: 'abc123', operation: 'send_email'}, 'Email sent successfully');// ✅ Good - API operations with contextserver.log.warn({ endpoint: '/api/users', method: 'POST', statusCode: 429, clientIp: '192.168.1.1', operation: 'rate_limit_exceeded'}, 'Rate limit exceeded for client');
Best Practices for Context Objects:
Always include operation: A consistent field that describes what operation was being performed
Add identifiers: Include relevant IDs (userId, orderId, sessionId, etc.) for easy filtering
Include request context: IP addresses, user agents, request IDs for web requests
Add timing information: Duration, timestamps, or performance metrics when relevant
Use consistent naming: Stick to camelCase and consistent field names across your application
Examples of Good Context Properties:
operation: What was happening (e.g., ‘send_email’, ‘user_login’, ‘database_query’)
userId, sessionId, requestId: Identifiers for tracking