Skip to main content
Version: 0.2.46

SDK 설치 가이드

설치

SDK 설치

npm install @tracivo/sdk

Babel Plugin 추가 설치 (React / React Native 프로젝트 한정)

npm install -D @tracivo/babel-plugin

적용 가이드

중요

SDK 초기화 코드를 별도의 TS 파일에 작성하여, 서버 엔트리 코드 파일에서 첫번째로 import하는 것이 중요합니다.

SDK 초기화 코드

Next.js 경우, 아래 Next.js 설정 을 참고하여 초기화 바랍니다.

init-tracivo.ts 파일을 생성합니다:

/**
* SDK 초기화 - 다른 모듈보다 먼저 로드되어야 함
*/
import Tracivo from '@tracivo/sdk';

// SDK 초기화
Tracivo.init({
apiKey: '<Tracivo API Key>',
functionLogging: {
enabled: true, // 함수 로깅 활성화
excludeFunctions: [/^use[A-Z]/, /^_/], // React hooks와 private 함수 제외
},
networkLogging: {
enableInboundHttpLogging: true, // Inbound HTTP 요청/응답 로깅 활성화
ignoreRoutes: [
{ path: /^\/health$/ },
{ method: 'GET', path: /\/products$/ },
{ path: '/docs' },
],
},
});

console.log('Tracivo SDK initialized with function logging');

핵심 파라미터

파라미터기본값권장값설명
functionLogging.enabledfalsetrue프로젝트 내에서 정의된 함수들에 대해 Argument와 Return 값을 포함한 호출 내역을 Trace로 묶어서 기록합니다.
networkLogging.enableInboundHttpLoggingfalsetrue서버에 Inbound로 발생하는 HTTP 요청/응답 내역을 Trace에 포함합니다.

networkLogging.ignoreRoutes

{
method?: string | string[],
path: string | RegExp
}

Inbound HTTP 요청 중 method, path에 대응하는 route에 대해서는 Trace 데이터를 작성하지 않습니다.

metadata

metadata?: Record<string, unknown>

장치 ID, 빌드 버전 등 해당 서버에서 발생하는 전체 Trace 데이터에 포함시킬 값을 자유롭게 입력할 수 있습니다.

Trace란?

Tracivo에서 네트워크 요청, 코드 내에서 명시적으로 남기는 로그, 함수 호출 내역 등을 하나의 흐름으로 묶어서 관리하는 단위입니다.

주의사항

함수 호출 및 로그 출력 위치를 정확하게 추적하려면 서버가 JavaScript로 빌드된 상태에서 실행되어야 합니다.

  • 코드 위치 추적 불가: tsc server.ts
  • 코드 위치 추적 가능: node dist/server.js

Node.js / Express.js 설정

SDK 초기화 코드 Import & Middleware 등록

server.ts (서버 엔트리 파일):

import './init-tracivo';

// 반드시 첫 번째 import
import Tracivo from '@tracivo/sdk';

import express from 'express';

// ...

const app = express();
app.use(express.json());

app.use(Tracivo.middleware()); // Tracivo 미들웨어 (Trace 컨텍스트 생성)

// ...

HTTP 요청 건마다 실행 흐름 내에 발생하는 모든 데이터를 동일한 Trace로 묶어서 관리하기 위해 Tracivo의 미들웨어를 서버에 등록해야 합니다.

tsconfig.json 설정

{
"compilerOptions": {
"module": "CommonJS",
"sourceMap": true
}
}
옵션설명
module: "CommonJS"모듈 시스템이 CommonJS일 때 함수 로깅 기능을 사용할 수 있습니다. ESM인 경우 해당 기능이 비활성화됩니다. (ESM에서도 로그와 HTTP 호출 내역은 정상 반영됩니다)
sourceMap: true함수 호출, 로그 출력 위치를 TypeScript 파일 기준으로 추적할 수 있도록 소스맵 활성화가 필요합니다.

수동 트레이스 생성

코드 내에서 직접 Trace를 생성해 setInterval()이나 cron 등을 통해 내부에서 Trigger하는 실행 흐름 각각에 대해 Trace ID를 부여할 수 있습니다.

setInterval() 예제

intervalHandle = setInterval(() => {
Tracivo.startNewTrace(() => {
// 매 실행마다 새 trace 시작
/* Scheduled job logic */
});
}, intervalMs);

cron 예제

task = cron.schedule(schedule, () => {
Tracivo.startNewTrace(() => {
// 매 실행마다 새 trace 시작
/* Scheduled job logic */
});
});

React / React Native 설정

babel.config.js

module.exports = function (api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
plugins: [
[
'@tracivo/babel-plugin',
{
projectRoot: __dirname,
wrapperImport: '@tracivo/sdk',
},
],
],
};
};

vite.config.ts (Vite 프로젝트)

import react from '@vitejs/plugin-react';

import path from 'path';
import { defineConfig } from 'vite';

export default defineConfig({
plugins: [
react({
babel: {
plugins: [
[
'@tracivo/babel-plugin',
{
projectRoot: path.resolve(__dirname),
wrapperImport: '@tracivo/sdk',
},
],
],
},
}),
],
});

Next.js 설정

1. 환경 변수 설정

.env 파일에 API 키를 설정합니다:

TRACIVO_API_KEY=your-api-key-here

2. API 라우트 생성

app/api/tracivo/init/route.ts 파일을 생성합니다:

import { NextResponse } from 'next/server';

export async function GET() {
return NextResponse.json({
apiKey: process.env.TRACIVO_API_KEY || '',
});
}

3. Tracivo Provider 컴포넌트 생성

app/tracivo-provider.tsx 파일을 생성합니다:

"use client";

import { useEffect, ReactNode } from "react";
import Tracivo from "@tracivo/sdk";

export function TracivoProvider({ children }: { children: ReactNode }) {
useEffect(() => {
// 클라이언트에서만 초기화
const initTracivo = async () => {
try {
const res = await fetch("/api/tracivo/init");
const { apiKey } = await res.json();

Tracivo.init({
apiKey,
functionLogging: { enabled: true },
});

console.log("[Tracivo] Initialized");
} catch (error) {
console.error("[Tracivo] Failed:", error);
}
};

if (typeof window !== "undefined") {
initTracivo();
}

return () => {
Tracivo.destroy();
};
}, []);

return <>{children}</>;
}

4. Root Layout에 Provider 적용

app/layout.tsx 파일에 TracivoProvider를 적용합니다:

import { TracivoProvider } from "./tracivo-provider";

export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="ko">
<body>
<TracivoProvider>
{children}
</TracivoProvider>
</body>
</html>
);
}

5. Babel 설정 (함수 로깅을 위해 설정 필요)

babel.config.js 파일을 생성합니다:

module.exports = {
presets: ['next/babel'],
plugins: [
[
'@tracivo/babel-plugin',
{
projectRoot: __dirname,
wrapperImport: '@tracivo/sdk',
// regex 패턴 일치하는 function 로깅 제외
excludeFunctions: [/^use[A-Z]/, /^_/], // React hooks와 private 함수 제외
},
],
],
};

6. Next.js 설정 업데이트

next.config.ts 파일에 Babel 빌드 옵션을 추가합니다:

import type { NextConfig } from 'next';

const nextConfig: NextConfig = {
output: 'standalone',
serverExternalPackages: ['msw'],
experimental: {
forceSwcTransforms: false, // Babel 사용을 위해 SWC 강제 변환 비활성화
},
};

export default nextConfig;