npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@nicollasfrazao/liguelead-log-service

v2.2.0-6

Published

A standalone logging service for Express applications with multi-destination storage (local files + S3 via Kinesis Firehose) and comprehensive request tracking using strategy pattern.

Readme

Log Service Node.js

npm version Node.js TypeScript License: ISC

Serviço de logging standalone para aplicações Express com armazenamento multi-destino (arquivos locais + S3 via Kinesis Firehose) e rastreamento abrangente de requisições.

✨ Features

  • 🔄 Logging em Lote - Suporte a operações em massa com method overloading
  • 🔗 Correlation ID - Rastreamento único de requisições através do sistema
  • 🛡️ Sanitização Automática - Proteção de dados sensíveis (PII, credenciais)
  • ⏱️ Métricas de Performance - Medição automática de tempo de resposta
  • 🚀 AWS Lambda Ready - Otimizado para ambientes serverless
  • 📊 Multi-destino - Console, arquivo local, e S3 via Kinesis Firehose
  • 🔄 Fallback Inteligente - Recuperação automática em caso de falhas
  • 🔐 IAM Role Support - Autenticação via STS AssumeRole

📦 Instalação

npm install @nicollasfrazao/liguelead-log-service

🚀 Uso Rápido

Configuração Básica

import express from 'express';
import { LogService, LogMiddleware } from '@nicollasfrazao/liguelead-log-service';

const app = express();

// Middleware de logging (adicione ANTES das rotas)
app.use(LogMiddleware.handler);

// Suas rotas
app.get('/api/users', async (req, res) => {
  await LogService.info('Buscando usuários', {
    method: req.method,
    url: req.url,
    ip: req.ip
  });
  
  res.json({ users: [] });
});

app.listen(3000);

Variáveis de Ambiente

# Configuração Principal
LOG_USE=true                    # Habilita/desabilita logging
LOG_LEVEL=info                  # debug | info | warn | error
LOG_DESTINATION=both            # console | storage | both

# Identificação
LOG_SERVICE_NAME=my-service     # Nome do serviço nos logs
LOG_PREFIX=[MY-APP]             # Prefixo das mensagens
NODE_ENV=development            # development | homologation | production | test

# Conteúdo dos Logs
LOG_INCLUDE_PAYLOAD=true        # Inclui corpo das requisições
LOG_INCLUDE_RESPONSE=true       # Inclui corpo das respostas
LOG_INCLUDE_HEADERS=true        # Inclui headers das requisições
LOG_MAX_BODY_SIZE=1000          # Tamanho máximo do body (bytes)

# Fallback
LOG_FALLBACK_TO_LOCAL_STORAGE=true  # Fallback para arquivo local
LOG_FALLBACK_TO_CONSOLE=true        # Fallback para console

# Chamadas Externas
LOG_EXTERNAL_REQUEST_CALL=true  # Loga chamadas para APIs externas

☁️ Configuração AWS (S3 via Kinesis Firehose)

Opção 1: IAM Role (Recomendado)

LOG_USE_S3_STORAGE=true
LOG_AWS_ROLE_ARN=arn:aws:iam::123456789:role/firehose-delivery-role
LOG_FIREHOSE_STREAM_NAME=my-app-logs-firehose
LOG_AWS_REGION=us-east-1

Opção 2: Access Keys (Desenvolvimento)

LOG_USE_S3_STORAGE=true
LOG_AWS_ACCESS_KEY_ID=your-access-key
LOG_AWS_SECRET_ACCESS_KEY=your-secret-key
LOG_FIREHOSE_STREAM_NAME=my-app-logs-firehose
LOG_AWS_REGION=us-east-1

LocalStack (Desenvolvimento Local)

LOG_USE_S3_STORAGE=true
LOG_AWS_ENDPOINT=http://localhost:4566
LOG_FIREHOSE_STREAM_NAME=dev-logs-firehose
LOG_AWS_ACCESS_KEY_ID=test
LOG_AWS_SECRET_ACCESS_KEY=test

Configurações Avançadas AWS Lambda

