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

@panopticon/nestjs-monitoring-sdk

v0.2.2

Published

3-line NestJS monitoring SDK for logs and distributed tracing

Readme

@woongno/nestjs-monitoring-sdk

3줄의 코드로 NestJS 애플리케이션의 로그와 분산 추적을 자동 수집하는 모니터링 SDK

특징

  • 간편한 통합: 3줄의 코드만으로 완벽한 모니터링 시스템 구축
  • 자동 수집: HTTP 요청, 로그, DB 쿼리, 외부 API 호출 자동 추적
  • 분산 추적: OpenTelemetry 호환 Trace ID/Span ID 자동 생성
  • 최소 오버헤드: 배치 전송으로 애플리케이션 성능 영향 최소화
  • Non-blocking: 모니터링 실패가 앱 동작에 영향 없음
  • TypeScript: 완전한 타입 지원

설치

npm install @woongno/nestjs-monitoring-sdk

빠른 시작

기본 설정 (3줄!)

// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { MonitoringSDK } from '@woongno/nestjs-monitoring-sdk';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // 이 3줄만 추가하세요!
  MonitoringSDK.init(app, {
    apiKey: 'your-api-key-123',
    endpoint: 'https://producer.woongno-monitoring.com',
    serviceName: 'user-service',
    environment: 'production'
  });

  await app.listen(3000);
}
bootstrap();

이게 전부입니다! 이제 다음이 자동으로 수집됩니다:

  • ✅ 모든 HTTP 요청/응답 (Root Span)
  • ✅ 애플리케이션 로그 (Winston)
  • ✅ DB 쿼리 (TypeORM)
  • ✅ 외부 API 호출 (axios)

수집 데이터

1. HTTP 요청 Trace (Root Span)

{
  "type": "span",
  "timestamp": "2025-11-19T10:03:10.947563+00:00",
  "service_name": "user-service",
  "environment": "production",
  "trace_id": "ceed8e5abfdfec0d6cc06b9eb8e53005",
  "span_id": "9678cbd561a00b1d",
  "parent_span_id": null,
  "name": "POST /payments",
  "kind": "SERVER",
  "duration_ms": 132.015854,
  "status": "OK",
  "http_method": "POST",
  "http_path": "/payments",
  "http_status_code": 200
}

2. DB 쿼리 Trace (Child Span)

{
  "type": "span",
  "trace_id": "ceed8e5abfdfec0d6cc06b9eb8e53005",
  "span_id": "abc123def456",
  "parent_span_id": "9678cbd561a00b1d",
  "name": "SELECT users",
  "kind": "CLIENT",
  "duration_ms": 15.5,
  "db_system": "postgresql",
  "db_statement": "SELECT * FROM users WHERE id = $1"
}

3. 로그

{
  "type": "log",
  "timestamp": "2025-11-19T10:03:10.947563+00:00",
  "service_name": "user-service",
  "environment": "production",
  "level": "error",
  "message": "User not found",
  "context": "UserService"
}

설정 옵션

interface MonitoringConfig {
  // 필수 설정
  apiKey: string;              // Producer 서버 인증 키
  endpoint: string;            // Producer 서버 URL
  serviceName: string;         // 서비스 이름

  // 선택 설정
  environment?: string;        // 환경 (기본: 'development')
  batchSize?: number;          // 배치 크기 (기본: 100)
  flushInterval?: number;      // 전송 주기 ms (기본: 5000)

  // 기능 토글
  enableLogTracking?: boolean;        // 로그 수집 (기본: true)
  enableHttpTracking?: boolean;       // HTTP 추적 (기본: true)
  enableDbTracking?: boolean;         // DB 추적 (기본: true)
  enableHttpClientTracking?: boolean; // 외부 API 추적 (기본: true)
}

TypeORM DB 추적 설정 (선택사항)

TypeORM 설정에서 DB 쿼리 추적을 활성화하려면:

// app.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { MonitoringSDK } from '@woongno/nestjs-monitoring-sdk';

// SDK 초기화 후 DB Logger 가져오기
const sdk = MonitoringSDK.init(app, config);

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'postgres',
      host: 'localhost',
      port: 5432,
      // DB 쿼리 추적 활성화
      logging: true,
      logger: sdk.getDbLogger(),
    }),
  ],
})
export class AppModule {}

고급 사용법

수동으로 Trace Context 접근

import { getCurrentTraceId, getCurrentSpanId } from '@woongno/nestjs-monitoring-sdk';

export class UserService {
  async getUser(id: string) {
    const traceId = getCurrentTraceId();
    const spanId = getCurrentSpanId();

    console.log(`[TraceID: ${traceId}] Fetching user ${id}`);

    // 비즈니스 로직...
  }
}

수동으로 데이터 Flush

const sdk = MonitoringSDK.init(app, config);

// 테스트나 특수한 경우 즉시 전송
await sdk.flush();

// 현재 버퍼 크기 확인
console.log('Buffer size:', sdk.getBufferSize());

아키텍처

NestJS App (SDK)
    ↓
BatchSender (배치 수집)
    ↓
Producer Server (HTTP/HTTPS)
    ↓
MSK (Kafka)
    ↓
Consumer → OpenSearch/TimescaleDB

성능 최적화

  • 배치 전송: 100개 또는 5초마다 일괄 전송 (설정 가능)
  • Non-blocking: 전송 실패 시 앱 동작에 영향 없음
  • AsyncLocalStorage: Trace Context를 효율적으로 관리
  • 최소 파싱: SDK는 수집만, 복잡한 파싱은 Producer에서

시스템 요구사항

  • Node.js >= 16
  • NestJS >= 9.0.0
  • TypeScript >= 5.0

라이센스

MIT

지원

이슈나 질문은 GitHub Issues에서 관리합니다.