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

logify-nest

v1.0.11

Published

Logger contextual para NestJS com suporte a correlation_id, user_id e integração com Pino.

Readme

logify-nest

Logger contextual para NestJS com suporte a correlation_id, user_id, access_token e integração com Pino.

Instalação

npm install logify-nest

Configuração Básica

import { LogifyNestJsModule } from 'logify-nest';

@Module({
  imports: [
    LogifyNestJsModule.forRoot({
      serviceName: 'meu-servico',
      // ignoredPaths: ['/health', '/metrics'], // opcional
    }),
  ],
})
export class AppModule {}

O módulo já registra o Interceptor global e o Middleware para contexto.

Principais Features

  • Correlation ID automático (propagado entre serviços)
  • User ID extraído do header ou JWT (access_token)
  • Interceptor global para logs de request/response
  • Middleware para propagação de contexto
  • Propagação automática de headers (X-Correlation-Id, X-User-Id)
  • Compatível com Pino
  • Stack trace detalhado em erros

Uso dos Métodos de Log

// Injetando o serviço
constructor(private readonly logify: LogifyNestJsService) {}

// Log de negócio
this.logify.log('Mensagem informativa', { extraKey: 'valor' });

// Log de erro com stack trace
try {
  // ...
} catch (error) {
  this.logify.error('Erro ao processar', error);
  // ou
  this.logify.error('Erro ao processar', { stack_trace: error.stack, err: error });
}

// Log de warning/debug
this.logify.warn('Atenção!');
this.logify.debug('Debugando...', { contexto: 'detalhe' });

Propagação de Headers

Para propagar o contexto entre micro-serviços (ex: HTTP, filas, workers):

const headers = this.logify.getPropagationHeaders();
// headers: { 'X-Correlation-Id': '...', 'X-User-Id': '...' }

Propagação Manual de Contexto (ex: Worker, Fila)

Quando processar uma mensagem recebida (ex: RabbitMQ), injete o contexto antes de logar:

const correlationId = amqpMsg?.properties?.headers?.['x-correlation-id'];
const userId = amqpMsg?.properties?.headers?.['x-user-id'];
this.logify.setLoggingContext({ corr_id: correlationId, user_id: userId });
// Agora todos os logs usam esse contexto
this.logify.log('Processando mensagem...');

Se o user_id não for passado, será extraído automaticamente do access_token (se presente).

Como funciona a extração de contexto

  • O correlation_id é extraído dos headers (X-Correlation-Id) ou gerado automaticamente.
  • O user_id é extraído dos headers (X-User-Id) ou decodificado do JWT (access_token).
  • O access_token pode ser passado nos headers ou diretamente.

Stack Trace em Erros

Ao logar erros, o campo stack_trace é preenchido automaticamente se você passar o objeto Error ou o stack:

this.logify.error('Erro fatal', error); // stack e err extraídos
// ou
this.logify.error('Erro fatal', { stack_trace: error.stack, err: error });

Integração automática

O Interceptor e Middleware já garantem contexto e logs de request/response:

  • Logs de início e fim de request
  • Propagação automática de correlation_id e user_id
  • Ignora paths de healthcheck por padrão

Exemplo Completo

import { Controller, Get } from '@nestjs/common';
import { LogifyNestJsService } from 'logify-nest';

@Controller()
export class AppController {
  constructor(private readonly logify: LogifyNestJsService) {}

  @Get('hello')
  getHello() {
    this.logify.log('Recebi um pedido no /hello', { rota: '/hello' });
    return { message: 'Hello World!' };
  }

  @Get('error')
  getError() {
    try {
      throw new Error('Falha simulada');
    } catch (error) {
      this.logify.error('Erro na rota /error', error);
    }
    return { message: 'Erro tratado!' };
  }
}

Licença

MIT