LOG_AWS_LAMBDA_CREDENTIALS_MAX_RETRIES=3     # Máximo de retries para credenciais
LOG_AWS_LAMBDA_CREDENTIALS_CACHE_BUFFER_MS=120000  # Buffer antes da expiração
LOG_AWS_LAMBDA_REQUEST_TIMEOUT_MS=12000      # Timeout de requisição
LOG_AWS_LAMBDA_MAX_ATTEMPTS=4                # Máximo de tentativas

📖 API

LogService

Serviço principal estático para logging.

import { LogService } from '@nicollasfrazao/liguelead-log-service';

// Métodos de log (todos assíncronos)
await LogService.info(message, context?, correlationId?);
await LogService.warn(message, context?, correlationId?);
await LogService.error(message, context?, correlationId?);
await LogService.debug(message, context?, correlationId?);

// Configuração
const config = LogService.getConfig();

Method Overloading

Todos os métodos de log suportam múltiplas assinaturas:

// 1. Apenas mensagem
await LogService.info('Operação realizada');

// 2. Com contexto único
await LogService.info('Operação realizada', {
  method: 'POST',
  url: '/api/users',
  ip: '192.168.1.1'
});

// 3. Com array de contextos (batch)
await LogService.info('Operações em lote', [
  { method: 'GET', url: '/api/user/1', ip: '192.168.1.1' },
  { method: 'GET', url: '/api/user/2', ip: '192.168.1.1' }
]);

// 4. Com log pré-formatado
await LogService.info('Log externo', {
  timestamp: '2025-01-01T00:00:00Z',
  level: 'info',
  environment: 'production',
  service: 'external-service',
  correlation_id: 'ext-123',
  message: 'Mensagem externa',
  context: { method: 'POST', url: '/external', ip: '10.0.0.1' }
});

LogMiddleware

Middleware para logging automático de requisições HTTP.

import { LogMiddleware } from '@nicollasfrazao/liguelead-log-service';

// Registrar middleware
app.use(LogMiddleware.handler);

LogHelper

Funções utilitárias para criação de contextos e logs.

import { LogHelper } from '@nicollasfrazao/liguelead-log-service';

// Gerar correlation ID
const correlationId = LogHelper.generateCorrelationId();

// Obter IP do cliente
const ip = LogHelper.getClientIp(request);

LogError

Classe de erro customizada com suporte a status code e detalhes.

import { LogError } from '@nicollasfrazao/liguelead-log-service';

throw new LogError('Usuário não encontrado', 404, { userId: 123 });

executeRequest

Executa chamadas para APIs externas com logging automático.

import { LogService } from '@nicollasfrazao/liguelead-log-service';
import axios from 'axios';

const response = await LogService.executeRequest<UserResponse>(
  {
    name: 'UserAPI',                              // Nome identificador
    method: 'POST',                               // Método HTTP
    url: 'https://api.example.com/users',        // URL da API
    payload: { name: 'John' },                    // Payload (opcional)
    origin: req,                                  // Request Express (opcional)
    handler: () => axios.post('https://api.example.com/users', { name: 'John' })
  },
  { user_id: 'user-123' },                       // Contexto adicional
  'correlation-id-123'                           // Correlation ID
);

🔧 Interfaces e Types

LogInterface

interface LogInterface {
  timestamp: string;
  level: 'info' | 'warn' | 'error' | 'debug';
  id: string;
  environment: 'development' | 'homologation' | 'production' | 'test';
  service: string;
  correlation_id: string;
  message: string;
  context?: LogContextInterface;
}

LogContextInterface

interface LogContextInterface {
  user_id?: string;
  app_id?: string;
  method?: string;
  url?: string;
  user_agent?: string;
  ip?: string;
  payload?: any;
  response?: any;
  status_code?: number;
  response_time?: number;
  error?: string;
  stack?: string;
  headers?: Record<string, any>;
  content_type?: string;
}

LogConfigInterface

