home / skills / athola / claude-night-market / usage-logging

This skill helps you implement robust usage logging and audit trails across services for analytics, costs, and debugging.

npx playbooks add skill athola/claude-night-market --skill usage-logging

Review the files below or copy the command above to add this skill to your agents.

Files (3)
SKILL.md
4.2 KB
---
name: usage-logging
description: Consult this skill when implementing usage logging and audit trails.
  Use when implementing audit trails, tracking costs, collecting usage analytics,
  managing session logging. Do not use when simple operations without logging needs.
category: infrastructure
tags:
- logging
- usage
- audit
- metrics
- sessions
- analytics
dependencies: []
tools:
- usage-logger
provides:
  infrastructure:
  - usage-logging
  - session-management
  - audit-trails
  patterns:
  - structured-logging
  - metrics-collection
  - cost-tracking
usage_patterns:
- audit-logging
- cost-tracking
- usage-analytics
- session-management
complexity: beginner
estimated_tokens: 450
progressive_loading: true
modules:
- modules/session-patterns.md
- modules/log-formats.md
---
## Table of Contents

- [Overview](#overview)
- [When to Use](#when-to-use)
- [Core Concepts](#core-concepts)
- [Session Management](#session-management)
- [Log Entry Structure](#log-entry-structure)
- [Quick Start](#quick-start)
- [Initialize Logger](#initialize-logger)
- [Log Operations](#log-operations)
- [Query Usage](#query-usage)
- [Integration Pattern](#integration-pattern)
- [Log Storage](#log-storage)
- [Detailed Resources](#detailed-resources)
- [Exit Criteria](#exit-criteria)


# Usage Logging

## Overview

Session-aware logging infrastructure for tracking operations across plugins. Provides structured JSONL logging with automatic session management for audit trails and analytics.

## When To Use

- Need audit trails for operations
- Tracking costs across sessions
- Building usage analytics
- Debugging with operation history

## When NOT To Use

- Simple operations without logging needs

## Core Concepts

### Session Management

Sessions group related operations:
- Auto-created on first operation
- Timeout after 1 hour of inactivity
- Unique session IDs for tracking

### Log Entry Structure

```json
{
  "timestamp": "2025-12-05T10:30:00Z",
  "session_id": "session_1733394600",
  "service": "my-service",
  "operation": "analyze_files",
  "tokens": 5000,
  "success": true,
  "duration_seconds": 2.5,
  "metadata": {}
}
```
**Verification:** Run the command with `--help` flag to verify availability.

## Quick Start

### Initialize Logger
```python
from leyline.usage_logger import UsageLogger

logger = UsageLogger(service="my-service")
```
**Verification:** Run the command with `--help` flag to verify availability.

### Log Operations
```python
logger.log_usage(
    operation="analyze_files",
    tokens=5000,
    success=True,
    duration=2.5,
    metadata={"files": 10}
)
```
**Verification:** Run the command with `--help` flag to verify availability.

### Query Usage
```python
# Recent operations
recent = logger.get_recent_operations(hours=24)

# Usage summary
summary = logger.get_usage_summary(days=7)
print(f"Total tokens: {summary['total_tokens']}")
print(f"Total cost: ${summary['estimated_cost']:.2f}")

# Recent errors
errors = logger.get_recent_errors(count=10)
```
**Verification:** Run the command with `--help` flag to verify availability.

## Integration Pattern

```yaml
# In your skill's frontmatter
dependencies: [leyline:usage-logging]
```
**Verification:** Run the command with `--help` flag to verify availability.

Standard integration flow:
1. Initialize logger for your service
2. Log operations after completion
3. Query for analytics and debugging

## Log Storage

Default location: `~/.claude/leyline/usage/{service}.jsonl`

```bash
# View recent logs
tail -20 ~/.claude/leyline/usage/my-service.jsonl | jq .

# Query by date
grep "2025-12-05" ~/.claude/leyline/usage/my-service.jsonl
```
**Verification:** Run the command with `--help` flag to verify availability.

## Detailed Resources

- **Session Patterns**: See `modules/session-patterns.md` for session management
- **Log Formats**: See `modules/log-formats.md` for structured formats

## Exit Criteria

- Operation logged with all required fields
- Session tracked for grouping
- Logs queryable for analytics
## Troubleshooting

### Common Issues

**Command not found**
Ensure all dependencies are installed and in PATH

**Permission errors**
Check file permissions and run with appropriate privileges

**Unexpected behavior**
Enable verbose logging with `--verbose` flag

Overview

This skill provides session-aware usage logging and audit-trail utilities for plugins and services. It emits structured JSONL records with session IDs, timestamps, duration, token counts, and metadata to support cost tracking, analytics, and debugging. The logger auto-manages sessions with timeouts and stores logs in a local JSONL file per service.

How this skill works

Initialize a UsageLogger for your service, then call log_usage after each operation to record a standardized entry. The logger auto-creates and maintains session IDs (timeout after one hour of inactivity) and writes JSONL lines to a per-service file. Query helpers return recent operations, summaries (tokens and estimated cost), and recent errors for analytics and troubleshooting.

When to use it

  • You need immutable audit trails for user or system actions
  • Track tokens, duration, and estimated costs across sessions
  • Collect usage analytics for billing or product insights
  • Correlate operations during debugging or incident investigations
  • Manage session-scoped logging for multi-step workflows

Best practices

  • Initialize one logger per service/component and reuse it across requests
  • Log after operation completion to capture success, duration, and actual token counts
  • Include minimal structured metadata (IDs, file counts) for useful queries without sensitive data
  • Rotate or archive JSONL files for long-running services and back them up for audits
  • Restrict file permissions and sanitize metadata to avoid logging secrets

Example use cases

  • Track API call token usage and estimate cost per customer for billing reports
  • Record multi-step plugin sessions to reconstruct user flows during bug reviews
  • Capture recent errors and their session context to speed incident investigation
  • Aggregate weekly usage summaries to inform quota limits and pricing decisions
  • Store operation histories to satisfy compliance-audit requests

FAQ

Where are logs stored by default?

Logs are saved as JSONL at ~/.claude/leyline/usage/{service}.jsonl by default.

How are sessions managed?

Sessions are auto-created on the first logged operation and timeout after one hour of inactivity; each session gets a unique ID for grouping operations.

How do I get usage summaries?

Use get_usage_summary(days=n) to aggregate tokens and estimated cost; use get_recent_operations(hours=n) and get_recent_errors(count=n) for detailed views.