옵션

cost-tracking

affaan-m/ECC affaan-m/ECC

로컬 ECC 비용 추적기 메트릭스 로그에서 Claude Code 토큰 사용량, 지출 및 예산을 분석합니다. 요약 정보, 모델별·세션별·날짜별 세부 내역 및 CSV 내보내기 기능을 제공합니다.

...모든 것을 확장하십시오
32
업데이트 된 시간 2026년 10월 2일

비용 추적

이 스킬을 사용하여 ECC의 stop:cost-tracker 후크가 기록하는 메트릭스 로그에서 Claude Code의 비용 및 사용 내역을 분석할 수 있습니다.

데이터 저장 위치

트래커는 세션 종료(session-stop)마다 하나의 JSON 객체를 ~/.claude/metrics/costs.jsonl 파일에 추가합니다. 각 행은 해당 세션에 대한 누적 스냅샷이므로, 총 지출액을 계산하려면 session_id별로 최신 행을 선택하고 세션 간 합계를 구해야 합니다. 모든 행을 합산하면 중복 계산됩니다.

행 스키마:

필드 의미
timestamp 스냅샷의 ISO 타임스탬프
session_id Claude Code 세션 식별자
transcript_path 세션 기록의 경로
model 사용된 모델
입력 토큰 / 출력 토큰 토큰 수
cache_write_tokens / cache_read_tokens 프롬프트 캐시 토큰 수
estimated_cost_usd 세션에 대한 미리 계산된 누적 비용(USD)

가격을 수동으로 계산하는 것보다 estimated_cost_usd를 우선적으로 사용하십시오. 모델 및 캐시 가격은 변동할 수 있으며, 트래커가 가장 신뢰할 수 있는 정보원입니다.

사용 시점

  • 사용자가 “지금까지 얼마를 지출했나요?”, “이 세션 비용은 얼마인가요?”, 또는 “토큰 사용량은 얼마인가요?”라고 질문할 때
  • 사용자가 예산, 지출 한도, 초과 지출 또는 비용 관리에 대해 언급할 때.
  • 사용자가 모델, 세션 또는 날짜별 비용 내역을 원하거나 CSV로 내보내기를 요청할 때.

작동 방식

먼저 로그가 존재하는지 확인합니다( sqlite3가 아닌 node를 사용하세요. 트래커는 JSONL 형식으로 기록하며, node는 크로스 플랫폼입니다):

node -e 'const fs=require("fs"),os=require("os"),p=require("path");const f=p.join(os.homedir(),".claude","metrics","costs.jsonl");console.log(fs.existsSync(f)?"비용 로그 발견":"비용 로그 미발견: "+f)'

로그가 없는 경우, 사용량 데이터를 임의로 생성하지 마십시오. 사용자에게 비용 추적 데이터는 stop:cost-tracker 훅이 활성화된 상태에서 첫 번째 세션이 종료된 후에 채워진다는 점을 안내하십시오.

예시 — 모델별 지난 7일간의 요약

node -e '
const fs=require("fs"),os=require("os"),path=require("path");
const f=path.join(os.homedir(),".claude","metrics","costs.jsonl");
if(!fs.existsSync(f)){console.log("비용 로그를 찾을 수 없음: "+f);process.exit(0);}
const rows=fs.readFileSync(f,"utf8").split(/\r?\n/).filter(Boolean).map(l=>{try{return JSON.parse(l)}catch{return null}}).filter(Boolean);
const bySession = new Map();
for (const r of rows) { const k = r.session_id || r.transcript_path || r.timestamp; const p = bySession.get(k); if (!p || String(r.timestamp)>String(p.timestamp)) bySession.set(k, r);}
const latest = [...bySession.values()];
const cost = r => Number(r.estimated_cost_usd) || 0, day = r => String(r.timestamp || "").slice(0, 10), sum = a => a.reduce((s, r) => s + cost(r), 0), f4 = n => "$" + n.toFixed(4);
const today = new Date().toISOString().slice(0, 10), yest = new Date(Date.now() - 864e5).toISOString().slice(0, 10);
console.log("오늘: " + f4(sum(latest.filter(r => day(r) === today))) + " | 어제: " + f4(sum(latest.filter(r => day(r) === yest))) + " | 총계: " + f4(sum(latest)) + " (" + latest.length + " 세션)");
const m=new Map();for(const r of latest){const k=r.model||"(unknown)";m.set(k,(m.get(k)||0)+cost(r));}
console.log("모델별:");[...m.entries()].sort((a,b)=>b[1]-a[1]).forEach(([k,v])=>console.log("  "+f4(v)+"  "+k));
'

