Skip to main content
ClaudeWave
Skill462 estrellas del repoactualizado 3d ago

Code Consistency - Logging & Standards

This Claude Code skill audits Python logging in the taylorsatula/mira-OSS repository for severity level misalignment and incomplete exception handling. It provides a decision tree to categorize log messages from DEBUG through CRITICAL based on their context, then flags common mistakes such as logging caught exceptions as INFO instead of ERROR, treating cache misses as critical failures, and omitting stack traces via logger.exception(). Use when reviewing pull requests or conducting code quality assessments to ensure consistent, appropriate logging practices.

Instalar en Claude Code
Copiar
git clone --depth 1 https://github.com/taylorsatula/mira-OSS /tmp/code-consistency---logging-standards && cp -r /tmp/code-consistency---logging-standards/.claude/skills/checking-code-consistency ~/.claude/skills/code-consistency---logging-standards
Después abre una sesión nueva de Claude Code; el skill carga automáticamente.

SKILL.md

# Code Consistency Checker

Scan Python files for logging issues. Flag incorrect severity levels and missing exception context.

---

## Logging Level Decision Tree

**Ask: What happened in this code?**

```
Variable value, loop iteration, function entry/exit, detailed diagnostics?
  → DEBUG

Successful operation, workflow step completed, state change confirmed?
  → INFO

Unexpected but handled: fallback used, retry attempt, deprecated call, approaching limit?
  → WARNING

Functionality failed: operation error, caught exception, feature broken?
  → ERROR (use logger.exception() in except blocks)

System-wide failure: cannot serve requests, out of resources, imminent crash?
  → CRITICAL
```

---

## Common Logging Mistakes

### Wrong Severity Level

```python
# ❌ WRONG: Exception logged as INFO
try:
    result = risky_operation()
except Exception as e:
    logger.info(f"Operation failed: {e}")  # Should be ERROR

# ✅ CORRECT: Use logger.exception() in except blocks
try:
    result = risky_operation()
except Exception as e:
    logger.exception("Operation failed")  # Automatically ERROR + stack trace
```

```python
# ❌ WRONG: Normal operation logged as ERROR
user = get_user(user_id)
logger.error(f"Retrieved user {user_id}")  # Should be INFO or DEBUG

# ✅ CORRECT: Normal operations are INFO
user = get_user(user_id)
logger.info(f"Retrieved user {user_id}")
```

```python
# ❌ WRONG: Fallback behavior logged as ERROR
cache_value = cache.get(key)
if cache_value is None:
    logger.error("Cache miss, using database")  # Should be WARNING or INFO
    value = db.query(key)

# ✅ CORRECT: Degraded mode is WARNING
cache_value = cache.get(key)
if cache_value is None:
    logger.warning("Cache miss, falling back to database")
    value = db.query(key)
```

```python
# ❌ WRONG: Routine error logged as CRITICAL
if not user_id:
    logger.critical("Missing user_id parameter")  # Should be ERROR
    raise ValueError("user_id required")

# ✅ CORRECT: CRITICAL only for system-wide failures
if connection_pool_exhausted():
    logger.critical("Database connection pool exhausted, cannot serve requests")
    shutdown()
```

### Missing Exception Context

```python
# ❌ WRONG: Missing stack trace
try:
    process_data()
except Exception as e:
    logger.error(f"Failed: {e}")  # No stack trace

# ✅ CORRECT: Use logger.exception() or exc_info=True
try:
    process_data()
except Exception as e:
    logger.exception("Data processing failed")  # Includes stack trace

# ✅ ALSO CORRECT: Explicit exc_info
try:
    process_data()
except Exception as e:
    logger.error("Data processing failed", exc_info=True)
```

### Logger Pattern Violations

```python
# ❌ WRONG: Using root logger
logger = logging.getLogger()
logger.info("message")

# ✅ CORRECT: Named logger
logger = logging.getLogger(__name__)
logger.info("message")
```

```python
# ❌ WRONG: Using print() for logging
print(f"Processing user {user_id}")

# ✅ CORRECT: Use logger
logger.info(f"Processing user {user_id}")
```

### Security Issues

```python
# ❌ WRONG: Logging sensitive data
logger.info(f"User authenticated: {username} / {password}")
logger.debug(f"API request: {api_key}")

# ✅ CORRECT: Redact sensitive information
logger.info(f"User authenticated: {username}")
logger.debug("API request authenticated")
```

---

## Severity Level Guidelines

### DEBUG (Development only, filter out in production)
- Variable values during execution
- Function entry/exit traces
- Loop iteration details
- Cache hits/misses (when debugging)
- Query performance timing
- Internal state inspection

**Production**: Set level to INFO or higher

### INFO (Normal operations)
- User logged in/out
- Batch processing started/completed
- Configuration loaded
- Service started/stopped
- Scheduled job executed
- Workflow step completed
- Major operation succeeded

**If it's expected and good, it's INFO**

### WARNING (Unexpected but handled)
- API rate limit approaching (80% capacity)
- Deprecated function called
- Retry attempt (N of M)
- Using fallback/default value
- Resource usage high but manageable
- Temporary degradation

**If it's weird but working, it's WARNING**

