비용 추적은(는) 무엇을 하나요?
이 기술을 사용하여 ECC의 stop:cost-tracker 훅이 기록하는 메트릭 로그에서 Claude Code 비용 및 사용량 내역을 분석하세요.
데이터 위치
추적기는 세션이 종료될 때마다 하나의 JSON 객체를 ~/.claude/metrics/costs.jsonl 파일에 추가합니다. 각 행은 해당 세션의 누적 스냅샷이므로, 총 지출을 계산하려면 session_id별 최신 행을 가져와 모든 세션의 합계를 구해야 합니다. 모든 행을 단순히 합산하면 중복 계산이 발생합니다.
행 스키마:
| 필드 | 의미 |
|---|---|
timestamp | 스냅샷의 ISO 타임스탬프 |
session_id | Claude Code 세션 식별자 |
transcript_path | 세션 기록 파일 경로 |
model | 사용된 모델 |
input_tokens / output_tokens | 토큰 수 |
cache_write_tokens / cache_read_tokens | 프롬프트 캐시 토큰 수 |
estimated_cost_usd | 세션의 USD 누적 예상 비용 |
estimated_cost_usd를 수동 계산보다 우선 사용하세요. 모델 및 캐시 가격은 변경될 수 있으며, 추적기가 신뢰할 수 있는 출처입니다.
사용 시기
- 사용자가 "얼마나 썼지?", "이 세션 비용은 얼마야?" 또는 "내 토큰 사용량은?"과 같이 질문할 때
- 사용자가 예산, 지출 한도, 초과 사용 또는 비용 제어에 대해 언급할 때
- 사용자가 모델, 세션, 날짜별 비용 분석이나 CSV 내보내기를 원할 때
작동 방식
먼저 로그 파일이 존재하는지 확인하세요 (node 사용. sqlite3 사용 금지 — 추적기는 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)?"cost log found":"cost log not found: "+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("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));
'
세션 세부 분석이나 CSV 내보내기를 위해 동일한 latest 집합 (또는 CSV의 경우 원시 행)을 반복하여 필요한 필드를 출력하세요.
보고 지침
비용 데이터를 제시할 때는 오늘 지출과 어제 지출, 전체 세션 합계, 모델별 분석 및 세션 수를 포함하세요. 1달러 미만 금액은 소수점 4자리, 더 큰 금액은 소수점 2자리로 표시하세요.
안티 패턴
- 모든 행을 합산하지 마세요. 각 행은 세션별 누적이므로 먼저
session_id별 최신 행으로 축소해야 합니다. estimated_cost_usd가 있으면 원시 토큰 수로 비용을 추정하지 마세요.- 확인하지 않고 로그가 존재한다고 가정하지 마세요.
- 사용자에게 보여주는 답변에 현재 모델 가격을 하드코딩하지 마세요.
- 임의 코드를 실행하는 검증되지 않은 훅이나 플러그인을 설치하지 마세요.
관련 항목
/cost-report- 동일한 메트릭 로그를 사용하는 명령형 보고서cost-aware-llm-pipeline- 모델 라우팅 및 예산 설계 패턴token-budget-advisor- 컨텍스트 및 토큰 예산 계획strategic-compact- 반복 토큰 지출을 줄이기 위한 컨텍스트 압축