세션 드릴다운이나 CSV 내보내기의 경우, 동일한 최신 세트(또는 CSV의 경우 원시 행)를 반복 처리하여 필요한 필드를 출력합니다.

보고 지침

비용 데이터를 제시할 때는 오늘의 지출액과 어제의 지출액 비교, 모든 세션의 총합, 모델별 내역, 세션 수를 포함하십시오. 1달러 미만의 금액은 소수점 넷째 자리까지, 그 이상의 금액은 소수점 둘째 자리까지 표시하십시오.

반대 패턴

  • 모든 행을 합산하지 마십시오. 데이터는 세션별로 누적된 것이므로, 먼저 session_id 별로 최신 행으로 필터링하십시오.
  • estimated_cost_usd가 있는 경우, 원시 토큰 수를 바탕으로 비용을 추정하지 마십시오.
  • 확인 없이 로그가 존재한다고 가정하지 마십시오.
  • 사용자에게 표시되는 답변에 현재 모델의 가격을 하드코딩하지 마십시오.
  • 임의의 코드를 실행하는, 검토되지 않은 후크나 플러그인의 설치를 권장하지 마십시오.

관련 항목

  • /cost-report - 동일한 메트릭스 로그에 대한 명령형 보고서.
  • cost-aware-llm-pipeline - 모델 라우팅 및 예산 설계 패턴.
  • token-budget-advisor - 컨텍스트 및 토큰 예산 계획.
  • strategic-compact - 반복적인 토큰 소모를 줄이기 위한 컨텍스트 압축.
GitHub에서 보기
---
name: cost-tracking
description: Analyze Claude Code token usage, spending, and budgets from the local ECC cost-tracker metrics log. Provides summaries, breakdowns by model, session, or date, and CSV export.
---

# Cost Tracking

Use this skill to analyze Claude Code cost and usage history from the metrics log
that ECC's `stop:cost-tracker` hook writes.

## Where the data lives

The tracker appends one JSON object per session-stop to
`~/.claude/metrics/costs.jsonl`. Each row is a **cumulative snapshot for that
session**, so to total spend you take the **latest row per `session_id`** and
sum across sessions — summing every row multiply-counts.

Row schema:

| Field | Meaning |
| --- | --- |
| `timestamp` | ISO timestamp of the snapshot |
| `session_id` | Claude Code session identifier |
| `transcript_path` | Path to the session transcript |
| `model` | Model used |
| `input_tokens` / `output_tokens` | Token counts |
| `cache_write_tokens` / `cache_read_tokens` | Prompt-cache token counts |
| `estimated_cost_usd` | Precomputed cumulative cost in USD for the session |

Prefer `estimated_cost_usd` over hand-calculating pricing — model and cache
prices change, and the tracker is the source of truth.

## When to Use

- The user asks "how much have I spent?", "what did this session cost?", or
  "what is my token usage?"
- The user mentions budgets, spending limits, overruns, or cost controls.
- The user wants a cost breakdown by model, session, or date, or a CSV export.

## How It Works

First verify the log exists (use `node`, not `sqlite3` — the tracker writes
JSONL, and `node` is cross-platform):