### ERROR (Functionality failed)
- Database query failed
- API call failed
- File not found
- Validation error
- Tool execution failed
- User operation failed
- Any caught exception affecting functionality

**Use `logger.exception()` in except blocks**

### CRITICAL (System failure)
- Database unreachable
- Out of memory
- Connection pool exhausted
- Authentication system down
- Cannot serve requests
- Imminent shutdown

**Should trigger immediate alerts/paging**

---

## Check Execution

1. **Find all logger calls**: `logger.debug/info/warning/error/critical/exception()`

2. **For each call, ask**:
   - What situation triggered this log?
   - Does severity match the decision tree?
   - Is this in an except block? (should use `logger.exception()`)

3. **Check patterns**:
   - Named logger used? (`getLogger(__name__)`)
   - No `print()` statements for operational logging?
   - No sensitive data logged?

4. **Flag issues with**:
   - Line number
   - Current severity vs. correct severity
   - Reason for change

---

## Output Format

```
FILE: path/to/file.py

LOGGING ISSUES:

Line 23: Severity too high
  Current: logger.error("Retrieved user data")
  Should be: logger.info("Retrieved user data")
  Reason: Normal successful operation should be INFO, not ERROR

Line 78: Missing exception context
  Current: logger.error(f"Failed: {e}")
  Should be: logger.exception("Operation failed")
  Reason: Use logger.exception() in except blocks for automatic stack trace

Line 134: Severity too low
  Current: logger.info("API call failed, retrying")
  Should be: logger.warning("API call failed, retrying")
  Reason: Retry indicates unexpected issue, should be WARNING

Line 201: Security violation
  Current: logger.debug(f"Authenticating with token: {api_token}")
  Should be: logger.debug("Authenticating with API")
  Reason: Never log cred
code-renamerSubagent

Use this agent when you need to rename classes, methods, functions, or variables in code files to align with specific naming requirements or conventions. Examples: <example>Context: User wants to clean up function names by removing a specific prefix. user: 'Please remove the prefix get_ from all function names in this file' assistant: 'I'll use the code-renamer agent to systematically rename all functions by removing the get_ prefix' <commentary>The user wants systematic renaming of functions, which is exactly what the code-renamer agent is designed for.</commentary></example> <example>Context: User wants to standardize method naming conventions. user: 'Can you rename all the camelCase methods to snake_case in this class?' assistant: 'I'll use the code-renamer agent to convert all camelCase method names to snake_case convention' <commentary>This is a systematic renaming task that requires careful attention to naming conventions.</commentary></example>

investigative-sidekickSubagent

Use this agent when the user makes offhanded comments, rhetorical questions, or expresses wishes about understanding something better. Trigger on patterns like:\n\n<example>\nContext: User is reviewing code and sees an assistant's explanation about how a function works.\nuser: "Can you believe this? Is this even right?"\nassistant: "Let me use the investigative-sidekick agent to verify if that explanation is accurate."\n<task tool_call to investigative-sidekick with context about what needs verification>\n</example>\n\n<example>\nContext: User is debugging and expresses frustration.\nuser: "I wish I could figure out what's causing this memory leak in the session handler"\nassistant: "I'll use the investigative-sidekick agent to investigate the root cause of that memory leak."\n<task tool_call to investigative-sidekick with the specific problem to investigate>\n</example>\n\n<example>\nContext: User reads a commit message claiming a performance improvement.\nuser: "Did this actually make things faster though?"\nassistant: "Let me launch the investigative-sidekick agent to verify that performance claim."\n<task tool_call to investigative-sidekick to fact-check the performance assertion>\n</example>\n\n<example>\nContext: User is reviewing documentation that seems questionable.\nuser: "This doesn't seem right - are we really supposed to use sync calls in async contexts?"\nassistant: "I'm going to use the investigative-sidekick agent to investigate whether that's actually correct."\n<task tool_call to investigative-sidekick to verify the technical claim>\n</example>\n\nActivate proactively when the user:\n- Questions accuracy or truthfulness ("Can you believe...", "Is this right?", "Really?")\n- Expresses wishes about understanding ("I wish I could figure out...", "I'd love to know...")\n- Shows skepticism ("Did this actually...", "Does this really...")\n- Makes rhetorical questions that imply investigation ("What's causing...", "Why is this...")\n- Doubts explanations or documentation they're reading

thinkSlash Command

Control thinking token limits via environment variable

validate-moduleSlash Command

Run complete two-agent validation on module+tests (contract extraction + test validation). Binary pass/fail with specific issues.

contextvar-opportunity-finderSkill

Detect explicit user_id parameters in functions to identify potential opportunities for using ambient context. This is an investigation tool that flags instances for human review, not a prescriptive analyzer.

contextvar-remediationSkill
fail-fast-no-hedgingSkill

Eliminate component hedging anti-patterns that mask infrastructure failures. Build systems that fail loudly when broken instead of limping along in degraded states. Critical for production reliability and operational visibility.

Git WorkflowSkill

DO NOT COMMIT unless user explicitly tells you to. Use this skill EVERY SINGLE TIME before creating a git commit. Provides mandatory commit message format, staging rules, and post-commit summary requirements for the MIRA project