VibeCoding Logger

repository·main·Indexed 40 days ago

https://github.com/fladdict/vibe-logger

An AI-native logging library for LLM agent development available in Python and TypeScript/Node.js. It generates structured JSON "AI briefing packages" containing rich context, correlation IDs, and dedicated fields like human_note and ai_todo to help LLMs debug and analyze code more effectively. Version 0.1.0.

Tokens
17.6K
Snippets
57
Records
68
Agent score
46%

What's inside VibeLogger

  1. What is the VibeCoding Logger core concept?

    main
    VibeCoding Logger is a specialized logging system designed for AI-driven development. Unlike traditional logs meant for humans, it produces "AI briefing packages"—structured JSON data that provides Large Language Models (LLMs) with rich context, correlation tracking, and embedded human annotations to help them understand and debug code effectively.
  2. What is VibeCoding Logger and how does it work?

    main

    VibeCoding Logger is an "AI-native" logging solution designed for the Vibe Coding methodology (where humans provide natural language instructions and AI generates code).

    Unlike traditional loggers meant for human reading, VibeCoding Logger focuses on creating high-quality, structured data packages (JSON) that maximize information for LLMs. It allows developers to act as "diagnosticians" by providing rich context, stack traces, and direct instructions to the AI (the "surgeon").

    Key conceptual pillars include:

    • Structured JSON Output: Optimized for AI parsing.
    • Rich Context: Captures operations, variable states, and correlation IDs.
    • Human-to-AI Communication: Dedicated fields for human notes and AI tasks.
    • Environment Capture: Automatically records runtime details (OS, language versions) for reproducibility.
  3. Thread-safe logging in Python

    main

    The vibelogger library is fully thread-safe, making it suitable for concurrent or multi-threaded applications.

    import threading
    from vibelogger import create_file_logger
    
    logger = create_file_logger("multi_threaded_app")
    
    def worker(worker_id):
        logger.info(
            operation="worker_task",
            message=f"Worker {worker_id} processing",
            context={"worker_id": worker_id}
        )
    
    # Safe to use across multiple threads
    threads = [threading.Thread(target=worker, args=(i,)) for i in range(10)]
    for t in threads:
        t.start()
  4. Implement correlation tracking for related operations

    main

    To link related operations across your application, provide a correlationId when creating the logger. All subsequent logs from that instance will share the same ID, making it easy for an AI to reconstruct a sequence of events.

    // Use same correlation ID across related operations
    const correlationId = `request-${Date.now()}`;
    const logger = createLogger({ correlationId });
    
    await logger.info('request_start', 'Processing API request');
    await logger.info('auth_check', 'Validating credentials');
    await logger.info('business_logic', 'Executing core logic');
    await logger.info('request_end', 'Request completed');
    
    // All logs will have the same correlation_id
  5. Understand the JSON Log Format

    main

    The vibelogger TypeScript implementation produces JSON logs that are compatible with the Python version. Each log entry follows this structure:

    interface LogEntry {
      timestamp: string;           // ISO 8601 UTC
      level: 'DEBUG' | 'INFO' | 'WARNING' | 'ERROR' | 'CRITICAL';
      correlation_id: string;      // UUID or custom
      operation: string;           // What the code was trying to do
      message: string;            // Human readable message
      context: Record<string, any>; // Rich context data
      environment: EnvironmentInfo; // Runtime environment
      source?: string;            // File location and function
      stack_trace?: string;       // Error stack trace
      human_note?: string;        // Instructions for AI
      ai_todo?: string;          // Specific AI tasks
    }

    Note on Naming: While the TypeScript API uses camelCase for parameters (e.g., humanNote), the exported JSON format uses snake_case (e.g., human_note) to maintain cross-language compatibility.

    interface LogEntry {
      timestamp: string;
      level: 'DEBUG' | 'INFO' | 'WARNING' | 'ERROR' | 'CRITICAL';
      correlation_id: string;
      operation: string;
      message: string;
      context: Record<string, any>;
      environment: EnvironmentInfo;
      source?: string;
      stack_trace?: string;
      human_note?: string;
      ai_todo?: string;
    }
  6. Understand the VibeLogger JSON schema

    main

    VibeLogger emits structured JSON designed for LLM consumption. Key fields include:

    • timestamp: ISO format with UTC timezone
    • level: Log level (e.g., ERROR, INFO)
    • correlation_id: Links related operations across the request
    • operation: The specific task the code was attempting
    • message: Human-readable description
    • context: Structured data like function arguments, variables, or state
    • environment: Runtime info (e.g., python_version, os) for reproduction
    • source: Exact file location and function name
    • human_note: Natural language instructions for the AI
    • ai_todo: Specific analysis requests for the AI
    {
      "timestamp": "2025-07-07T08:36:42.123Z",
      "level": "ERROR", 
      "correlation_id": "req_abc123",
      "operation": "fetchUserProfile",
      "message": "User profile not found",
      "context": {
        "user_id": "user-123",
        "query": "SELECT * FROM users WHERE id = ?"
      },
      "environment": {
        "python_version": "3.11.0",
        "os": "Darwin"
      },
      "source": "/app/user_service.py:42 in get_user_profile()",
      "human_note": "AI-TODO: Check database connection",
      "ai_todo": "Analyze why user lookup is failing"
    }
  7. How logException handles errors

    main

    The logException method is designed to handle both standard Error objects and arbitrary values thrown in JavaScript (like strings or numbers). It normalizes these into a consistent ErrorInfo structure to ensure the JSON log remains predictable.

    • If an Error object is passed, it extracts message, stack, and name.
    • If a primitive is passed (e.g., throw 'error'), it converts the value to a string and sets the name to UnknownError.
    logException(operation: string, error: Error | unknown, options?: LogOptions) {
      const errorInfo = this.extractErrorInfo(error);
      // ... normalization logic
    }
    
    private extractErrorInfo(error: unknown): ErrorInfo {
      if (error instanceof Error) {
        return { message: error.message, stack: error.stack, name: error.name };
      }
      return { message: String(error), stack: undefined, name: 'UnknownError' };
    }
  8. Enable AI-assisted debugging via CLAUDE.md

    main

    To integrate VibeCoding Logger into your AI-driven workflow (e.g., using Claude Code), add the following instructions to your project's CLAUDE.md file. This tells the AI to use the library and where to find debugging data.

    ### Project Logging
    * Use vibelogger library for all logging needs
    * vibelogger instruction: https://github.com/fladdict/vibe-logger/blob/main/README.md
    * Check ./logs/<project_name>/ folder for debugging data when issues occur
    ### Project Logging
    * Use vibelogger library for all logging needs
    * vibelogger instruction: https://github.com/fladdict/vibe-logger/blob/main/README.md
    * Check ./logs/<project_name>/ folder for debugging data when issues occur
  9. Optimize for memory-efficient logging (Python)

    main

    For long-running processes where you want to avoid Out-Of-Memory (OOM) issues, disable in-memory log storage by setting keep_logs_in_memory=False in the VibeLoggerConfig.

    from vibelogger import VibeLoggerConfig, create_logger
    
    # For long-running processes - disable memory storage
    config = VibeLoggerConfig(
        log_file="./logs/production.log",
        keep_logs_in_memory=False,  # Don't store logs in memory
        auto_save=True
    )
    logger = create_logger(config=config)
  10. Quick Start with createFileLogger

    main

    The recommended way to start is using createFileLogger, which automatically manages timestamped log files in a ./logs/ directory. This approach is ideal for capturing rich context for AI analysis.

    import { createFileLogger } from 'vibelogger';
    
    // Create logger with auto-save to timestamped file
    const logger = createFileLogger('my-project');
    
    // Log with rich context for AI analysis
    await logger.info('user_login', 'User authentication started', {
      context: {
        userId: '123',
        method: 'oauth',
        ipAddress: '192.168.1.100'
      },
      humanNote: 'Monitor for suspicious patterns',
      aiTodo: 'Check if multiple failed attempts from this IP'
    });
    
    // Log exceptions with full context
    try {
      await riskyOperation();
    } catch (error) {
      await logger.logException('payment_processing', error, {
        context: { orderId: 'order-123', amount: 99.99 },
        aiTodo: 'Suggest error handling improvements'
      });
    }
    
    // Get logs formatted for AI analysis
    const aiContext = await logger.getLogsForAI();
    console.log(aiContext); // Send this to your LLM