1.0.0 β€’ Published 3 months ago

@treeimmersion/logging v1.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
3 months ago

@treeimmersion/logging

@treeimmersion/logging is a lightweight and flexible logging library for Node.js applications, built on top of Pino. It provides structured logging, error tracking, and optimized integration with Datadog to enhance application observability.

Features

  • πŸš€ Lightweight & Fast: Built on Pino, ensuring high performance with minimal resource consumption.
  • πŸ“Š Structured Logging: Enhances traceability and analysis with well-organized logs.
  • πŸ”§ Adaptive Configuration: Automatically adjusts log formats based on the environment (development or production).
  • πŸ“‘ Datadog Integration: Tags active spans with relevant error and stack trace information.
  • 🎨 Customizable Format: Allows inclusion of specific metadata on operations and states.

Installation

Install the library via npm:

npm install @treeimmersion/logging

Usage

Available Methods

The logger provides three primary methods (info, error, debug), each requiring the following parameters:

  1. message (string): Main log message.
  2. operation (string): Name of the ongoing operation.
  3. status (string): Operation status (success, failure, etc.).
  4. meta (LogMeta | LogError): Additional data providing operation context.

Example: Logging Information

import logger from '@treeimmersion/logging';

logger.info('Operation completed', 'register', 'success', {
  username: 'tm2600',
  name: 'TM 2600',
  role: 'admin',
});

Example: Logging Errors

The logger automatically captures error messages and stack traces:

try {
  throw new Error('Not found');
} catch (error) {
  logger.error('Record not found', 'searchUser', 'failure', {
    error,
    username: 'tm2600',
    role: 'admin',
  });
}

Configuration

Automatic Mode Based on Environment

  • Development Mode: Uses pino-pretty for more readable logs.
  • Production Mode: Emits logs in JSON format, ideal for tools like Datadog or ELK.

Advanced Configuration in config.ts

Modify the default logger settings, such as log level and output format, in the config.ts file.

export const LOG_LEVEL = process.env.LOG_LEVEL || 'info';
export const LOG_FORMAT = process.env.LOG_FORMAT || 'json';

Customizing Log Format in formatters.ts

The formatters.ts file allows modifications to log structure. For example, you can add custom timestamps or change the output format.

export const formatLog = (message: string, level: string) => {
  return `${new Date().toISOString()} [${level.toUpperCase()}]: ${message}`;
};

Datadog APM Integration

If an active span is detected in Datadog, captured errors are automatically tagged:

import tracer from 'dd-trace';
import logger from '@treeimmersion/logging';

try {
  throw new Error('Service failure');
} catch (error) {
  const span = tracer.scope().active();
  logger.error('Request error', 'service_request', 'failure', { error });

  if (span) {
    span.setTag('error.message', error.message);
    span.setTag('error.stack', error.stack);
  }
}

Setting Log Levels

Define the logging level using the LOG_LEVEL environment variable:

LOG_LEVEL=debug node app.js

Full Example with Express

import express from 'express';
import logger from '@treeimmersion/logging';

const app = express();
app.use(express.json());

app.post('/register', (req, res) => {
  const { username, name, role } = req.body;
  try {
    const result = { enable: true, success: true };
    logger.info('Register successful', 'register', 'success', { username, name, role, result });
    res.status(200).json(result);
  } catch (error) {
    logger.error('Register failed', 'register', 'failure', { error, username, name, role });
    res.status(500).json({ message: 'Register error' });
  }
});

app.listen(3000, () => {
  logger.info('Server running on port 3000', 'server_start', 'success');
});

Unit Testing

The logger.test.ts file contains tests to verify the logger’s functionality. Run tests with:

npm test

Example unit test:

test('Should log an info message', () => {
  const logSpy = jest.spyOn(console, 'log');
  logger.info('Test message', 'test_operation', 'success');
  expect(logSpy).toHaveBeenCalled();
  logSpy.mockRestore();
});

Custom Types

  • LogMeta: Defines additional metadata for logs.
  • LogError: Extends LogMeta, including an error field of role Error.
export interface LogMeta {
  [key: string]: any;
}

export interface LogError extends LogMeta {
  error: Error;
}

Best Logging Practices

  • Use info for normal events and error only for actual failures.
  • Add key metadata to improve traceability.
  • Avoid logging sensitive data.

Contributing

Contributions are welcome! To contribute:

  1. Create a branch for your feature or fix.
  2. Write tests for your changes.
  3. Submit a pull request with a clear description of modifications.

πŸ“Œ Note: Follow structured logging best practices to maintain high-quality code and observability. πŸš€