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

log-gateway-js

v0.0.21

Published

Universal logging library for React, Next.js, and NestJS

Downloads

210

Readme

log-gateway-js

React, Next.js, NestJS를 지원하는 범용 로깅 라이브러리입니다.

소개

log-gateway-js는 여러 프레임워크를 지원하는 통합 로깅 솔루션입니다. 로깅 서버로 로그를 전송하여 중앙 집중식 로그 관리를 제공합니다.

설치

npm install log-gateway-js
# 또는
pnpm add log-gateway-js
# 또는
yarn add log-gateway-js

사용법

React

// main.tsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./index.css";
import App from "./App.tsx";
import { initializeLoggerClient } from "log-gateway-js";

initializeLoggerClient({
  region: "ap-northeast-2",
  service: "my-react-app",
  version: "1.0.0",
  env: "development",
});

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <App />
  </StrictMode>
);

컴포넌트에서 사용:

import { log } from "log-gateway-js";

function MyComponent() {
  const handleClick = () => {
    log.info("Button clicked", { userId: "123" });
  };

  return <button onClick={handleClick}>Click</button>;
}

Next.js App Router

Next.js App Router는 Server Component와 Client Component를 구분합니다. 서버와 클라이언트 각각 로거를 초기화해야 합니다.

1. Layout에서 서버 초기화

import { initializeLogger } from "log-gateway-js";
import Providers from "./components/Providers";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  initializeLogger({
    region: "ap-northeast-2",
    service: "my-nextjs-app-server",
    version: "1.0.0",
    env: process.env.NODE_ENV,
  });

  return (
    <html>
      <body>
        <Providers>{children}</Providers>
      </body>
    </html>
  );
}

2. Providers에서 클라이언트 초기화

"use client";

import { initializeLoggerClient } from "log-gateway-js";
import { useEffect } from "react";

function Provider({ children }: { children: React.ReactNode }) {
  useEffect(() => {
    initializeLoggerClient({
      region: "ap-northeast-2",
      service: "my-nextjs-app-server",
      version: "1.0.0",
      env: "env",
    });
  }, []);
  return <div>{children}</div>;
}

export default Provider;

3. 컴포넌트에서 사용

import { log } from "log-gateway-js";

// Server Component
export default function Page() {
  return <div>Page</div>;
}

// Client Component
("use client");
export default function Button() {
  return <button onClick={() => log.info("Clicked")}>Click</button>;
}

NextJS Page Router에서 사용하기

import "@/styles/globals.css";
import { initializeLogger, initializeLoggerClient } from "log-gateway-js";
import type { AppProps } from "next/app";
import { useEffect } from "react";

if (typeof window === "undefined") {
  initializeLogger({
    region: "ap-northeast-2",
    service: "my-nextjs-app-server",
    version: "1.0.0",
    env: "env",
  });
}

export default function App({ Component, pageProps }: AppProps) {
  useEffect(() => {
    initializeLoggerClient({
      region: "ap-northeast-2",
      service: "my-nextjs-app-client",
      version: "1.0.0",
      env: "env",
    });
  }, []);
  return <Component {...pageProps} />;
}

NestJS에서 사용하기

Logger Module 생성

// logger.module.ts
import { Module } from "@nestjs/common";
import { initializeLogger } from "log-gateway-js";

const logger = initializeLogger({
  region: "ap-northeast-2",
  service: "my-nestjs-app",
  version: "1.0.0",
  env: process.env.NODE_ENV || "development",
});

@Module({
  providers: [
    {
      provide: "LOGGER",
      useValue: logger,
    },
  ],
  exports: ["LOGGER"],
})
export class LoggerModule {}

Service에서 사용

import { Injectable, Inject } from "@nestjs/common";
import { LoggerService } from "log-gateway-js";

@Injectable()
export class MyService {
  constructor(@Inject("LOGGER") private readonly logger: LoggerService) {}

  async processData(data: any) {
    this.logger.info("Processing data", { recordCount: data.length });

    try {
      // 비즈니스 로직
    } catch (error) {
      this.logger.error("Processing failed", error);
      throw error;
    }
  }
}

API 문서

initializeLogger(config)

전역 로거를 초기화합니다.

