Logging
Logging
Section titled “Logging”Learn how to implement structured logging in your Veloce-TS applications using Pino, one of the fastest loggers for Node.js.
Overview
Section titled “Overview”Veloce-TS provides built-in logging with:
- Pino Integration - Fast, structured JSON logging
- Child Loggers - Contextual logging with inheritance
- Log Levels - trace, debug, info, warn, error, fatal
- Request ID Integration - Automatic request tracking
- Pretty Printing - Human-readable logs in development
Quick Start
Section titled “Quick Start”import { getLogger } from 'veloce-ts';
const logger = getLogger();
logger.info('Application started');logger.error('Something went wrong', new Error('Error details'));Configuration
Section titled “Configuration”Initialize Logger
Section titled “Initialize Logger”import { initializeLogger } from 'veloce-ts';
// Development - Pretty printinginitializeLogger({ level: 'debug', pretty: true});
// Production - JSON outputinitializeLogger({ level: 'info', pretty: false});Get Logger Instance
Section titled “Get Logger Instance”import { getLogger } from 'veloce-ts';
const logger = getLogger();Log Levels
Section titled “Log Levels”logger.trace('Very detailed information');logger.debug('Debug information');logger.info('General information');logger.warn('Warning message');logger.error('Error occurred', error);logger.fatal('Fatal error', error);Child Loggers
Section titled “Child Loggers”Create contextual loggers:
// In controller@Controller('/users')class UserController { private logger = getLogger().child({ component: 'UserController' });
@Get('/:id') async getUser(@Param('id') id: string, @RequestId() requestId: string) { const logger = this.logger.child({ requestId, userId: id });
logger.info('Fetching user'); // ... logic logger.info('User fetched successfully'); }}Structured Logging
Section titled “Structured Logging”logger.info({ userId: '123', action: 'login', ip: '192.168.1.1'}, 'User logged in');
// Output (JSON):// {// "level": 30,// "time": 1234567890,// "userId": "123",// "action": "login",// "ip": "192.168.1.1",// "msg": "User logged in"// }Request ID Integration
Section titled “Request ID Integration”With request context middleware, request ID automatically appears in logs:
app.use(createRequestContextMiddleware({ logging: true }));
@Get('/data')async getData(@RequestId() requestId: string) { logger.info('Processing request'); // Includes requestId automatically}Best Practices
Section titled “Best Practices”1. Use Child Loggers
Section titled “1. Use Child Loggers”// Goodconst logger = getLogger().child({ component: 'Service' });
// Betterconst logger = getLogger().child({ component: 'UserService', version: '1.0'});2. Include Context
Section titled “2. Include Context”logger.info({ userId, action: 'update' }, 'User updated');3. Log Errors Properly
Section titled “3. Log Errors Properly”try { await riskyOperation();} catch (error) { logger.error({ error, userId }, 'Operation failed'); throw error;}Complete Example
Section titled “Complete Example”import { VeloceTS, getLogger, initializeLogger, createRequestContextMiddleware} from 'veloce-ts';
// InitializeinitializeLogger({ level: process.env.LOG_LEVEL || 'info', pretty: process.env.NODE_ENV !== 'production'});
const app = new VeloceTS();app.use(createRequestContextMiddleware({ logging: true }));
@Controller('/api')class ApiController { private logger = getLogger().child({ component: 'ApiController' });
@Get('/data') async getData(@RequestId() requestId: string) { this.logger.info({ requestId }, 'Fetching data');
try { const data = await fetchData(); this.logger.info({ requestId, count: data.length }, 'Data fetched'); return data; } catch (error) { this.logger.error({ requestId, error }, 'Failed to fetch data'); throw error; } }}Next Steps
Section titled “Next Steps”- Learn about Request Context for request tracking
- Explore Caching for performance optimization