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 🙏

© 2025 – Pkg Stats / Ryan Hefner

azify-logger-client-v2

v1.9.42

Published

Azify Logger Client - Centralized logging for OpenSearch

Readme

🚀 Azify Logger - Logging Centralizado

Sistema de logging centralizado com OpenTelemetry e OpenSearch para múltiplas aplicações.

📦 Instalação

Na sua aplicação, adicione ao package.json:

{
  "dependencies": {
    "azify-logger-client-v2": "^1.3.1"
  }
}

Ou via npm:

npm install azify-logger-client-v2

⚡ Utilização

Para aplicações Restify:

1. No arquivo de inicialização:

#!/usr/bin/env node
require('azify-logger-client-v2/register-otel');
// Resto do código...

2. No servidor Restify:

import { middleware as azifyMiddleware } from 'azify-logger-client-v2'

const server = restify.createServer()
server.use(azifyMiddleware.restify())

3. Variável de ambiente:

APP_NAME=nome-app

PRONTO! 🎉

Para aplicações Express:

require('azify-logger-client-v2')

const express = require('express')
const app = express()
// Logs automáticos via OpenTelemetry

❌ O que NÃO precisa:

  • ❌ Instalar dependências OpenTelemetry separadamente
  • ❌ Configurar tracing manualmente

⚙️ Variáveis de Ambiente

| Variável | Padrão | Descrição | |----------|-------|-----------| | APP_NAME | - | Nome da aplicação | | AZIFY_LOGGER_URL | http://localhost:3000 | URL do logger | | OTEL_EXPORTER_OTLP_ENDPOINT | http://localhost:4318/v1/traces | OTLP endpoint | | NODE_ENV | development | Ambiente | | AZIFY_LOGGER_AUTOREG_DISABLE | "" | Se "1", desativa auto-registro do OTEL |

Para desenvolvimento local: só precisa de APP_NAME (o resto usa defaults)

Para produção: configure todas as URLs apontando para servidores de produção

Docker e Node antigos

Se seu container usa uma versão antiga do Node e você ver erros de inicialização do OpenTelemetry (ex.: Cannot find module 'node:events' saindo de google-logging-utils ou @opentelemetry/resource-detector-gcp), defina no container:

AZIFY_LOGGER_AUTOREG_DISABLE=1

Isso evita carregar register-otel.js e mantém os envios de log via streams/middleware normalmente, permitindo visualização no OpenSearch.

🎯 O Que Você Ganha

  • Zero Config: OpenTelemetry habilitado automaticamente
  • Logs Completos: Headers, body, query params, status
  • Trace Consistente: REQUEST e RESPONSE com mesmo traceId/spanId
  • Genérico: Funciona com Bunyan, Pino, console.log ou qualquer logger
  • Centralizado: Todos os logs no OpenSearch

🔧 Uso Avançado

Com Bunyan existente (adicionar stream)

Se sua app já tem Bunyan e você quer adicionar o azify-logger como stream adicional:

// Forma segura com try/catch (não quebra se não tiver instalado)
let createAzifyBunyanStream
try {
  createAzifyBunyanStream = require('azify-logger-client-v2/streams/bunyan')
} catch (_) {
  createAzifyBunyanStream = null
}

const bunyan = require('bunyan')
const streams = [
  { level: 'info', stream: process.stdout }
]

// Adiciona stream do azify-logger se disponível
if (createAzifyBunyanStream) {
  streams.push({
    level: 'info',
    type: 'raw',
    stream: createAzifyBunyanStream({
      loggerUrl: process.env.AZIFY_LOGGER_URL || 'http://localhost:3000',
      serviceName: process.env.APP_NAME || 'app'
    })
  })
}

const logger = bunyan.createLogger({ name: 'app', streams })
logger.info('Teste')  // Vai para stdout E para azify-logger

Com Bunyan (auto-patch - mais simples)

require('azify-logger-client-v2')

const bunyan = require('bunyan')
const log = bunyan.createLogger({ name: 'nome-app' })

log.info('Teste')  // Automaticamente enviado para azify-logger

Com Pino

const { streams } = require('azify-logger-client-v2')
const pino = require('pino')

const logger = pino({ level: 'info' }, streams.createPinoStream({
  loggerUrl: 'http://localhost:3000',
  serviceName: 'nome-app'
}))