interface LogConfigInterface {
  environment: 'development' | 'homologation' | 'production' | 'test';
  level: 'error' | 'warn' | 'info' | 'debug';
  includePayload: boolean;
  includeResponse: boolean;
  includeHeaders: boolean;
  maxBodySize: number;
  sensitiveFields: string[];
  logExternalRequestCall: boolean;
  timestampFormat: 'iso' | 'epoch';
  useColors: boolean;
  logPrefix: string;
  logDestination: 'storage' | 'console' | 'both';
  useS3Storage: boolean;
  useLog: boolean;
  service: string;
  fallbackToLocalStorage: boolean;
  fallbackToConsole: boolean;
}

🛡️ Sanitização Automática

Os seguintes campos são automaticamente mascarados nos logs:

| Campo | Variações Detectadas | |-------|---------------------| | Senhas | password, senha | | Tokens | token, access_token, refresh_token | | Autenticação | authorization, api_key, apikey, secret | | Cartões | credit_card, creditcard, card_number, cvv, cvc | | Documentos | cpf, cnpj, ssn, social_security | | Contato | email | | Chaves | private_key, privatekey | | Sessão | session_id, sessionid |

Exemplo de saída sanitizada:

{
  "context": {
    "payload": {
      "username": "john.doe",
      "password": "[REDACTED]",
      "credit_card": "[REDACTED]"
    }
  }
}

📁 Estrutura de Armazenamento

Arquivos Locais

storage/logs/
├── development/
│   └── 2025-02-09-combined.log
├── homologation/
│   └── 2025-02-09-combined.log
├── production/
│   └── 2025-02-09-combined.log
└── test/
    └── 2025-02-09-combined.log

S3 via Kinesis Firehose

s3://my-bucket/
└── logs/
    └── 2025/02/09/
        ├── firehose_output-1-2025-02-09-12-00-00-uuid.gz
        └── firehose_output-2-2025-02-09-12-30-00-uuid.gz

🚀 AWS Lambda

O serviço é otimizado para AWS Lambda com:

  • Detecção automática de ambiente Lambda
  • Timeouts otimizados (8s máximo por operação)
  • Cache de credenciais com refresh automático
  • Retry inteligente com backoff exponencial
  • Fallback para console em caso de timeout

Constantes Lambda

| Constante | Valor | Descrição | |-----------|-------|-----------| | MAX_OPERATION_TIMEOUT | 8000ms | Timeout máximo por operação | | TIMEOUT_BUFFER | 5000ms | Buffer antes do timeout da Lambda | | CREDENTIALS_CACHE_BUFFER | 300000ms | Refresh de credenciais (5 min antes) |

🔄 Resiliência de Rede

O sistema possui retry automático para erros de rede:

Erros Retryable

  • ECONNRESET, ECONNREFUSED, ETIMEDOUT
  • EPIPE, EHOSTUNREACH, ENETUNREACH
  • EAI_AGAIN, ENOTFOUND
  • socket hang up, connection timeout

Estratégia de Retry

  1. Tentativa inicial → Firehose
  2. Se falha de rede → Retry com backoff exponencial
  3. Se todas falham → Fallback para armazenamento local
  4. Se local falhar → Fallback para console (se habilitado)

📊 Formato dos Logs

Log de Requisição

{
  "timestamp": "2025-02-09T10:30:00.000Z",
  "level": "info",
  "id": "uuid-v4",
  "environment": "production",
  "service": "my-service",
  "correlation_id": "550e8400-e29b-41d4-a716-446655440000",
  "message": "[MY-APP] Incoming request",
  "context": {
    "method": "POST",
    "url": "/api/users",
    "ip": "192.168.1.100",
    "user_agent": "Mozilla/5.0...",
    "headers": {
      "content-type": "application/json",
      "authorization": "[REDACTED]"
    },
    "payload": {
      "name": "John Doe",
      "password": "[REDACTED]"
    }
  }
}

Log de Chamada Externa

{
  "timestamp": "2025-02-09T10:30:01.500Z",
  "level": "info",
  "id": "uuid-v4",
  "environment": "production",
  "service": "my-service",
  "correlation_id": "550e8400-e29b-41d4-a716-446655440000",
  "message": "[MY-APP] External request call to UserAPI completed",
  "context": {
    "method": "POST",
    "url": "https://api.example.com/users",
    "status_code": 201,
    "response_time": 1500,
    "payload": { "name": "John Doe" },
    "response": { "id": "user-123", "created": true }
  }
}