```bash
node -e 'const fs=require("fs"),os=require("os"),p=require("path");const f=p.join(os.homedir(),".claude","metrics","costs.jsonl");console.log(fs.existsSync(f)?"cost log found":"cost log not found: "+f)'
```

If the log is missing, do not fabricate usage data. Tell the user that cost
tracking populates after the first session ends with the `stop:cost-tracker`
hook enabled.

## Example — summary, by model, last 7 days

```bash
node -e '
const fs=require("fs"),os=require("os"),path=require("path");
const f=path.join(os.homedir(),".claude","metrics","costs.jsonl");
if(!fs.existsSync(f)){console.log("cost log not found: "+f);process.exit(0);}
const rows=fs.readFileSync(f,"utf8").split(/\r?\n/).filter(Boolean).map(l=>{try{return JSON.parse(l)}catch{return null}}).filter(Boolean);
const bySession=new Map();
for(const r of rows){const k=r.session_id||r.transcript_path||r.timestamp;const p=bySession.get(k);if(!p||String(r.timestamp)>String(p.timestamp))bySession.set(k,r);}
const latest=[...bySession.values()];
const cost=r=>Number(r.estimated_cost_usd)||0, day=r=>String(r.timestamp||"").slice(0,10), sum=a=>a.reduce((s,r)=>s+cost(r),0), f4=n=>"$"+n.toFixed(4);
const today=new Date().toISOString().slice(0,10), yest=new Date(Date.now()-864e5).toISOString().slice(0,10);
console.log("today: "+f4(sum(latest.filter(r=>day(r)===today)))+" | yesterday: "+f4(sum(latest.filter(r=>day(r)===yest)))+" | total: "+f4(sum(latest))+" ("+latest.length+" sessions)");
const m=new Map();for(const r of latest){const k=r.model||"(unknown)";m.set(k,(m.get(k)||0)+cost(r));}
console.log("by model:");[...m.entries()].sort((a,b)=>b[1]-a[1]).forEach(([k,v])=>console.log("  "+f4(v)+"  "+k));
'
```

For a session drilldown or CSV export, iterate the same `latest` set (or the raw
rows for CSV) and print the fields you need.

## Reporting Guidance

When presenting cost data, include today's spend vs yesterday, total across all
sessions, a by-model breakdown, and session count. Format sub-dollar amounts
with four decimals, larger amounts with two.

## Anti-Patterns

- Do not sum every row — they are cumulative per session; reduce to the latest
  row per `session_id` first.
- Do not estimate costs from raw token counts when `estimated_cost_usd` is present.
- Do not assume the log exists without checking.
- Do not hard-code current model pricing in user-facing answers.
- Do not recommend installing unreviewed hooks or plugins that execute arbitrary code.

## Related

- `/cost-report` - Command-form report over the same metrics log.
- `cost-aware-llm-pipeline` - Model-routing and budget-design patterns.
- `token-budget-advisor` - Context and token-budget planning.
- `strategic-compact` - Context compaction to reduce repeated token spend.

모든 파일

1개 파일

cost-tracking 설치

스킬 파일을 다운로드하여 .claude/skills/ 디렉터리에 압축을 풀어주세요.

ZIP 다운로드

저장소를 클론하고 스킬 파일을 프로젝트에 복사하세요.

git clone https://github.com/affaan-m/ECC/tree/main/skills/cost-tracking # Copy SKILL.md to your .claude/skills/ directory

복사 복사
빠른 설정: 스킬 폴더를 .claude/skills/로 복사하세요. Claude가 해당 스킬을 자동으로 감지하여 사용합니다.
저장소 affaan-m/ECC

관련 스킬

airtable-automation
업데이트 된 시간 2026년 6월 29일
notion-automation
업데이트 된 시간 2026년 6월 29일
seo-programmatic
업데이트 된 시간 2026년 6월 29일
revops
업데이트 된 시간 2026년 6월 29일
OR