logger.info('Teste')

Logger Direto (sem Bunyan/Pino)

const { createAzifyLogger } = require('azify-logger-client-v2')

const logger = createAzifyLogger({
  serviceName: 'nome-app',
  loggerUrl: 'http://localhost:3000'
})

logger.info('Mensagem', { userId: '123' })
logger.error('Erro', new Error('Falha'), { context: 'payment' })

🛠️ Setup do Serviço de Logging (Infra)

Se você precisa subir a infraestrutura do azify-logger:

1. Iniciar serviços

./start-docker.sh

Aguarde alguns minutos. Você verá:

✅ Tudo pronto!
📊 OpenSearch: http://localhost:9200
🎨 OpenSearch Dashboards: http://localhost:5601
📝 Logger API: http://localhost:3000
🔭 OTEL Collector: http://localhost:4318

2. Testar

curl -X POST http://localhost:3000/test-log \
  -H "Content-Type: application/json" \
  -d '{
    "level": "info",
    "message": "Teste",
    "meta": {"service": {"name": "teste"}}
  }'

3. Ver logs

OpenSearch Dashboards:

http://localhost:5601

Como usar:

  1. Acesse: http://localhost:5601
  2. Para logs detalhados: Vá para Discover
  3. Para dashboard profissional: Vá para Dashboard → "Application Health Dashboard"
  4. Use os filtros:
    • service.name: "nome-da-app" (para filtrar por serviço)
    • appName: "nome-da-app" (para filtrar por app)
    • traceId: "valor" (para ver logs de uma requisição)
    • statusCode: 400 (para ver apenas erros)
    • statusCode: 201 (para ver apenas sucessos)

📊 Estrutura dos Logs

Cada log no OpenSearch contém:

{
  "timestamp": "2025-10-01T10:15:30.123Z",
  "level": "info",
  "message": "[REQUEST] POST /api/payment",
  "service": {
    "name": "nome-app",
    "version": "1.0.0"
  },
  "traceId": "abc123...",
  "spanId": "xyz789...",
  "method": "POST",
  "url": "/api/payment",
  "requestBody": { ... },
  "statusCode": 200,
  "responseTime": 123.45,
  "responseBody": { ... },
  "environment": "production",
  "hostname": "app-server-01"
}

🔍 Como Funciona

  1. OpenTelemetry cria um span para cada request HTTP
  2. Middleware captura request e response com o mesmo span ativo
  3. Logger envia ambos os logs com traceId e spanId iguais
  4. OpenSearch indexa e permite buscar por traceId

📖 Arquitetura

┌─────────────┐
│  aplicação  │  
└──────┬──────┘
       │ HTTP POST
       ↓
┌─────────────┐
│ azify-logger│  (recebe logs)
└──────┬──────┘
       │
       ↓
┌─────────────┐
│ OpenSearch  │  (armazena)
└──────┬──────┘
       │
       ↓
┌─────────────┐
│  Dashboards |
|  OpenSearch │ (visualiza)
└─────────────┘

📈 OpenSearch Dashboards

O azify-logger usa OpenSearch Dashboards para visualização profissional dos logs:

🎯 Funcionalidades Disponíveis

  1. 📊 Discover - Visualização e busca de logs

    • Filtros por serviço, app, traceId, statusCode
    • Busca em tempo real
    • Visualização detalhada de cada log
  2. 📈 Dashboard Profissional - "Application Health Dashboard"

    • Taxa de Sucesso - Percentual de requisições 2xx
    • Latência Média - Tempo médio de resposta
    • Erros 4xx/5xx - Contador de erros
    • Distribuição de Status Codes - Gráfico de pizza
    • Requisições por Minuto - Gráfico temporal
    • Top Endpoints - Endpoints mais acessados
  3. 🔍 Filtros Avançados - Busca poderosa

    • service.name: "nome-da-app" - Filtrar por serviço
    • appName: "nome-da-app" - Filtrar por aplicação
    • traceId: "abc123" - Ver todos os logs de uma requisição
    • statusCode: [400 TO 499] - Ver apenas erros 4xx
    • responseTime: >1000 - Ver requisições lentas

🚀 Acesso

# Local
http://localhost:5601

# Sem autenticação necessária (desenvolvimento)