📂 Estrutura do Projeto

src/
├── index.ts                 # Exports públicos
├── configs/
│   ├── aws.config.ts        # Configurações AWS
│   └── log.config.ts        # Configurações de logging
├── constants/
│   ├── firehose.constants.ts
│   ├── lambda.constants.ts  # Constantes Lambda
│   ├── log.constants.ts
│   ├── network.constants.ts # Retry e timeout
│   └── sanitization.constants.ts
├── errors/
│   └── log.error.ts         # Erro customizado
├── helpers/
│   ├── log.formatting.helper.ts
│   ├── log.helper.ts        # Utilitários
│   └── log.sanitization.helper.ts
├── interfaces/
│   ├── aws.config.interface.ts
│   ├── external.request.interface.ts
│   ├── external.response.interface.ts
│   ├── log.config.interface.ts
│   ├── log.context.interface.ts
│   ├── log.interface.ts
│   ├── log.storage.base.service.interface.ts
│   └── network.retry.options.interface.ts
├── middlewares/
│   └── log.middleware.ts    # Middleware Express
├── services/
│   ├── log.service.ts       # Serviço principal
│   ├── log.storage.base.service.ts
│   ├── log.storage.external.s3.service.ts
│   ├── log.storage.external.service.ts
│   ├── log.storage.local.service.ts
│   └── log.storage.service.ts
├── types/
│   ├── log.data.type.ts
│   ├── log.destination.type.ts
│   ├── log.level.type.ts
│   ├── log.sensitive.field.type.ts
│   └── retryable.error.code.type.ts
└── utils/
    ├── network.util.ts
    ├── log.type.guard.util.ts
    └── validation.util.ts

🔧 Scripts

npm run build        # Compila TypeScript para dist/
npm run clean        # Remove diretório dist
npm run dev          # Modo watch (desenvolvimento)
npm run prepublishOnly  # Clean + build para publicação

📋 Requisitos

  • Node.js: >= 16.0.0
  • Express: ^4.0.0 || ^5.0.0 (peer dependency)

🤝 Contribuição

  1. Fork o repositório
  2. Crie uma branch para sua feature (git checkout -b feature/nova-feature)
  3. Commit suas mudanças (git commit -m 'feat: add nova feature')
  4. Push para a branch (git push origin feature/nova-feature)
  5. Abra um Pull Request

Convenção de Commits

Todos os commits devem ser em inglês seguindo o padrão Conventional Commits:

  • feat: Nova feature
  • fix: Correção de bug
  • docs: Documentação
  • refactor: Refatoração
  • test: Testes
  • chore: Manutenção

🤖 MCP Server (AI Integration)

An MCP (Model Context Protocol) server is included for AI-assisted logging integration. It allows AI agents like Claude Desktop, VS Code Copilot, Cursor, and Windsurf to analyze, validate, fix, and implement logging in your Express projects.

Use it with:

npx @nicollasfrazao/liguelead-log-service

Or import programmatically:

import { startServer } from '@nicollasfrazao/liguelead-log-service/mcp';
await startServer();

Available tools: analyze_project, validate_logging, suggest_logging, fix_logging, implement_logging, generate_snippet

See MCP Configuration Guide below and src/.mcp/README.md for full documentation and agent setup.

MCP Configuration

Claude Desktop

Add to ~/Library/Application Support/Claude/claude_desktop_config.json (macOS) or %APPDATA%\Claude\claude_desktop_config.json (Windows):

{
  "mcpServers": {
    "liguelead-log-service": {
      "command": "npx",
      "args": ["@nicollasfrazao/liguelead-log-service"]
    }
  }
}

VS Code (Copilot)

Add to .vscode/mcp.json in your project:

{
  "servers": {
    "liguelead-log-service": {
      "command": "npx",
      "args": ["@nicollasfrazao/liguelead-log-service"]
    }
  }
}

Cursor

Add to .cursor/mcp.json:

{
  "mcpServers": {
    "liguelead-log-service": {
      "command": "npx",
      "args": ["@nicollasfrazao/liguelead-log-service"]
    }
  }
}

📄 Licença

ISC © Ligue Lead Tech