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

@mecanizou/telemetry-hub

v1.2.3

Published

Mecanizou telemetry lib

Readme

📊 Telemetry Hub

Biblioteca centralizada para telemetria e logging estruturado padronizado, compatível com múltiplos frameworks (Tsed, SST/Middy).

🔗 Quick Links

🎯 Objetivo

Padronizar a forma como logs são gerados em diferentes tipos de projetos, garantindo:

  • Consistência nos campos de log entre diferentes implementações
  • Observabilidade através do OpenTelemetry
  • Facilidade de manutenção com uma única fonte de verdade

📦 Instalação

npm install @mecanizou/telemetry-hub

🏗️ Arquitetura

src/telemetry/
├── core/                    # 🎯 Implementação base (StandardLogger, StandardTracer)
│   ├── types.ts             # Interface StandardLogData
│   ├── logger.ts            # StandardLogger
│   ├── tracer-types.ts      # Interface StandardTraceData
│   ├── tracer.ts            # StandardTracer
│   ├── index.ts             # Exports
│   ├── README.md            # 📚 Visão geral do Core
│   ├── LOGGING.md           # 📝 Guia de logging
│   ├── TRACING.md           # 🔍 Guia de tracing
│   └── __tests__/           # Testes (57 testes, 100% cobertura)
│       ├── logger.test.ts
│       ├── tracer.test.ts
│       ├── logger-types.test.ts
│       └── README.md        # 📚 Documentação dos testes
│
├── tsed/                    # 🔷 Implementação para Tsed
│   ├── config.ts            # TsedTelemetryProvider (logs + traces + métricas)
│   ├── service.ts           # TsedTelemetryService
│   ├── log-telemetry.ts     # Decorator @TsedLogTelemetry
│   ├── sync-log-record-processor.ts
│   ├── index.ts
│   ├── README.md            # 📚 Guia de uso Tsed
│   ├── IMPLEMENTATION_SUMMARY.md    # 📝 Resumo da implementação
│   └── SST_COMPARISON.md    # 🔄 Comparação Tsed vs SST
│
└── sst/                     # 🟦 Implementação para SST/Middy
    ├── telemetry.ts         # Configuração OpenTelemetry + getStandardLogger/Tracer
    ├── index.ts
    ├── README.md            # 📚 Guia de uso SST
    └── middy/
        ├── middleware.ts    # Middleware Middy (usa StandardLogger + StandardTracer)
        └── index.ts

Componentes Principais

1. StandardLogger (Core)

  • Classe base que formata logs no padrão OpenTelemetry
  • Garante que todos os campos seguem a mesma estrutura
  • Implementa os métodos: logError, logInfo, logWarn, logDebug

2. StandardLogData (Interface)

Define o contrato padrão de log com campos:

  • severity, message, error
  • serviceName, environment
  • http (method, url, endpoint, statusCode, etc.)
  • user (accountUserUid, accountUid, applicationUid)
  • execution (requestId, awsRequestId, functionName, controller, etc.)
  • performance (durationMs, success)
  • context (dados adicionais)

🚀 Uso

Para Projetos Tsed

import { 
  TsedTelemetryProvider, 
  TsedTelemetryService,
  TsedLogTelemetry 
} from '@mecanizou/telemetry-hub';

// 1. Configurar provider (no módulo principal)
@Configuration({
  // ...
})
export class Server {
  @Inject()
  protected telemetryProvider: TsedTelemetryProvider;

  async $afterInit() {
    await this.telemetryProvider.initialize();
  }
}

// 2. Usar decorator nos controllers
export class CheckoutController {
  @TsedLogTelemetry()
  async getCheckout(@Context() $ctx: ServerlessContext) {
    // Erros são capturados e logados automaticamente
    return await this.service.execute();
  }
}

Para Projetos SST (Lambdas com Middy)

import { middyMiddleware } from '@mecanizou/telemetry-hub';
import middy from '@middy/core';

export const handler = middy(async (event, context) => {
  // Sua lógica aqui
  return { statusCode: 200, body: 'OK' };
}).use(middyMiddleware());

O middleware automaticamente:

  • Registra logs de INFO em caso de sucesso
  • Registra logs de ERROR em caso de falha
  • Mantém traces e métricas do OpenTelemetry

⚙️ Configuração

Variáveis de Ambiente Obrigatórias

OTEL_EXPORTER_OTLP_ENDPOINT=https://seu-endpoint-otel.com
OTEL_EXPORTER_OTLP_USER=seu-usuario
OTEL_EXPORTER_OTLP_PASS=sua-senha

Variáveis de Ambiente Opcionais

SERVICE_NAME=my-service        # Default: 'unknown-service' (Tsed) ou 'sst-service' (SST)
STAGE=production               # Default: 'development'

✅ Testes

O projeto possui 79 testes com 100% de cobertura:

  • Core: 57 testes (logger, tracer, tipos)
  • SST: 9 testes (integração, singleton, forceFlush)
  • Tsed: 13 testes (provider, service, integração)

Para executar:

npm test              # Executar todos os testes
npm run test:watch    # Modo watch
npm run test:ui       # UI interativa
npm run test:coverage # Relatório de cobertura

📝 Campos Padronizados de Log

Todos os logs exportam os seguintes atributos OpenTelemetry:

{
  // Identificação
  timestamp: "2024-12-05T10:30:00.000Z",
  "service.name": "cart-service",
  "deployment.environment.name": "production",
  
  // Erro (quando aplicável)
  "error.type": "ValidationError",
  "error.message": "Invalid cart item",
  "error.stack": "...",
  
  // HTTP
  "http.method": "POST",
  "http.url": "/api/cart/checkout",
  "http.endpoint": "/api/cart/checkout",
  "http.status_code": 400,
  
  // Usuário
  "accountUser.uid": "user-123",
  "account.uid": "account-456",
  "application.uid": "app-789",
  
  // Execução
  "request.id": "req-abc",
  "aws.request.id": "aws-xyz",
  "function.name": "checkoutHandler",
  "function.invocation_id": "inv-123",
  "controller.name": "CheckoutController",
  "controller.method": "getCheckout",
  "origin": "mobile",
  
  // Performance
  "duration.ms": 234,
  "execution.success": true,
  
  // Contexto adicional
  "context": "{...}"
}

🔄 Compatibilidade

| Framework | Versão Testada | Status | |-----------|---------------|--------| | Tsed | ^8.19.4 | ✅ | | SST/Middy | ^6.4.5 | ✅ | | OpenTelemetry | ^0.56.0 | ✅ |

📚 Documentação Adicional

📖 Guia de Navegação da Documentação - Mapa completo de toda documentação disponível

Core (Conceitos e Implementação Base)

  • Core README - Visão geral do StandardLogger e StandardTracer
  • LOGGING.md - Guia detalhado de logging estruturado
  • TRACING.md - Guia detalhado de traces padronizados
  • Testes - Documentação dos testes (57 tests, 100% coverage)

Por Framework

🤝 Contribuindo

Esta é uma lib interna da Mecanizou. Para contribuir:

  1. Clone o repositório
  2. Instale dependências: npm install
  3. Execute testes: npm test
  4. Execute verificação de tipo: npm run test:tsc
  5. Formate código: npm run fix

📄 Licença

ISC