Claude 코드 사용량
토큰 소비, 비용, 성능 지표 및 사용량 최적화를 추적하기 위한 포괄적인 Claude 코드 사용량 모니터링 및 분석 도구.
개요
Claude 코드 사용량 도구는 Claude 코드 토큰 소비 및 API 사용에 대한 실시간 모니터링, 분석 및 최적화 기능을 제공합니다. 이러한 도구는 개발자가 비용을 추적하고, 성능을 모니터링하며, 사용 패턴을 분석하고, 상세한 지표, 알림 및 보고 기능을 통해 Claude 코드 워크플로우를 최적화하는 데 도움을 줍니다.
⚠️ 사용 안내: 사용량 모니터링 도구는 Claude 코드 세션 파일 및 API 로그에 대한 접근이 필요합니다. 모니터링 솔루션을 구현할 때 적절한 권한 및 데이터 개인정보 보호 규정을 준수하세요.
핵심 도구
Claude 코드 사용량 모니터
# Install via npm
npm install -g claude-code-usage-monitor
# Install via pip
pip install claude-code-usage-monitor
# Clone from GitHub
git clone https://github.com/Maciek-roboblog/Claude-Code-Usage-Monitor.git
cd Claude-Code-Usage-Monitor
npm install
npm start
ccusage CLI 도구
# Install ccusage
npm install -g ccusage
# Basic usage analysis
ccusage analyze
# Analyze specific session
ccusage analyze --session session-id
# Generate report
ccusage report --format json
# Real-time monitoring
ccusage monitor --live
설치 및 설정
사용량 모니터 설정
# Start usage monitor
claude-usage-monitor --port 3000
# With configuration file
claude-usage-monitor --config config.json
# Docker deployment
docker run -p 3000:3000 -v ~/.claude:/data claude-usage-monitor
VS Code 확장 프로그램
# Install from marketplace
code --install-extension suzuki0430.ccusage-vscode
# Manual installation
git clone https://github.com/suzuki0430/ccusage-vscode.git
cd ccusage-vscode
npm install
npm run compile
code --install-extension ccusage-vscode-*.vsix
Raycast 확장 프로그램
# Install Raycast extension
raycast://extensions/nyatinte/ccusage
# Configure API access
raycast://preferences/extensions/ccusage
모니터링 명령어
실시간 모니터링
| 명령어 | 설명 |
|---|---|
ccusage monitor | 실시간 모니터링 시작 |
ccusage dashboard | 웹 대시보드 열기 |
ccusage status | 현재 사용 상태 확인 |
ccusage alerts | 활성 알림 보기 |
ccusage live | 라이브 사용 스트림 |
ccusage watch | 특정 메트릭 보기 |
ccusage tail | 테일 사용 로그 |
분석 명령어
| 명령어 | 설명 |
|---|---|
ccusage analyze | 사용 패턴 분석 |
ccusage report | 사용 보고서 생성 |
ccusage summary | 사용 요약 |
ccusage trends | 사용 트렌드 분석 |
ccusage compare | 시간 기간 비교하기 |
ccusage breakdown | 상세 분석 |
ccusage optimize | 최적화 제안 |
구성
모니터 구성
{
"monitor": {
"port": 3000,
"host": "localhost",
"updateInterval": 1000,
"retentionDays": 30,
"enableAlerts": true
},
"claude": {
"sessionPath": "~/.claude/sessions",
"logPath": "~/.claude/logs",
"apiEndpoint": "https://api.anthropic.com",
"trackModels": ["claude-3-sonnet", "claude-3-haiku", "claude-3-opus"]
},
"metrics": {
"trackTokens": true,
"trackCosts": true,
"trackPerformance": true,
"trackErrors": true,
"granularity": "minute"
},
"alerts": {
"dailyLimit": 10000,
"costThreshold": 50.00,
"errorRate": 0.05,
"responseTime": 5000
}
}
비용 추적
{
"costTracking": {
"enabled": true,
"currency": "USD",
"models": {
"claude-3-opus": {
"inputCost": 0.000015,
"outputCost": 0.000075
},
"claude-3-sonnet": {
"inputCost": 0.000003,
"outputCost": 0.000015
},
"claude-3-haiku": {
"inputCost": 0.00000025,
"outputCost": 0.00000125
}
},
"budgets": {
"daily": 25.00,
"weekly": 150.00,
"monthly": 500.00
}
}
}
대시보드 기능
웹 대시보드
# Access dashboard
http://localhost:3000
# Dashboard sections
- Real-time metrics
- Usage graphs
- Cost analysis
- Session history
- Performance metrics
- Alert management
- Export options
대시보드 구성 요소
| 컴포넌트 | 설명 |
|---|---|
Token Counter | 실시간 토큰 사용량 |
Cost Tracker | 현재 및 예상 비용 |
Session Browser | 세션 기록 찾아보기 |
Performance Graph | 응답 시간 메트릭스 |
Error Monitor | 오류율 추적 |
Usage Heatmap | 사용 패턴 시각화 |
Alert Panel | 활성 알림 및 알림 |
지표 표시
// Dashboard metrics configuration
const dashboardConfig = {
widgets: [
{
type: "counter",
metric: "tokens_today",
title: "Today's Tokens",
format: "number"
},
{
type: "gauge",
metric: "cost_today",
title: "Today's Cost",
format: "currency",
max: 50
},
{
type: "chart",
metric: "tokens_hourly",
title: "Hourly Usage",
timeRange: "24h"
},
{
type: "table",
metric: "top_sessions",
title: "Top Sessions",
limit: 10
}
],
refreshInterval: 5000,
theme: "dark"
};
사용량 분석
토큰 분석
# Analyze token usage
ccusage tokens --period today
ccusage tokens --period week
ccusage tokens --period month
# Token breakdown by model
ccusage tokens --by-model
# Token efficiency analysis
ccusage tokens --efficiency
# Token usage trends
ccusage tokens --trends
비용 분석
# Cost breakdown
ccusage costs --breakdown
# Cost by time period
ccusage costs --period month
# Cost optimization suggestions
ccusage costs --optimize
# Budget tracking
ccusage costs --budget-status
# Cost projections
ccusage costs --forecast
성능 분석
# Response time analysis
ccusage performance --response-time
# Throughput analysis
ccusage performance --throughput
# Error rate analysis
ccusage performance --errors
# Performance trends
ccusage performance --trends
# Bottleneck identification
ccusage performance --bottlenecks
보고
보고서 생성
# Generate daily report
ccusage report --period today --format pdf
# Weekly summary
ccusage report --period week --format html
# Monthly analysis
ccusage report --period month --format json
# Custom date range
ccusage report --from 2025-07-01 --to 2025-07-15
# Detailed breakdown
ccusage report --detailed --include-sessions
보고서 형식
| 형식 | 설명 |
|---|---|
JSON | 기계 판독 가능한 데이터 |
CSV | 스프레드시트 호환 |
HTML | 웹에서 볼 수 있는 보고서 |
PDF | 인쇄 가능한 문서 |
Markdown | 문서 형식 |
Excel | 고급 스프레드시트 |
자동 보고
{
"automation": {
"reports": [
{
"name": "daily_summary",
"schedule": "0 9 * * *",
"format": "email",
"recipients": ["team@company.com"],
"template": "daily_template"
},
{
"name": "weekly_analysis",
"schedule": "0 9 * * 1",
"format": "pdf",
"storage": "s3://reports-bucket/weekly/",
"template": "weekly_template"
}
]
}
}
알림 시스템
알림 구성
The remaining placeholders (3-20) are left blank as no specific text was provided for translation.```json { “alerts”: { “rules”: [ { “name”: “high_token_usage”, “condition”: “tokens_per_hour > 5000”, “severity”: “warning”, “actions”: [“email”, “slack”] }, { “name”: “budget_exceeded”, “condition”: “daily_cost > budget.daily * 0.9”, “severity”: “critical”, “actions”: [“email”, “sms”, “webhook”] }, { “name”: “high_error_rate”, “condition”: “error_rate > 0.05”, “severity”: “warning”, “actions”: [“slack”] } ], “channels”: { “email”: { “smtp”: “smtp.gmail.com”, “from”: “alerts@company.com”, “to”: [“admin@company.com”] }, “slack”: { “webhook”: “https://hooks.slack.com/…”, “channel”: “#claude-alerts” }, “webhook”: { “url”: “https://api.company.com/alerts”, “method”: “POST” } } } }
| 알림 | 트리거 | 액션 |
|---------|-------------|-------------|
| `Token Limit` | 일일 토큰 임계값 | 이메일 알림 |
| `Cost Threshold` | 예산 비율 | Slack 알림 |
| `Error Rate` | 높은 오류 비율 | 웹훅 호출 |
| `Performance` | 느린 응답 시간 | 대시보드 하이라이트 |
| `Session Limit` | 최대 세션 수에 도달했습니다 | 자동 정리 |## 최적화 기능```bash
# Analyze optimization opportunities
ccusage optimize --analyze
# Token efficiency suggestions
ccusage optimize --tokens
# Cost reduction recommendations
ccusage optimize --costs
# Performance improvements
ccusage optimize --performance
# Model selection optimization
ccusage optimize --models
```### 사용량 최적화```json
{
"optimization": {
"strategies": [
{
"name": "model_selection",
"description": "Choose optimal model for task",
"rules": [
{
"condition": "task_complexity < 0.3",
"recommendation": "claude-3-haiku"
},
{
"condition": "task_complexity >= 0.7",
"recommendation": "claude-3-opus"
}
]
},
{
"name": "context_optimization",
"description": "Optimize context window usage",
"techniques": [
"context_compression",
"selective_history",
"smart_truncation"
]
}
]
}
}
```### 최적화 전략```yaml
# GitHub Actions workflow
name: Claude Usage Monitoring
on:
schedule:
- cron: '0 */6 * * *'
jobs:
monitor:
runs-on: ubuntu-latest
steps:
- name: Check Usage
run: |
ccusage analyze --format json > usage.json
ccusage costs --budget-check
- name: Upload Report
uses: actions/upload-artifact@v2
with:
name: usage-report
path: usage.json
```## 통합 예시```javascript
// Slack bot for usage monitoring
const { App } = require('@slack/bolt');
const app = new App({
token: process.env.SLACK_BOT_TOKEN,
signingSecret: process.env.SLACK_SIGNING_SECRET
});
app.command('/claude-usage', async ({ command, ack, respond }) => {
await ack();
const usage = await getClaudeUsage();
await respond({
text: `Claude Usage Today:
Tokens: ${usage.tokens}
Cost: $${usage.cost}
Sessions: ${usage.sessions}`
});
});
```### CI/CD 통합```yaml
# Prometheus configuration
global:
scrape_interval: 15s
scrape_configs:
- job_name: 'claude-usage'
static_configs:
- targets: ['localhost:3000']
metrics_path: '/metrics'
scrape_interval: 30s
```### Slack 통합```bash
# Get current usage
GET /api/usage/current
# Get usage history
GET /api/usage/history?period=7d
# Get cost breakdown
GET /api/costs/breakdown
# Get performance metrics
GET /api/performance/metrics
# Get alerts
GET /api/alerts
# Export data
GET /api/export?format=json&period=month
```### Prometheus 통합```javascript
// Real-time usage updates
const ws = new WebSocket('ws://localhost:3000/ws');
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
switch(data.type) {
case 'usage_update':
updateUsageDisplay(data.usage);
break;
case 'alert':
showAlert(data.alert);
break;
case 'cost_update':
updateCostDisplay(data.cost);
break;
}
};
```## API 참조```bash
# Monitor not starting
- Check port availability
- Verify session file permissions
- Check configuration file syntax
- Review log files
# Missing data
- Verify Claude Code session path
- Check file permissions
- Ensure proper API access
- Review data retention settings
# Performance issues
- Reduce monitoring frequency
- Optimize database queries
- Clear old data
- Check system resources
```### REST API 엔드포인트```bash
# Enable debug mode
DEBUG=ccusage:* ccusage monitor
# Verbose logging
ccusage --verbose analyze
# Test configuration
ccusage config --test
# Validate data sources
ccusage validate --sources
```### WebSocket APIhttps://github.com/Maciek-roboblog/Claude-Code-Usage-Monitor#
# 문제 해결https://github.com/ryoppippi/ccusage##
# 일반적인 문제https://marketplace.visualstudio.com/items?itemName=suzuki0430.ccusage-vscode##
# 디버그 명령https://www.raycast.com/nyatinte/ccusage#
# 리소스https://docs.claude-usage.dev/- [Claude Code 사용량 모니터 GitHub](