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

@kaikybrofc/logger-module

v1.0.4

Published

Módulo de log moderno em TypeScript usando Winston e Rotação de Arquivos.

Readme

Logger Module TS

Um módulo de log moderno, robusto e de alta performance para aplicações Node.js utilizando TypeScript, Winston, fast-redact para segurança de dados, AsyncLocalStorage para rastreabilidade e sistemas avançados de controle de tráfego.

✨ Características

  • Arquitetura Modular: Estrutura limpa e escalável separando tipos, configurações, contexto e núcleo.
  • Alta Performance: Utiliza o motor fast-redact para mascaramento de dados extremamente rápido.
  • Traffic Control: Sistemas integrados de Sampling (amostragem) e Rate Limiting (limite de frequência) por chave.
  • Formatos Dinâmicos: Alterna automaticamente entre formato Humano (Pretty) em desenvolvimento e JSON Estruturado em produção.
  • Rastreamento Automático (RequestId): Injeção automática de IDs de rastreamento em todos os logs de um contexto assíncrono.
  • Níveis RFC5424 + Customizados: Suporte nativo a níveis como fatal, security e audit, além de permitir novos níveis via ENV.
  • Redação Massiva de Dados: Proteção automática para mais de 200 chaves sensíveis pré-configuradas.
  • Dicionário Customizável: Carregue chaves sensíveis extras via arquivo externo (JSON, CSV ou TXT).
  • Resiliência Avançada: Proteção contra referências circulares e suporte a BigInt.

🚀 Instalação

npm install @kaikybrofc/logger-module

⚙️ Configuração (.env)

| Variável | Descrição | Padrão | |----------|-----------|---------| | NODE_ENV | Ambiente (development, production, test) | development | | LOG_LEVEL | Nível mínimo de exibição | debug (dev) / info (prod) | | LOG_FORMAT | Formato do console (pretty ou json) | Dinâmico | | LOG_EXTRA_LEVELS | Níveis extras (nome:prioridade,ex: trace:15) | - | | LOG_SAMPLING_RATE | Taxa de amostragem global (0.0 a 1.0) | 1.0 | | LOG_RATE_LIMIT_MAX | Máximo de logs por janela para uma chave | 100 | | LOG_SENSITIVE_FILE | Arquivo com chaves sensíveis extras | - | | LOG_AUDIT_IMMUTABLE | Ativa trilha de auditoria com Hashing (Chain-of-Trust) | false | | LOKI_HOST | URL do host Grafana Loki | - | | ELASTICSEARCH_NODE | URL do node Elasticsearch | - | | DATADOG_API_KEY | API Key do Datadog | - |

📖 Funcionalidades em Destaque

📤 Exportação Opcional (Loki/Elastic/Datadog)

O logger suporta exportação automática para serviços externos se configurado via ENV e com as bibliotecas instaladas:

  • Loki: Requer winston-loki
  • Elasticsearch: Requer winston-elasticsearch
  • Datadog: Requer datadog-winston

O carregamento é dinâmico e opcional, não bloqueando o funcionamento do logger caso as bibliotecas não estejam presentes.

🛡️ Auditoria Imutável (Chain-of-Trust)

Quando LOG_AUDIT_IMMUTABLE=true é ativado, todos os logs de nível audit são gravados em um arquivo especial (logs/auditoria.log) onde cada linha é encadeada à anterior via hashing SHA-256. Se qualquer entrada for alterada, a cadeia de hashes será invalidada, garantindo integridade e conformidade.

logger.audit('Acesso a dados sensíveis', { userId: 123 });

🚦 Controle de Tráfego (Rate Limit & Sampling)

Evite flood de logs e reduza custos de infraestrutura:

// Rate Limit: Permite apenas 5 logs por minuto para este erro específico
logger.error('Erro de conexão banco', { 
  rateLimitKey: 'db_error', 
  rateLimitMax: 5 
});

// Sampling: Loga apenas 1 a cada 10 ocorrências
logger.info('Processamento de rotina', { 
  sampleKey: 'routine_task', 
  sampleRate: 10 
});

🔐 Segurança e Níveis Especiais

Use níveis focados em conformidade (LGPD/ISO):

logger.security('Tentativa de login bloqueada', { ip: '...' });
logger.audit('Permissões de usuário alteradas', { adminId: '1' });

🆔 Rastreabilidade

import { runWithContext } from '@kaikybrofc/logger-module';

runWithContext(() => {
  logger.info('Log herda ID automaticamente');
});

📂 Estrutura de Pastas

src/
├── config/      # ENV, Redação e Níveis
├── context/     # AsyncLocalStorage (RequestId)
├── core/        # Logger, Traffic Control e Redact
├── types/       # Definições TypeScript
└── index.ts     # API Pública

📄 Licença

MIT