파라미터:

  • config: LoggerConfig - 로거 설정 객체

반환값:

  • LoggerService - 초기화된 로거 서비스 인스턴스

예시:

const logger = initializeLogger({
  region: "ap-northeast-2",
  service: "my-app",
});

initializeLoggerClient(config)

클라이언트 사이드에서 전역 로거를 초기화합니다 (Next.js App Router용).

파라미터:

  • config: LoggerConfig - 로거 설정 객체

예시:

useEffect(() => {
  initializeLoggerClient({
    region: "ap-northeast-2",
    service: "my-app",
  });
}, []);

<LoggerProvider>

React 컴포넌트로, 자동으로 클라이언트 사이드 로거를 초기화합니다.

Props:

  • children: ReactNode - 자식 컴포넌트
  • config: LoggerConfig - 로거 설정 객체

예시:

import { LoggerProvider } from "log-gateway-js";

function App() {
  return (
    <LoggerProvider
      config={{
        region: "ap-northeast-2",
        service: "my-app",
        version: "1.0.0",
        env: "production",
      }}
    >
      {children}
    </LoggerProvider>
  );
}

getLogger()

초기화된 전역 로거를 가져옵니다.

반환값:

  • LoggerService - 전역 로거 인스턴스

예시:

const logger = getLogger();
logger.info("Message");

log 객체

전역 로거의 편의 메서드들입니다.

메서드:

  • log.info(message, context?) - 정보 로그
  • log.warn(message, context?) - 경고 로그
  • log.error(message, context?) - 에러 로그
  • log.debug(message, context?) - 디버그 로그

예시:

import { log } from "log-gateway-js";

log.info("User logged in", { userId: "123" });
log.error("Failed to connect", error);

LoggerService 클래스

로거 서비스 클래스입니다. 싱글톤 패턴으로 작동합니다.

LoggerService.getInstance(config?)

싱글톤 인스턴스를 가져옵니다.

파라미터 (선택사항):

  • config: LogConfig - 첫 초기화 시 설정 객체

반환값:

  • LoggerService - 로거 서비스 인스턴스

LoggerService.initialize(config)

새로운 인스턴스를 생성하여 초기화합니다.

파라미터:

  • config: LogConfig - 로거 설정 객체

반환값:

  • LoggerService - 로거 서비스 인스턴스

logger.info(message, context?)

정보 레벨 로그를 전송합니다.

파라미터:

  • message: string - 로그 메시지
  • context?: string | Error | object - 컨텍스트 데이터

logger.warn(message, context?)

경고 레벨 로그를 전송합니다.

파라미터:

  • message: string - 로그 메시지
  • context?: string | Error | object - 컨텍스트 데이터

logger.error(message, context?)

에러 레벨 로그를 전송합니다.

파라미터:

  • message: string - 로그 메시지
  • context?: string | Error | object - 컨텍스트 데이터

logger.debug(message, context?)

디버그 레벨 로그를 전송합니다.

파라미터:

  • message: string - 로그 메시지
  • context?: string | Error | object - 컨텍스트 데이터

설정 옵션

LoggerConfig

interface LoggerConfig {
  region: string; // 리전 정보 (예: 'ap-northeast-2')
  service: string; // 서비스 이름 (필수)
  version?: string; // 버전 정보 (선택)
  env?: string; // 환경 정보 (예: 'production', 'development') (선택)
}

필수 필드:

  • region: 로그를 생성하는 리전 정보
  • service: 서비스 식별 이름

선택 필드:

  • version: 서비스 버전 번호
  • env: 실행 환경 (개발, 스테이징, 프로덕션 등)

예제

에러 처리와 함께 사용하기

import { log } from "log-gateway-js";

async function fetchUserData(userId: string) {
  try {
    const data = await api.getUser(userId);
    log.info("User data fetched", { userId, dataSize: data.length });
    return data;
  } catch (error) {
    log.error("Failed to fetch user data", { userId, error });
    throw error;
  }
}

객체 컨텍스트 전송하기

log.info("Order created", {
  orderId: "ORD-123",
  userId: "USER-456",
  amount: 10000,
  items: [
    { productId: "PROD-1", quantity: 2 },
    { productId: "PROD-2", quantity: 1 },
  ],
});