@unidev-hub/logger
TypeScript icon, indicating that this package has built-in type declarations

1.0.2 • Public • Published

@unidev-hub/logger

A standardized logging package for TypeScript microservices, built on top of Pino.

Features

  • 🚀 High-performance logging using Pino
  • 🔍 Request ID tracking for service correlation
  • 🌐 Express middleware for request/response logging
  • 🛡️ Consistent error logging format
  • 🧩 Contextual child loggers

Installation

npm install @unidev-hub/logger

Usage

Basic Usage

import { createLogger } from '@unidev-hub/logger';

const logger = createLogger({
  serviceName: 'user-service',
  level: 'info',
  prettyPrint: process.env.NODE_ENV === 'development'
});

logger.info('Server started', { port: 3000 });
logger.error('Failed to connect to database', new Error('Connection timeout'));
// Or with additional context
logger.error('Failed to connect to database', new Error('Connection timeout'), { host: 'db-server-1' });

With Express

import express from 'express';
import { createLogger, createRequestLogger, getRequestLogger } from '@unidev-hub/logger';

const app = express();
const logger = createLogger({ serviceName: 'api-gateway' });

// Apply middleware
app.use(createRequestLogger(logger, {
  getUserId: (req) => req.user?.id,
  skipPaths: ['/health', '/metrics']
}));

// Use in route handlers
app.get('/users', (req, res) => {
  const requestLogger = getRequestLogger(req);
  
  requestLogger.info('Fetching users');
  
  // Your logic here
  
  res.json({ users: [] });
});

app.listen(3000, () => {
  logger.info('Server started', { port: 3000 });
});

Error Logging

// With Error object
logger.error('Failed to connect to database', new Error('Connection timeout'));

// With context object
logger.error('User validation failed', { userId: '123', reason: 'Invalid email' });

// With both Error and additional context
logger.error('Payment processing failed', new Error('Gateway timeout'), { orderId: 'ORD-123' });

Child Loggers

function processOrder(orderId: string, userId: string) {
  const orderLogger = logger.child({ orderId, userId });
  
  orderLogger.info('Processing order');
  
  // All logs from this logger will include orderId and userId
  orderLogger.debug('Validating payment');
  orderLogger.info('Order processed successfully');
}

Configuration

The logger accepts the following configuration options:

Option Type Description Default
serviceName string Name of the service Required
level string Minimum log level 'info' or LOG_LEVEL env var
prettyPrint boolean Format logs for human readability true in development
environment string Environment name NODE_ENV or 'development'
additionalFields object Extra fields to add to all logs {}

Request Logger Middleware Options

Option Type Description Default
getUserId Function Extract user ID from request undefined
logRequestBody boolean Include request body in logs false
logResponseBody boolean Include response body in logs false
skipPaths string[] Paths to exclude from logging []

Best Practices

  1. Use child loggers to add context to related log entries
  2. Include error objects in error logs for stack traces
  3. Use appropriate log levels:
    • trace: Very detailed debugging
    • debug: Debugging information
    • info: Normal operations
    • warn: Warning conditions
    • error: Error conditions
    • fatal: Critical failures

License

MIT

Package Sidebar

Install

npm i @unidev-hub/logger

Weekly Downloads

27

Version

1.0.2

License

MIT

Unpacked Size

46.8 kB

Total Files

8

Last publish

Collaborators

  • mayu03
  • samyak1988