# ControlTheory Documentation

The runtime feedback loop for AI-generated code

{% columns %}
{% column %}

<figure><img src="/files/Cph3qdd64hWQOwXkSKIG" alt=""><figcaption></figcaption></figure>
{% endcolumn %}

{% column %}

<figure><img src="/files/ro7GT9f08mBlb6USJOrf" alt=""><figcaption></figcaption></figure>
{% endcolumn %}
{% endcolumns %}

Documentation for ControlTheory's two products:

* [**Dstl8**](https://docs.controltheory.com/controltheory-documentation/dstl8-docs) is the runtime feedback loop for AI-generated code, powered by our Möbius AI agent for root cause analysis, impact assessment, and fix recommendations. Available in Pro, Scale, and Enterprise tiers. Dstl8 ingests logs from sources like Vercel, Supabase, Kubernetes, CloudWatch, GitHub Actions, and any OTLP exporter, organizes them into streams and workspaces, and runs an AI agent (Möbius) over the data for incident detection and analysis. Context streams back into Claude Code, Cursor, and your dev flow.
* [**Gonzo**](https://docs.controltheory.com/controltheory-documentation/gonzo-docs) is an open-source terminal UI for log analysis. It reads logs from files, stdin, or OTLP and renders charts, severity counts, and pattern detection in real time. MIT licensed, written in Go, installs via Homebrew, Go, or a single binary.

#### Get started

**Dstl8**

* [Sign up](https://app.dstl8.ai/lp/dstl8-signup)
* [Add your first source](https://docs.controltheory.com/controltheory-documentation/dstl8-docs/sources)
* [Connect Möbius to Claude Code or Cursor](https://docs.controltheory.com/controltheory-documentation/dstl8-docs/mcp-integration)

**Gonzo**

* [Installation](https://docs.controltheory.com/controltheory-documentation/gonzo-docs/getting-started/installation)
* [Quick start](https://docs.controltheory.com/controltheory-documentation/gonzo-docs/getting-started/quick-start)
* [Command line reference](https://docs.controltheory.com/controltheory-documentation/gonzo-docs/configuration/command-line-reference)

#### Reference

* [Gonzo on GitHub](https://github.com/control-theory/gonzo)
* [ControlTheory website](https://www.controltheory.com) for blog posts, talks, and company information.


# Gonzo Docs

Gonzo is a Go-based TUI (Terminal User Interface) log analysis tool that helps you analyze log streams with beautiful charts, AI-powered insights, and advanced filtering - all from your terminal.

<figure><img src="/files/nshjiF9YzflQAohQQNE0" alt="" width="375"><figcaption></figcaption></figure>

> Gonzo: a powerful, real-time log analysis terminal UI inspired by [k9s](https://k9scli.io/).

<figure><img src="/files/PVam54QRgI8slllLJwlT" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
🆕 Press `d` from any Gonzo view to launch [Dstl8.Lite](/controltheory-documentation/gonzo-docs/dstl8.lite-gui), a local browser-based dashboard powered by Gonzo.
{% endhint %}

### ✨ Key Features

* **Live Streaming** - Process logs as they arrive from stdin, files, or network
* **OTLP Native** - First-class support for OpenTelemetry (OTLP) log format
* **Dstl8.Lite GUI** - Press `d` to launch a local browser dashboard with workspaces, log search, and severity heatmaps
* **Format Detection** - Automatically detects JSON, logfmt, and plain text
* **k9s-Inspired Layout** - Familiar 2x2 grid interface
* **Real-time Charts** - Word frequency, attributes, severity distribution, and time series
* **AI Analysis** - Get intelligent insights about log patterns and anomalies
* **Smart Navigation** - Keyboard + mouse controls with vim-style shortcuts

### 🚀 Quick Start

Install Gonzo using your preferred method:

{% tabs %}
{% tab title="Go Install" %}

```bash
go install github.com/control-theory/gonzo/cmd/gonzo@latest
```

{% endtab %}

{% tab title="Homebrew" %}

```bash
brew install gonzo
```

{% endtab %}

{% tab title="Binary Download" %}
Download the latest release for your platform from the [releases page](https://github.com/control-theory/gonzo/releases).
{% endtab %}
{% endtabs %}

Start analyzing logs immediately:

```bash
# Analyze a log file
gonzo -f application.log

# Follow logs in real-time
gonzo -f /var/log/app.log --follow

# Analyze logs from stdin (traditional way)
cat application.log | gonzo

# Pipe from other commands
kubectl logs -f deployment/my-app | gonzo

# Grab Kubernetes logs natively (using kubeconfig)
gonzo --k8s-enabled=true
```

### 📖 Documentation Sections

{% hint style="info" %}
**New to Gonzo?** Start with the [Getting Started](/controltheory-documentation/gonzo-docs/getting-started) section for installation and basic usage.
{% endhint %}

#### Essential Reading

* **Installation** - Get Gonzo up and running
* **Quick Start** - Your first log analysis
* **Interface Overview** - Understanding the dashboard

#### Core Features

* **Log Input Methods** - Files, stdin, and OTLP
* **Patterns** - Bubble up patterns and severity across your logs
* **Filtering & Search** - Find what matters
* **AI Integration** - (Optional) Intelligent log insights

#### Advanced Usage

* **Configuration** - Customize your experience
* **Integration Examples** - Real-world scenarios
* **Troubleshooting** - Common issues and solutions

### 🔗 Links

* **GitHub Repository:** [control-theory/gonzo](https://github.com/control-theory/gonzo)
* **Report Issues:** [GitHub Issues](https://github.com/control-theory/gonzo/issues)
* **Discussions:** [GitHub Discussions](https://github.com/control-theory/gonzo/discussions)

### 🤝 Community

Gonzo is an open-source project built by the community. We welcome contributions, feedback, and bug reports!

* Star the project on [GitHub](https://github.com/control-theory/gonzo) if you find it useful
* Join the conversation in [GitHub Discussions](https://github.com/control-theory/gonzo/discussions)
* Join our [Slack channel](https://join.slack.com/t/ctrltheorycommunity/shared_invite/zt-3dr6rke5w-GlcRaW2bvn4zcSaV8byZgA)
* Check out our [Contributing Guidelines](https://github.com/control-theory/gonzo/blob/main/CONTRIBUTING.md)

***

*Made with ❤️ by* [*ControlTheory*](https://www.controltheory.com/) *and the Gonzo community*


# Getting Started

Welcome to Gonzo! Get up and running with powerful log analysis in under 10 minutes. This section will take you from installation to analyzing your first logs with confidence.

### What is Gonzo?

Gonzo is an open source **Go-based TUI (Terminal User Interface) log analysis tool** that transforms how you understand and debug your applications. Inspired by [k9s](https://k9scli.io/), Gonzo provides:

* 🔍 **Real-time log analysis** with beautiful terminal charts
* 🤖 **AI-powered insights** to identify patterns and anomalies
* 📊 **Multiple data views** in an intuitive 2x2 grid layout
* 🚀 **Live streaming** from files, stdin, or OpenTelemetry
* 🎯 **Smart filtering** with regex support and severity tracking

{% hint style="success" %}
**Perfect for:** Application debugging, system monitoring, microservice analysis, and any scenario where you need to quickly understand what's happening in your logs.
{% endhint %}

### Your Journey to Log Analysis Mastery

This Getting Started section is designed as a **progressive learning path**. Each guide builds on the previous one:

```
Installation → Quick Start → Basic Usage → Ready for Advanced Features!
     ⏱️ 2-3 min     ⏱️ 10 min      ⏱️ 15 min         🚀 You're ready!
```

### Guide Overview

#### Installation

**Get Gonzo installed and ready to use**

Multiple installation methods to fit your environment:

* **Go install** (recommended for developers)
* **Homebrew** (easiest for macOS/Linux)
* **Binary downloads** (works everywhere)
* **Build from source** (for contributors and latest features)
* **Shell completion** setup for better CLI experience

**What you'll have:** A working `gonzo` command ready to analyze logs\
**Time required:** 2-5 minutes\
**Prerequisites:** None

***

#### Quick Start

**Your first log analysis in 5 minutes**

Hands-on tutorial that gets you analyzing logs immediately:

* Create sample log files to work with
* Launch Gonzo and understand the interface
* Learn essential navigation and shortcuts
* Try filtering and real-time log following
* See AI analysis in action

**What you'll have:** Practical experience with Gonzo's core features\
**Time required:** 10-15 minutes\
**Prerequisites:** Gonzo installation complete

***

#### Basic Usage

**Master the fundamental usage patterns**

Comprehensive coverage of daily Gonzo workflows:

* File analysis patterns (single, multiple, glob)
* Real-time log following with `--follow`
* Stdin processing and piping from other tools
* Working with different log formats (JSON, logfmt, plain text)
* Common command-line options and configurations

**What you'll have:** Solid foundation for using Gonzo in real scenarios\
**Time required:** 15-20 minutes\
**Prerequisites:** Quick Start completion

### Success Milestones

As you work through Getting Started, you'll achieve these key milestones:

{% tabs %}
{% tab title="After Installation" %}
✅ **You can run Gonzo**

```bash
gonzo --version
```

✅ **Shell completion works** (optional but recommended)

```bash
gonzo <tab><tab>  # Shows available commands
```

✅ **Ready for your first analysis**
{% endtab %}

{% tab title="After Quick Start" %}
✅ **You understand the 2x2+1 interface**

* Top words (top-left) top words appearing in logs
* Attributes (top-right) for structured data
* Log Patterns (middle-right) for common terms/phrases in the logs
* Log Counts (middle-right) for serverity over time and heatmap
* Log Viewer (bottom) for real-time logs

✅ **You can navigate effectively**

* Switch panels with `Tab`
* Pause/unpause with `Space`
* Filter logs with `/`

✅ **You've seen AI analysis in action** (if configured)
{% endtab %}

{% tab title="After Basic Usage" %}
✅ **You know all the input methods**

* File analysis: `gonzo -f app.log`
* Real-time following: `gonzo -f app.log --follow`
* Piping: `cat logs | gonzo`

✅ **You understand log format support**

* JSON logs with automatic field extraction
* Logfmt with key-value parsing
* Plain text with intelligent parsing

✅ **You can handle real scenarios**

* Multiple log files
* High-volume log streams
* Integration with existing tools
  {% endtab %}
  {% endtabs %}

### Choose Your Path

Different users have different needs. Pick the approach that matches your situation:

#### 🚀 **Fast Track** (15 minutes total)

*Just want to start analyzing logs quickly?*

1. Installation - Use Go install or Homebrew
2. Quick Start - Skip to "Your First Log Analysis"
3. Start analyzing your own logs immediately

**Best for:** Experienced developers who learn by doing

#### 📚 **Complete Path** (30-40 minutes total)

*Want to understand everything thoroughly?*

1. Installation - Try multiple methods, set up shell completion
2. Quick Start - Work through all examples and scenarios
3. Basic Usage - Read all sections, try different patterns

**Best for:** Users new to log analysis tools or those who prefer comprehensive understanding

#### 🔧 **Integration Focus** (20-30 minutes total)

*Need to integrate with existing systems?*

1. Installation - Focus on your deployment method
2. Basic Usage - Emphasize stdin processing and piping
3. Quick Start - Try integration examples
4. Jump to Integration Examples next

**Best for:** DevOps engineers and system administrators

### Essential Commands to Remember

By the end of Getting Started, you'll know these core patterns:

```bash
# Basic file analysis
gonzo -f application.log

# Real-time monitoring  
gonzo -f /var/log/app.log --follow

# Gonzo Native K8s Support (leverage your kubeconfig)
gonzo --k8s-enabled=true

# Analyzing multiple sources
gonzo -f api.log -f db.log -f cache.log

# Piping from other tools
kubectl logs -f deployment/my-app | gonzo
docker logs -f my-container | gonzo
tail -f /var/log/syslog | gonzo

# With AI analysis (when configured)
gonzo -f app.log --ai-model="gpt-4"
```

### Common First-Time Scenarios

Here are real-world scenarios you can tackle right after Getting Started:

{% tabs %}
{% tab title="Application Debugging" %}
**Scenario:** Your web application is throwing errors

```bash
# Monitor application logs in real-time
gonzo -f /var/log/myapp.log --follow

# Filter for errors only
# Press '/' then type: Error|error
```

**You'll quickly see:**

* Error frequency and patterns
* Most common error messages
* When errors are occurring (time patterns)
  {% endtab %}

{% tab title="System Monitoring" %}
**Scenario:** System performance seems slow

```bash
# Monitor system logs
sudo tail -f /var/log/syslog | gonzo

# Look for performance indicators
# Filter with: (slow|timeout|memory|cpu)
```

**You'll identify:**

* Resource usage warnings
* Service startup/shutdown patterns
* Hardware or driver issues
  {% endtab %}

{% tab title="Container Troubleshooting" %}
**Scenario:** Docker container keeps crashing

```bash
# Analyze container logs
docker logs my-container | gonzo

# For live monitoring
docker logs -f my-container 2>&1 | gonzo
```

**You'll discover:**

* Crash patterns and frequency
* Error messages before failures
* Resource exhaustion indicators
  {% endtab %}
  {% endtabs %}

### Troubleshooting Your First Experience

**Installation issues?**

* Check Installation troubleshooting
* Verify Go version (1.21+ required)
* Try alternative installation methods

**Gonzo not starting?**

* Test with simple input: `echo "test log" | gonzo`
* Check terminal compatibility (UTF-8 support required)
* Verify file permissions for log files

**Interface looks wrong?**

* Ensure terminal is large enough (minimum 80x24)
* Check for `NO_COLOR` environment variable
* Try resizing terminal window

**Not seeing logs?**

* Verify file paths are correct
* Check file permissions (`ls -la logfile.log`)
* Try with absolute paths instead of relative

### What Happens Next?

After completing Getting Started, you'll be ready to dive deeper:

#### **Immediate Next Steps**

* **User Guide** - Master the interface and advanced navigation
* **Configuration** - Customize Gonzo for your workflow
* **Integration Examples** - Real-world usage patterns

#### **Advanced Features**

* **AI Integration** - Set up intelligent log analysis
* **Log Analysis** - Advanced pattern detection and insights
* **OTLP Integration** - OpenTelemetry log collection

#### **Community & Support**

* **Contributing** - Help improve Gonzo
* [**GitHub Discussions**](https://github.com/control-theory/gonzo/discussions) - Ask questions and share tips
* [**GitHub Issues**](https://github.com/control-theory/gonzo/issues) - Report bugs or request features

### Success Tips

🎯 **Start small** - Begin with a single log file you're familiar with\
📚 **Follow the order** - Each guide builds on the previous one\
🔄 **Practice regularly** - Try Gonzo with different types of logs\
❓ **Ask questions** - Use GitHub Discussions if you get stuck\
🚀 **Share your experience** - Help others by sharing tips and patterns

***

**Ready to transform your log analysis workflow?** 🚀

Start with Installation and you'll be analyzing logs like a pro in no time!


# Installation

Get Gonzo installed and ready to analyze your logs. Choose the installation method that works best for your environment.

### Package Managers

#### Go Install (Recommended)

If you have Go installed, this is the fastest way to get the latest version:

```bash
go install github.com/control-theory/gonzo/cmd/gonzo@latest
```

#### Homebrew (macOS/Linux)

For macOS and Linux users with Homebrew:

```bash
# Install gonzo
brew install gonzo
```

### Binary Downloads

Download pre-built binaries for your platform from the [GitHub releases page](https://github.com/control-theory/gonzo/releases).

Available for:

* Linux (x86\_64, ARM64)
* macOS (Intel, Apple Silicon)
* Windows (x86\_64)

{% tabs %}
{% tab title="Linux" %}

```bash
# Download and install (replace with latest version)
wget https://github.com/control-theory/gonzo/releases/download/v1.0.0/gonzo-linux-amd64
chmod +x gonzo-linux-amd64
sudo mv gonzo-linux-amd64 /usr/local/bin/gonzo
```

{% endtab %}

{% tab title="macOS" %}

```bash
# Download and install (replace with latest version)
curl -L -o gonzo https://github.com/control-theory/gonzo/releases/download/v1.0.0/gonzo-darwin-amd64
chmod +x gonzo
sudo mv gonzo /usr/local/bin/gonzo
```

{% endtab %}

{% tab title="Windows" %}

1. Download `gonzo-windows-amd64.exe` from the releases page
2. Rename to `gonzo.exe`
3. Add to your PATH or place in a directory that's already in PATH
   {% endtab %}
   {% endtabs %}

### Build from Source

For development or to get the absolute latest features:

#### Prerequisites

* Go 1.21 or higher
* Make (optional, for convenience commands)

#### Build Steps

```bash
# Clone the repository
git clone https://github.com/control-theory/gonzo.git
cd gonzo

# Build using Make (recommended)
make build

# Or build directly with Go
go build -o gonzo cmd/gonzo/main.go

# Install to GOPATH/bin
go install ./cmd/gonzo
```

#### Development Build Options

```bash
# Quick build
make build

# Development mode (format, vet, test, build)
make dev

# Build for all platforms
make cross-build

# Run tests
make test
```

### Shell Completion

Enable shell autocompletion for a better CLI experience:

{% tabs %}
{% tab title="Bash" %}

```bash
# Add to ~/.bashrc
source <(gonzo completion bash)

# Or install permanently
gonzo completion bash > /usr/local/share/bash-completion/completions/gonzo
```

{% endtab %}

{% tab title="Zsh" %}

```bash
# Add to ~/.zshrc
source <(gonzo completion zsh)

# Or install permanently (for oh-my-zsh)
gonzo completion zsh > ~/.oh-my-zsh/completions/_gonzo
```

{% endtab %}

{% tab title="Fish" %}

```bash
gonzo completion fish | source

# Or install permanently
gonzo completion fish > ~/.config/fish/completions/gonzo.fish
```

{% endtab %}

{% tab title="PowerShell" %}

```powershell
# Add to your PowerShell profile
gonzo completion powershell | Out-String | Invoke-Expression
```

{% endtab %}
{% endtabs %}

### Verification

Verify your installation is working:

```bash
# Check version
gonzo version

# Test with sample logs
echo '{"level":"info","msg":"test log"}' | gonzo

# View help
gonzo --help
```

### What's Next?

* Quick Start Tutorial - Learn the basics with a hands-on example
* Basic Usage - Common usage patterns
* Interface Overview - Understanding the Gonzo dashboard

### Troubleshooting Installation

#### Common Issues

**Command not found after installation**

* Make sure `$GOPATH/bin` is in your PATH for Go installs
* For manual installations, verify the binary is in your PATH

**Permission denied errors**

* Use `sudo` when moving binaries to system directories
* Or install to user directories like `~/bin`

**Go version errors**

* Gonzo requires Go 1.21 or higher
* Update Go: <https://golang.org/dl/>

Need help? Check our Troubleshooting Guide or [open an issue](https://github.com/control-theory/gonzo/issues).


# Quick Start

Get up and running with Gonzo in under 5 minutes! This tutorial will walk you through your first log analysis session.

{% hint style="info" %}
**Prerequisites:** Make sure you have Gonzo installed. If not, check the Installation Guide first.
{% endhint %}

### Your First Log Analysis

Let's start with a simple example using sample log data.

#### Step 1: Create Sample Logs

First, let's create some sample log data to analyze:

{% tabs %}
{% tab title="JSON Logs" %}

```bash
# Create a sample JSON log file
cat > sample.log << EOF
{"timestamp":"2024-01-15T10:30:00Z","level":"info","service":"web-api","message":"User login successful","user_id":"12345"}
{"timestamp":"2024-01-15T10:30:05Z","level":"error","service":"web-api","message":"Database connection failed","error":"timeout after 30s"}
{"timestamp":"2024-01-15T10:30:10Z","level":"warn","service":"auth","message":"Rate limit exceeded","ip":"192.168.1.100"}
{"timestamp":"2024-01-15T10:30:15Z","level":"info","service":"web-api","message":"User logout","user_id":"12345"}
{"timestamp":"2024-01-15T10:30:20Z","level":"error","service":"database","message":"Query execution failed","query":"SELECT * FROM users","error":"connection refused"}
EOF
```

{% endtab %}

{% tab title="Plain Text Logs" %}

```bash
# Create a sample plain text log file
cat > sample.log << EOF
2024-01-15 10:30:00 [INFO] web-api: User login successful (user_id: 12345)
2024-01-15 10:30:05 [ERROR] web-api: Database connection failed - timeout after 30s
2024-01-15 10:30:10 [WARN] auth: Rate limit exceeded from 192.168.1.100
2024-01-15 10:30:15 [INFO] web-api: User logout (user_id: 12345)
2024-01-15 10:30:20 [ERROR] database: Query execution failed - connection refused
EOF
```

{% endtab %}

{% tab title="Logfmt Format" %}

```bash
# Create a sample logfmt log file
cat > sample.log << EOF
time=2024-01-15T10:30:00Z level=info service=web-api msg="User login successful" user_id=12345
time=2024-01-15T10:30:05Z level=error service=web-api msg="Database connection failed" error="timeout after 30s"
time=2024-01-15T10:30:10Z level=warn service=auth msg="Rate limit exceeded" ip=192.168.1.100
time=2024-01-15T10:30:15Z level=info service=web-api msg="User logout" user_id=12345
time=2024-01-15T10:30:20Z level=error service=database msg="Query execution failed" error="connection refused"
EOF
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}

#### Gonzo now supports native Kubernetes integration and can connect directly to your cluster using your kubeconfig using "gonzo --k8s-enabled=true". See [here ](/controltheory-documentation/gonzo-docs/integration-examples/container-environments/kubernetes)for more.

{% endhint %}

#### Step 2: Launch Gonzo

Now let's analyze these logs with Gonzo:

```bash
# Analyze the log file
gonzo -f sample.log
```

🎉 **Gonzo will launch with a beautiful terminal interface!**

### Understanding the Interface

When Gonzo opens, you'll see a 5-panel layout inspired by k9s:

#### Panel Overview

<figure><img src="/files/CXr7uk4yyMk8Y3vMfs98" alt=""><figcaption></figcaption></figure>

| Panel                                               | Description                               | What You'll See                                                                       |
| --------------------------------------------------- | ----------------------------------------- | ------------------------------------------------------------------------------------- |
| **Word Frequency** (top-left)                       | Most common words                         | Keywords ranked by frequency                                                          |
| **Top** **Attributes** (top-right)                  | Metadata auto-detected in structured logs | Attributes detected in log message, e.g. in OTel format, or JSON format detected logs |
| **Top Detected Patterns** (middle-left)             | Log patterns by frequency/volume          | Top patterns in log message/body (using Drain3 algorithm)                             |
| **Log Counts by Severity Over Time** (middle-right) | Logs counts over time                     | Severity distribution, patterns, time series                                          |
| **Log Viewer** (bottom)                             | Live feed of log entries                  | Colored by severity (red=error, yellow=warn, etc.)                                    |

### Basic Navigation

Let's explore the interface:

#### Essential Keyboard Shortcuts

| Key                     | Action                       | Try This                                       |
| ----------------------- | ---------------------------- | ---------------------------------------------- |
| **Tab** / **Shift+Tab** | Switch between panels        | Navigate around the 2x2 grid                   |
| **↑/↓** or **k/j**      | Move up/down in lists        | Navigate through log entries                   |
| **Enter**               | View details                 | Press on a log entry or the Counts panel       |
| **Space**               | Pause/unpause dashboard      | Freeze the display to examine data             |
| **/**                   | Enter filter mode            | Type regex patterns to filter logs             |
| s                       | Search/highlight             | Search and highlight text in logs              |
| f                       | Enter full screen log viewer | Fill your terminal with full screen log viewer |
| Escape                  | Close modal/exit filter mode | Close modal/exit filter mode                   |
| **q**                   | Quit Gonzo                   | Exit the application                           |
| ?/h                     | Show help                    | Show help                                      |

#### Try These Actions

1. **Navigate panels:** Press `Tab` to move between the five panels
2. **Examine logs:** Use arrow keys in the Log Viewer to browse entries
3. **View details:** Press `Enter` on a log entry to see full details
4. **Explore analytics:** Press `Enter` on the Counts panel for deep analysis

### Filtering Your Logs

One of Gonzo's most powerful features is real-time filtering (regex supported):

#### Basic Filtering

```bash
# Press '/' to enter filter mode, then type:
error           # Show only entries containing "error"
error|Error     # Show only entries containing "error" or "Error"
```

#### Severity Filtering

Gonzo automatically detects and color-codes log levels:

* 🔴 **ERROR** - Critical issues requiring attention
* 🟡 **WARN** - Warnings and potential problems
* 🔵 **INFO** - Informational messages
* ⚪ **DEBUG** - Detailed debugging information

### Real-Time Log Following

For live log analysis, use the `--follow` flag:

```bash
# Follow a log file as it grows (like tail -f)
gonzo -f /var/log/app.log --follow

# Follow multiple log files
gonzo -f "/var/log/*.log" --follow

# Pipe from other commands
kubectl logs -f deployment/my-app | gonzo
```

{% hint style="success" %}
**Pro Tip:** Use `Space` to pause the live feed when you need to examine something closely. The logs keep buffering in the background!
{% endhint %}

### Next Steps

Now that you've got the basics down, explore these features:

#### 🔍 **Advanced Analysis**

* Press `Enter` on the **Log** **Counts panel** to see:
  * Time-series heatmaps
  * Top services by severity
  * Service distribution charts
  * 60-minute rolling window analysis

#### 🤖 **AI-Powered Insights**

Set up [AI analysis](#ai-powered-insights) (hosted or local models supported) for intelligent log insights:

```bash
# Set up OpenAI (or your preferred AI provider)
export OPENAI_API_KEY="sk-your-key-here"

# Analyze logs with AI
gonzo -f sample.log --ai-model="gpt-4"

# Press 'i' in log detail view for AI analysis
```

#### 📊 **Multiple Data Sources**

Gonzo handles various input methods:

```bash
# Multiple files
gonzo -f app.log -f error.log -f debug.log

# Glob patterns  
gonzo -f "/var/log/app/*.log"

# OTLP receiver mode
gonzo --otlp-enabled

# Follow logs in real time (like tail -f)
gonzo -f local.log --follow | gonzo
```

### Common Use Cases

Here are some real-world scenarios to try:

{% tabs %}
{% tab title="Application Debugging" %}

```bash
# Monitor application logs with AI analysis
export OPENAI_API_KEY="your-key"
gonzo -f /var/log/myapp.log --follow --ai-model="gpt-4"

# Filter for errors and get AI insights
# Press '/' then type: error
# Press 'i' in detail view for AI analysis
```

{% endtab %}

{% tab title="Kubernetes Monitoring" %}

```bash
# Monitor pod logs
kubectl logs -f deployment/frontend | gonzo

# Multiple pods
kubectl logs -f -l app=backend | gonzo

# With stern (if installed)
stern backend | gonzo
```

{% endtab %}

{% tab title="System Administration" %}

```bash
# Monitor system logs
sudo tail -f /var/log/syslog | gonzo

# Multiple system log files
gonzo -f "/var/log/*.log" --follow

# Docker container logs
docker logs -f my-container 2>&1 | gonzo
```

{% endtab %}
{% endtabs %}

### Troubleshooting

**Gonzo not starting?**

* Check that your terminal supports UTF-8
* Verify log file permissions
* Try with a simple test: `echo "test" | gonzo`

**Colors not showing?**

* Ensure your terminal supports ANSI colors
* Check if `NO_COLOR` environment variable is set

**Performance issues?**

* Adjust buffer sizes: `gonzo -f large.log --log-buffer=5000`
* Use filtering to reduce data volume

### What's Next?

Ready to dive deeper? Check out these guides:

* **Interface Overview** - Detailed explanation of all panels and features
* **Log Input Methods** - Files, stdin, OTLP, and more
* **AI Integration** - Set up intelligent log analysis
* **Configuration** - Customize Gonzo for your workflow

### Need Help?

* ❓ Check [Troubleshooting](/controltheory-documentation/gonzo-docs/troubleshooting)
* 🐛 Report issues on [GitHub](https://github.com/control-theory/gonzo/issues)
* 💬 Join discussions on [GitHub Discussions](https://github.com/control-theory/gonzo/discussions)

### Learn More

Check out these practical guides:

* [A Tale of Two Log Types: Gonzo in Action](https://www.controltheory.com/blog/a-tale-of-two-log-types-gonzo-in-action/) - Understanding log formats
* [AI and a TUI: Practical Logging Tools for SREs](https://www.controltheory.com/blog/ai-and-a-tui-practical-logging-tools-for-sres/) - Real-world SRE workflows

***

**Congratulations!** 🎉 You've completed the Gonzo quick start. You now know how to analyze logs, navigate the interface, and use basic filtering. Time to explore your real log data!


# Basic Usage

Master the essential Gonzo usage patterns. This guide covers the most common ways to analyze logs and the fundamental workflows you'll use daily.

{% hint style="info" %}
**New to Gonzo?** Complete the Quick Start Tutorial first for a hands-on introduction to the interface.
{% endhint %}

### Core Usage Patterns

#### Reading from Files

The most common way to use Gonzo is analyzing log files directly:

```bash
# Analyze a single log file
gonzo -f application.log

# Analyze multiple specific files
gonzo -f application.log -f error.log -f debug.log

# Use glob patterns for multiple files
gonzo -f "/var/log/*.log"
gonzo -f "/var/log/app/*.log" -f "/var/log/nginx/*.log"
```

{% tabs %}
{% tab title="Single File" %}
Perfect for focused analysis of one application or service:

```bash
gonzo -f /var/log/myapp.log
```

**Best for:**

* Debugging specific applications
* Analyzing archived log files
* Initial investigation of issues
  {% endtab %}

{% tab title="Multiple Files" %}
Combine logs from related services for comprehensive analysis:

```bash
gonzo -f api.log -f database.log -f cache.log
```

**Best for:**

* Multi-service debugging
* Correlating events across systems
* Full-stack troubleshooting
  {% endtab %}

{% tab title="Glob Patterns" %}
Automatically include all matching files:

```bash
gonzo -f "/var/log/myapp-*.log"
gonzo -f "/logs/**/*.log"
```

**Best for:**

* Rotated log files (app.log, app.log.1, etc.)
* Directory-based log organization
* Dynamic file discovery
  {% endtab %}
  {% endtabs %}

#### Real-Time Log Following

Monitor logs as they grow, similar to `tail -f`:

```bash
# Follow a single file
gonzo -f /var/log/app.log --follow

# Follow multiple files
gonzo -f "/var/log/*.log" --follow

# Follow with glob patterns
gonzo -f "/var/log/app-*.log" --follow
```

{% hint style="success" %}
**Pro Tip:** Use `Space` to pause the live feed while keeping the data flowing in the background. Press `Space` again to resume auto-scrolling.
{% endhint %}

#### Stdin Processing (Piping)

Gonzo excels at processing log streams from other commands:

{% tabs %}
{% tab title="Basic Piping" %}

```bash
# Analyze existing logs
cat application.log | gonzo

# Process compressed logs
zcat app.log.gz | gonzo
gunzip -c logs.gz | gonzo
```

{% endtab %}

{% tab title="Live Streaming" %}

```bash
# Stream system logs
tail -f /var/log/syslog | gonzo

# Follow multiple files
tail -f /var/log/*.log | gonzo

# Use multitail for complex scenarios
multitail -f /var/log/app.log /var/log/error.log | gonzo
```

{% endtab %}

{% tab title="Container Logs" %}

```bash
# Docker container logs
docker logs -f my-container 2>&1 | gonzo

# Multiple containers
docker logs -f container1 container2 2>&1 | gonzo

# Docker Compose services
docker-compose logs -f | gonzo
```

{% endtab %}

{% tab title="Kubernetes Logs" %}

```bash
# Pod logs
kubectl logs -f deployment/my-app | gonzo

# Multiple pods
kubectl logs -f -l app=backend | gonzo

# With stern (if installed) - get logs from all pods, all namespaces
stern . --all-namespaces --output json | gonzo
```

{% endtab %}
{% endtabs %}

### Command-Line Options

#### Essential Flags

| Flag                    | Description                   | Example                               |
| ----------------------- | ----------------------------- | ------------------------------------- |
| `-h, --help`            | Gonzo help                    | `-h, --help`                          |
| `-f, --file`            | Specify log files or patterns | `gonzo -f app.log`                    |
| `--follow`              | Follow files like `tail -f`   | `gonzo -f app.log --follow`           |
| `-u, --update-interval` | Dashboard refresh rate        | `gonzo -f app.log -u 2s`              |
| `-b, --log-buffer`      | Maximum log entries to keep   | `gonzo -f app.log -b 5000`            |
| `--ai-model`            | AI model for analysis         | `gonzo -f app.log --ai-model="gpt-4"` |

#### Buffer and Performance Tuning

Optimize Gonzo for your log volume and system resources:

```bash
# Large log files - increase buffer
gonzo -f huge.log --log-buffer=10000

# High-frequency logs - slower updates
gonzo -f busy.log --update-interval=5s

# Memory-constrained systems
gonzo -f app.log --memory-size=5000 --log-buffer=1000

# Performance monitoring
gonzo -f app.log --update-interval=500ms --log-buffer=2000
```

### Working with Different Log Formats

Gonzo automatically detects and handles multiple log formats, including [Custom Formats](/controltheory-documentation/gonzo-docs/advanced-features/custom-formats). Use the [Quick Start section](/controltheory-documentation/gonzo-docs/getting-started/quick-start#step-1-create-sample-logs) to try out a few of the supported log formats.

#### JSON Logs

```json
{"timestamp":"2024-01-15T10:30:00Z","level":"error","service":"api","message":"Database timeout"}
```

**Features:**

* ✅ Automatic field extraction
* ✅ Structured attribute display
* ✅ Nested object support
* ✅ Array handling

#### Logfmt Format

```
time=2024-01-15T10:30:00Z level=error service=api msg="Database timeout" duration=30.5s
```

**Features:**

* ✅ Key-value pair extraction
* ✅ Quoted value support
* ✅ Numeric type detection
* ✅ Space and special character handling

#### Plain Text Logs

```
2024-01-15 10:30:00 [ERROR] api: Database timeout after 30.5 seconds
```

**Features:**

* ✅ Pattern-based level detection
* ✅ Timestamp recognition
* ✅ Service name extraction
* ✅ Word frequency analysis

{% hint style="info" %}
**Format Detection:** Gonzo automatically detects the format of each log entry. You can mix different formats in the same analysis session.
{% endhint %}

### Essential Workflows

#### Debugging Application Issues

```bash
# 1. Start with error-level filtering
gonzo -f app.log --follow
# Press '/' and type: error|Error

# 2. Examine patterns in Counts panel
# Press Enter on Counts panel for detailed analysis

# 3. Use AI for insights (if configured)
# Press 'i' in any log detail view
```

#### Performance Monitoring

```bash
# Monitor multiple services
gonzo -f "/var/log/app-*.log" --follow

# Focus on warnings and errors
# Use filtering press '/': warn|error

# Track response times and patterns
# Watch Word Frequency panel for performance keywords
```

#### System Health Monitoring

```bash
# Monitor system logs
sudo gonzo -f "/var/log/syslog" --follow

# Multi-service monitoring
gonzo -f "/var/log/*.log" --follow

# Filter for critical events
# Use regex in filter press '/': fail|error|critical|timeout
```

### Navigation Essentials

#### Panel Navigation

<figure><img src="/files/NMhjn7Sv7gwZQBRc4neX" alt=""><figcaption></figcaption></figure>

#### Key Shortcuts for Daily Use

| Key                     | Action                       | Try This                                       |
| ----------------------- | ---------------------------- | ---------------------------------------------- |
| **Tab** / **Shift+Tab** | Switch between panels        | Navigate around the 2x2 grid                   |
| **↑/↓** or **k/j**      | Move up/down in lists        | Navigate through log entries                   |
| **Enter**               | View details                 | Press on a log entry or the Counts panel       |
| **Space**               | Pause/unpause dashboard      | Freeze the display to examine data             |
| **/**                   | Enter filter mode            | Type regex patterns to filter logs             |
| s                       | Search/highlight             | Search and highlight text in logs              |
| f                       | Enter full screen log viewer | Fill your terminal with full screen log viewer |
| Escape                  | Close modal/exit filter mode | Close modal/exit filter mode                   |
| **q**                   | Quit Gonzo                   | Exit the application                           |
| ?/h                     | Show help                    | Show help                                      |

### Configuration for Daily Use

#### Environment Variables

Set these for consistent behavior:

```bash
# Add to your ~/.bashrc or ~/.zshrc
export GONZO_UPDATE_INTERVAL="2s"
export GONZO_LOG_BUFFER="2000"
export GONZO_MEMORY_SIZE="15000"

# AI configuration
export OPENAI_API_KEY="your-key-here"
```

#### Config File Setup

Create `~/.config/gonzo/config.yml` for persistent settings:

```yaml
# Default file patterns
files:
  - "/var/log/app.log"
  - "/var/log/error.log"

# Enable real-time following
follow: true

# Performance settings
update-interval: 2s
log-buffer: 2000
memory-size: 15000

# AI model preference
ai-model: "gpt-4"
```

### Common Patterns by Use Case

#### Web Application Monitoring

```bash
# Monitor web server and application logs
gonzo -f /var/log/nginx/access.log -f /var/log/app/error.log --follow

# Filter for HTTP errors
# Regex: (4[0-9]{2}|5[0-9]{2}|error)
```

#### Microservices Debugging

```bash
# Monitor all service logs
gonzo -f "/var/log/service-*.log" --follow

# Focus on service communication
# Filter: (http|api|request|response)
```

#### Database Troubleshooting

```bash
# Monitor database logs
gonzo -f /var/log/postgresql/postgresql.log --follow

# Look for performance issues  
# Filter: (slow|timeout|deadlock|error)
```

#### CI/CD Pipeline Analysis

```bash
# Analyze build logs
gonzo -f build.log

# Monitor deployment logs
kubectl logs -f deployment/app | gonzo

# Filter for failures
# Regex: (fail|error|exit)
```

### Best Practices

#### 🎯 **Efficient Filtering**

* Start broad, then narrow down with specific filters
* Use regex for pattern matching: `*(api|web)`
* Combine severity with keywords: `*error.*database`

#### ⚡ **Performance Optimization**

* Use `--follow` only when needed for real-time analysis
* Adjust buffer sizes based on log volume
* Filter early to reduce processing overhead

#### 🔍 **Effective Analysis**

* Use the Counts panel for pattern recognition
* Leverage AI analysis for complex issues
* Pause the feed when examining specific entries

#### 🛠️ **Workflow Integration**

* Create shell aliases for common commands
* Use config files for consistent settings
* Combine with other tools (`stern`, `kubectl`, `docker`)

### Troubleshooting Common Issues

#### File Access Problems

```bash
# Permission denied
sudo gonzo -f /var/log/secure.log

# File not found
gonzo -f "/var/log/app*.log"  # Use quotes with wildcards
```

#### Performance Issues

```bash
# Large files - increase buffer and slow updates
gonzo -f huge.log --log-buffer=10000 --update-interval=5s

# High-frequency logs - reduce memory usage
gonzo -f busy.log --memory-size=5000
```

#### Display Issues

```bash
# Terminal too small
# Resize terminal or use minimal view

# Colors not showing
unset NO_COLOR
export TERM=xterm-256color
```

### What's Next?

Now that you've mastered basic usage, explore these advanced features:

* **Interface Overview** - Deep dive into each panel
* **Log Input Methods** - OTLP, streaming, and advanced sources
* **Filtering & Search** - Advanced filtering techniques
* **Configuration** - Customize for your workflow

***

**You're now ready to use Gonzo effectively for daily log analysis!** 🚀 These patterns will handle 90% of your log analysis needs.


# Log Analysis

### Detailed Analysis Modal

Press `Enter` on the Log Counts panel in the main view to access the comprehensive analysis modal. The modal uses the same receive time architecture as the main dashboard, ensuring consistent and reliable visualization regardless of log timestamp accuracy or clock skew issues.

<figure><img src="/files/0bhLogCgqO14aCw3Yisi" alt=""><figcaption></figcaption></figure>

### Time-Series Heatmap Analysis

#### Understanding the Heatmap

The time-series heatmap is one of Gonzo's most powerful visual analysis tools:

**Time Axis (Horizontal):**

* Shows last 60 minutes in 1-minute buckets
* Reading: `60` = 60 minutes ago, `0` = current minute
* Updates in real-time as new logs arrive

**Severity Axis (Vertical):**

* Each row represents a different log severity level
* Separate tracking for ERROR, WARN, INFO, DEBUG, etc.
* Independent scaling per severity level

**Intensity Indicators:**

```
░ = Low activity (1-25% of max for this severity)
▒ = Medium activity (25-50% of max)
▓ = High activity (50-75% of max)  
█ = Very high activity (75-100% of max)
```

#### Reading Heatmap Patterns

{% tabs %}
{% tab title="Incident Detection" %}
**Identifying When Problems Started:**

```
Time: 60  50  40  30  20  10  0
ERROR ░░░░░░░░████████████░░░░░░
WARN  ░░░░░░████████████████░░░░
```

**Analysis:**

* Problem started around 40 minutes ago
* Peak error activity 30-20 minutes ago
* Warnings preceded errors (early warning signs)
* System appears to be recovering now

**Use Case:** Incident timeline reconstruction
{% endtab %}

{% tab title="Performance Patterns" %}
**Daily Performance Cycles:**

```
Time: 60  50  40  30  20  10  0
ERROR ░░░░░░░░░░░░░░░░░░░░░░░░░░
WARN  ░░░░████░░░░████░░░░████░░
INFO  ████░░░░████░░░░████░░░░░░
```

**Analysis:**

* Regular 20-minute cycles in warnings
* High info activity alternating with warnings
* Suggests scheduled job or batch processing
* No critical errors, normal operational pattern

**Use Case:** Capacity planning and optimization
{% endtab %}

{% tab title="Cascade Failures" %}
**System Failure Propagation:**

```
Time: 60  50  40  30  20  10  0
ERROR ░░░░░░░░░░█░░██████████████
WARN  ░░░░░░░░█████████████████░
INFO  ░░░░░░████████████░░░░░░░░
```

**Analysis:**

* Single error triggered cascade
* Warnings spread quickly after initial error
* Info logs dropped off (services became unresponsive)
* Classic cascade failure pattern

**Use Case:** System resilience analysis
{% endtab %}
{% endtabs %}

#### Heatmap Best Practices

**🔍 Investigation Techniques:**

1. **Start wide, zoom in** - Look for obvious patterns first
2. **Compare severity levels** - How do different levels correlate?
3. **Identify inflection points** - When did patterns change?
4. **Look for cycles** - Are there recurring patterns?

**⚡ Quick Analysis:**

```bash
# Quick heatmap analysis workflow:
1. Press Enter on Counts panel
2. Scan heatmap for obvious spikes or patterns
3. Note correlation between severity levels
4. Identify time ranges for deeper investigation
5. Use time information to filter main log view
```

### Log Statistics Window

Select `i` from the main window to access the **Log Statistics** view. This window provides a general overview of all your logs including top services, severity distribution, most common patterns, and top attributes.

<figure><img src="/files/ppAraeWokoZZsRty4775" alt=""><figcaption></figcaption></figure>

### Log Detail View

Selecting `ENTER` on the Log Viewer in the main Gonzo TUI will drill down into the **Log Detail View**. From this modal you can look at attribute details, time and severity information, and select `i` to get further AI analysis from whatever AI model you've configured. On the right panel you can chat directly with your selected AI model in context to the selected log you are viewing. Nothing is shared with AI unless you explicitly connect to a model of your choice.

<figure><img src="/files/3OR9xaxqraiOxtyiXIyI" alt=""><figcaption></figcaption></figure>


# Dstl8.Lite GUI

Press d in Gonzo to launch a local browser dashboard with workspaces, search, and severity heatmaps.

Press `d` from any Gonzo view to launch Dstl8.Lite, a local browser-based dashboard powered by Gonzo. Same logs, richer UI: workspaces, pattern detection, severity heatmaps, and live log search. Runs entirely on your machine.

{% hint style="info" %}
Dstl8.Lite is bundled with Gonzo and runs locally. No account, no cloud, no extra install. If you want the full version with persistent workspaces, RBAC, and the Möbius AI agent, see [Dstl8](https://controltheory.com/).
{% endhint %}

<figure><img src="/files/6eg9S5bzGyDxceoACRCM" alt=""><figcaption></figcaption></figure>

#### Launch it

While Gonzo is running, hit `d` from any view. Your default browser opens to the Dstl8.Lite dashboard, streaming the same logs Gonzo is analyzing.

```bash
# Start Gonzo however you normally would
gonzo -f /var/log/app.log --follow

# Then press `d` once the TUI is up
```

#### What you get

**Log viewer with severity filtering and live search**

Search across the live stream and filter by severity level. Useful when you want to scan a wider range of logs than the TUI buffer shows.

<figure><img src="/files/jFSVKuyIk0kscItvjY9g" alt=""><figcaption></figcaption></figure>

**Severity heatmap across pods**

Visualize severity distribution over time, broken down by pod (or service, host, etc. depending on your input source). Spot which workloads are noisy and when.

<figure><img src="/files/hWzvThXdvmPl739Yehxc" alt=""><figcaption></figcaption></figure>

**Workspaces**

Group your logs into named workspaces so you can switch context without losing state. Each workspace keeps its own filters and views.

<figure><img src="/files/iBZOHSmhXN0JIfe8G3Tv" alt=""><figcaption></figcaption></figure>

**Pattern detection**

Recurring log patterns are extracted and surfaced automatically, the same pattern detection Gonzo uses in the Counts modal, but with more room to browse.

<figure><img src="/files/waQVRWmAXir1kXGIVmg3" alt=""><figcaption></figcaption></figure>

#### When to use Dstl8.Lite vs the TUI

| Use the TUI when...                           | Use Dstl8.Lite when...                               |
| --------------------------------------------- | ---------------------------------------------------- |
| You're SSH'd into a server                    | You're on your local machine with a browser handy    |
| You want fast keyboard-driven triage          | You want to search and filter across more log volume |
| You're piping logs through a quick `\| gonzo` | You're running a longer debugging session            |
| You want minimal resource overhead            | You want richer visualizations and multi-pane views  |

Both share the same underlying log stream, so you can have them open side-by-side and switch as needed.

#### Troubleshooting

**Browser doesn't open when I press `d`** Dstl8.Lite tries to open your default browser. If that fails, check the Gonzo footer for the local URL (typically `http://localhost:<port>`) and open it manually.

**Port already in use** The local server picks an open port automatically. If you're seeing conflicts, check what's bound on common ports (8080, 3000, etc.) or restart Gonzo.

**Logs not appearing in Dstl8.Lite** Dstl8.Lite streams whatever Gonzo is currently processing. If the TUI isn't showing logs either, check your input source (file path, stdin, OTLP receiver, k8s connection).


# Advanced Features

Unlock Gonzo's most powerful capabilities with AI-driven analysis, sophisticated pattern detection, and intelligent format processing. These features transform Gonzo from a log viewer into an intelligent analysis platform.

### What Makes Gonzo Advanced?

Gonzo goes beyond traditional log analysis tools by incorporating cutting-edge technologies:

#### 🤖 **AI-Powered Intelligence**

Leverage machine learning models to automatically identify patterns, anomalies, and root causes in your logs without manual analysis.

#### 📊 **Advanced Pattern Detection**

Built-in algorithms automatically discover recurring patterns, cluster similar events, and identify unusual behavior in your log streams.

#### 🔍 **Intelligent Format Processing**

Automatic detection and parsing of complex log formats with smart field extraction and type inference.

#### 📈 **Deep Analytics**

Time-series analysis, heatmap visualizations, and statistical insights that reveal trends invisible to traditional log analysis.

{% hint style="info" %}
**Prerequisites:** Complete the User Guide section first. Advanced features build on fundamental Gonzo knowledge and assume familiarity with the interface and basic operations.
{% endhint %}

### Feature Overview

#### AI Integration

**Transform log analysis with artificial intelligence**

Gonzo integrates with multiple AI providers to bring intelligent analysis to your logs:

* **Pattern Recognition** - AI identifies recurring issues and anomalies automatically
* **Root Cause Analysis** - Get intelligent suggestions about what caused problems
* **Natural Language Queries** - Ask questions about your logs in plain English
* **Predictive Insights** - Understand trends and potential future issues
* **Multi-Provider Support** - Works with OpenAI, local models (Ollama, LM Studio), and custom APIs

**Key Capabilities:**

* Automatic anomaly detection in log patterns
* Intelligent correlation across multiple log sources
* Natural language explanations of complex technical issues
* Proactive identification of potential problems
* Context-aware analysis based on your specific application domain

**Time to master:** 45-60 minutes\
**Prerequisites:** Basic Gonzo proficiency, API key for AI service

***

#### Log Analysis

**Deep analytical insights with advanced algorithms**

Sophisticated analysis capabilities that reveal hidden patterns and trends:

* **Drain3 Pattern Detection** - Automatically cluster similar log entries
* **Time-Series Analysis** - 60-minute rolling window with severity tracking
* **Heatmap Visualization** - ASCII-based intensity mapping over time
* **Service Distribution** - Understand which services generate what log types
* **Anomaly Detection** - Statistical analysis to identify unusual patterns

**Advanced Analytics:**

* Pattern extraction using state-of-the-art clustering algorithms
* Real-time trend analysis with configurable time windows
* Statistical outlier detection for identifying anomalies
* Cross-correlation analysis between different log sources
* Performance trend identification and prediction

**Time to master:** 30-45 minutes\
**Prerequisites:** Understanding of log patterns, basic statistics helpful

***

#### Format Detection

**Intelligent parsing of complex log formats**

Advanced format processing that goes beyond simple pattern matching:

* **Multi-Format Support** - JSON, logfmt, plain text, and custom formats
* **Intelligent Type Inference** - Automatic detection of data types and structures
* **Nested Object Handling** - Deep parsing of complex JSON structures
* **Custom Format Adaptation** - Learn and adapt to your specific log formats
* **Real-Time Processing** - Format detection that works with streaming data

**Smart Processing:**

* Automatic field extraction with semantic understanding
* Dynamic schema inference for evolving log formats
* Error-tolerant parsing that handles malformed entries
* Performance-optimized processing for high-volume streams
* Custom transformation rules for legacy formats

**Time to master:** 20-30 minutes\
**Prerequisites:** Basic understanding of log formats

### Learning Paths

Choose your path based on your goals and current expertise:

{% tabs %}
{% tab title="AI-First Path" %}
**Focus on intelligent analysis and automation**

Perfect for users who want to leverage AI for log analysis:

1. **AI Integration Setup** - Configure your AI provider
2. **AI Providers Guide** - Choose the right AI service
3. **Using AI Features** - Master AI-powered analysis
4. **Log Analysis** - Combine AI with algorithmic analysis
5. **Format Detection** - Optimize data input for AI

**Benefits:**

* Fastest path to intelligent insights
* Automated problem detection
* Natural language interaction with logs
* Reduced time to resolution for issues

**Estimated time:** 2-3 hours total
{% endtab %}

{% tab title="Analytics-First Path" %}
**Focus on algorithmic analysis and pattern detection**

Ideal for users who want deep analytical capabilities:

1. **Log Analysis** - Master pattern detection and analytics
2. **Format Detection** - Optimize data parsing
3. **AI Integration** - Add AI insights to analytical workflows
4. Practice with complex multi-source scenarios

**Benefits:**

* Deep understanding of log patterns
* Statistical approach to problem identification
* Works without external AI dependencies
* Excellent foundation for AI enhancement

**Estimated time:** 2-2.5 hours total
{% endtab %}

{% tab title="Format-First Path" %}
**Focus on data processing and format optimization**

Best for users with complex or custom log formats:

1. **Format Detection** - Master format processing
2. **Log Analysis** - Apply analytics to well-parsed data
3. **AI Integration** - Add AI to properly structured data
4. Advanced integration with custom formats

**Benefits:**

* Optimal data extraction from complex logs
* Foundation for all other advanced features
* Better performance with properly parsed data
* Custom format handling capabilities

**Estimated time:** 1.5-2 hours total
{% endtab %}
{% endtabs %}

### Advanced Feature Combinations

The real power of Gonzo comes from combining these advanced features:

#### AI-Enhanced Pattern Detection

```bash
# 1. Start with automatic pattern detection
gonzo -f complex-app.log --follow

# 2. Enable AI analysis
export OPENAI_API_KEY="your-key"
gonzo -f complex-app.log --follow --ai-model="gpt-4"

# 3. Use Counts panel for pattern analysis
# Press Enter on Counts panel → Review drain3 patterns
# Press 'i' on interesting patterns for AI explanation

# 4. Combine insights
# Algorithmic patterns + AI interpretation = Powerful insights
```

#### Multi-Format Intelligent Analysis

```bash
# Analyze mixed-format logs with AI
gonzo -f json-logs.log -f plain-text.log -f logfmt.log \
      --follow --ai-model="gpt-4"

# Benefits:
# - Automatic format detection for each log type
# - Unified analysis across different formats  
# - AI correlation of events across formats
# - Pattern detection that spans format boundaries
```

#### Real-Time Anomaly Detection

```bash
# Advanced real-time monitoring
gonzo -f production.log --follow --ai-model="gpt-4" \
      --update-interval=30s --log-buffer=5000

# Workflow:
# 1. Gonzo detects patterns automatically (drain3)
# 2. Tracks statistical baselines over time  
# 3. AI analyzes deviations from normal patterns
# 4. Alerts you to anomalies worth investigating
```

### Use Case Scenarios

#### Production Monitoring with AI

**Scenario:** 24/7 production monitoring with intelligent alerting

```bash
# Setup intelligent monitoring
export OPENAI_API_KEY="your-production-key"
gonzo -f /var/log/app/*.log --follow \
      --ai-model="gpt-4" \
      --log-buffer=10000 \
      --update-interval=60s

# AI continuously analyzes:
# - Error rate changes vs historical baselines
# - New error patterns not seen before
# - Performance degradation indicators
# - Security anomaly detection
```

#### Development Debugging Enhancement

**Scenario:** AI-assisted debugging during development

```bash
# Enhanced debugging session
gonzo -f logs/debug.log --follow --ai-model="gpt-3.5-turbo"

# Workflow:
# 1. Reproduce issue while Gonzo monitors
# 2. AI identifies unusual patterns during reproduction
# 3. Press 'i' on error logs for AI explanation
# 4. AI suggests debugging steps and root causes
# 5. Faster resolution with intelligent insights
```

#### Complex System Analysis

**Scenario:** Multi-service architecture investigation

```bash
# Comprehensive system analysis
gonzo -f api-gateway.log -f user-service.log -f db.log \
      --follow --ai-model="gpt-4"

# Advanced capabilities:
# - Cross-service correlation with AI insights
# - Pattern detection across service boundaries
# - Intelligent trace following through system
# - Root cause analysis spanning multiple services
```

### Performance Considerations

#### AI Feature Optimization

**Managing AI API Costs:**

```bash
# Use faster models for development
export GONZO_AI_MODEL="gpt-3.5-turbo"

# Use premium models for production issues
export GONZO_AI_MODEL="gpt-4"

# Local AI for cost-free analysis
export OPENAI_API_BASE="http://localhost:11434"  # Ollama
export GONZO_AI_MODEL="llama3"
```

**Balancing Features with Performance:**

```bash
# High-volume logs - optimize for speed
gonzo -f busy.log --follow \
      --update-interval=10s \
      --log-buffer=20000 \
      --memory-size=50000

# AI analysis - balance frequency vs cost
# Run AI analysis on filtered subsets rather than all logs
gonzo -f app.log --follow | grep ERROR | gonzo --ai-model="gpt-4"
```

#### Advanced Analytics Tuning

**Pattern Detection Optimization:**

```bash
# Tune drain3 sensitivity (via configuration)
# More sensitive = more patterns detected
# Less sensitive = broader pattern grouping

# Balance pattern granularity with usefulness
# Too many patterns = noise
# Too few patterns = missed insights
```

### Integration with Existing Workflows

#### CI/CD Integration

```bash
# AI-enhanced CI/CD analysis
build-command 2>&1 | gonzo --ai-model="gpt-3.5-turbo" &
GONZO_PID=$!

# After build completion
if [ $BUILD_FAILED ]; then
    echo "Build failed - check Gonzo AI analysis"
    # AI has been analyzing build logs in real-time
    # Press 'i' on error logs for failure analysis
fi
```

#### Monitoring Integration

```bash
# Enhanced alerting with AI context
if grep -q "ERROR" /var/log/app.log; then
    # Launch Gonzo with AI for context
    tail -100 /var/log/app.log | gonzo --ai-model="gpt-4" &
    
    # AI provides context for alerts
    echo "Error detected - Gonzo AI analysis running"
fi
```

### Getting Started with Advanced Features

#### Quick Start Checklist

**For AI Integration:**

* [ ] Choose AI provider (OpenAI, Ollama, LM Studio)
* [ ] Configure API keys and endpoints
* [ ] Test with simple log analysis
* [ ] Explore AI chat and analysis features

**For Log Analysis:**

* [ ] Understand the Counts panel and modal
* [ ] Practice with pattern detection
* [ ] Learn time-series analysis interpretation
* [ ] Experiment with different log types

**For Format Detection:**

* [ ] Test with JSON, logfmt, and plain text logs
* [ ] Observe automatic field extraction
* [ ] Understanding nested object handling
* [ ] Practice with mixed-format scenarios

#### First Advanced Session

```bash
# Complete advanced features test drive
# 1. Set up AI (if available)
export OPENAI_API_KEY="your-key"

# 2. Analyze logs with all features
gonzo -f mixed-format.log --ai-model="gpt-4"

# 3. Explore each advanced feature:
# - Press Enter on Counts panel (advanced analytics)
# - Press 'i' on log entries (AI analysis)  
# - Observe format detection in Attributes panel
# - Try AI chat with 'c' in log details

# 4. Combine features for comprehensive analysis
```

### What's Next?

After mastering Advanced Features, you'll be ready for:

* **Configuration** - Optimize settings for advanced workflows
* **Integration Examples** - Apply advanced features to real scenarios
* **API & Architecture** - Understand how advanced features work
* **Contributing** - Help improve advanced features

### Getting Help with Advanced Features

**Community Resources:**

* 📖 Advanced feature documentation and examples
* 💬 [GitHub Discussions](https://github.com/control-theory/gonzo/discussions) for complex use cases
* 🔧 [GitHub Issues](https://github.com/control-theory/gonzo/issues) for advanced feature bugs
* 🤝 Community examples and patterns

**Best Practices:**

* Start with one advanced feature at a time
* Practice with sample data before production use
* Understand cost implications of AI features
* Document successful patterns for team sharing

***

**Ready to unlock Gonzo's full potential?** 🚀 Advanced features transform log analysis from manual investigation to intelligent, automated insights. Start with AI Integration to experience the future of log analysis!


# Working with OTel

Gonzo can act as an OpenTelemetry Protocol (OTLP) log receiver, accepting logs directly from OpenTelemetry-instrumented applications.

### Basic OTLP Setup

```bash
# Start Gonzo as OTLP receiver
gonzo --otlp-enabled

# Custom ports
gonzo --otlp-enabled --otlp-grpc-port=5317 --otlp-http-port=5318

# OTLP with file backup
gonzo --otlp-enabled -f backup.log --follow
```

**Default Endpoints:**

* **gRPC:** `localhost:4317`
* **HTTP:** `http://localhost:4318/v1/logs`

### OpenTelemetry Collector Configuration

{% tabs %}
{% tab title="gRPC Configuration" %}
**OpenTelemetry Collector (otelcol) config:**

```yaml
# otel-collector-config.yaml
exporters:
  otlp/gonzo_grpc:
    endpoint: localhost:4317
    tls:
      insecure: true

service:
  pipelines:
    logs:
      receivers: [filelog, otlp]
      processors: [batch]
      exporters: [otlp/gonzo_grpc]
```

**Start collector:**

```bash
otelcol --config=otel-collector-config.yaml
```

{% endtab %}

{% tab title="HTTP Configuration" %}
**OpenTelemetry Collector (otelcol) config:**

```yaml
# otel-collector-config.yaml
exporters:
  otlphttp/gonzo_http:
    endpoint: http://localhost:4318/v1/logs

service:
  pipelines:
    logs:
      receivers: [filelog, otlp]
      processors: [batch]
      exporters: [otlphttp/gonzo_http]
```

**Benefits of HTTP:**

* Easier debugging with standard HTTP tools
* Better firewall compatibility
* Works with HTTP proxies
  {% endtab %}
  {% endtabs %}

### Application Integration

**Python Application:**

```python
from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporter
from opentelemetry.sdk._logs import LoggerProvider
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor

# Configure OTLP exporter
otlp_exporter = OTLPLogExporter(
    endpoint="localhost:4317",
    insecure=True
)

# Set up logging pipeline
logger_provider = LoggerProvider()
logger_provider.add_log_record_processor(
    BatchLogRecordProcessor(otlp_exporter)
)

# Your application logs now flow to Gonzo
import logging
logging.info("This log will appear in Gonzo!")
```

**Node.js Application:**

```javascript
const { NodeSDK } = require('@opentelemetry/sdk-node');
const { OTLPLogExporter } = require('@opentelemetry/exporter-logs-otlp-grpc');

const sdk = new NodeSDK({
  logRecordProcessor: new BatchLogRecordProcessor(
    new OTLPLogExporter({
      url: 'http://localhost:4317',
    })
  ),
});

sdk.start();
```

### OTLP Advantages

**Why Use OTLP with Gonzo:**

✅ **Native integration** - Structured log data preserves all attributes\
✅ **Real-time streaming** - Logs appear immediately as they're generated\
✅ **Metadata preservation** - Service names, trace IDs, and custom attributes\
✅ **Standardized format** - Works with any OpenTelemetry-compatible application\
✅ **Scalable architecture** - Handle logs from multiple services simultaneously

**Use Cases:**

* **Microservice architectures** - Centralized log collection from all services
* **Cloud-native applications** - Integration with OpenTelemetry ecosystems
* **Real-time monitoring** - Immediate visibility into application behavior
* **Distributed tracing correlation** - Logs automatically linked to traces

### OTLP Issues

```bash
# Connection refused
# Check if Gonzo is listening:
netstat -ln | grep 4317

# No logs appearing
# Verify OTLP configuration:
curl -X POST http://localhost:4318/v1/logs -d '{}'

# Port conflicts
# Use custom ports:
gonzo --otlp-enabled --otlp-grpc-port=5317
```

### What's Next?

Now that you understand all input methods, explore these advanced topics:

* **Filtering & Search** - Find exactly what you need in your logs
* **Configuration** - Set up persistent input configurations
* **Integration Examples** - Real-world input scenarios
* **AI Integration** - Add intelligence to your log analysis

***

**You now have complete mastery over getting data into Gonzo!** 🚀 Whether you're analyzing static files, monitoring real-time streams, or integrating with OpenTelemetry, you know the optimal approach for every scenario.


# AI Setup & Integration

Transform your log analysis with artificial intelligence. Gonzo's AI integration brings natural language understanding, pattern recognition, and intelligent insights to log analysis, making complex debugging faster and more intuitive.

{% hint style="success" %}
**Quick Start:** Set up your AI provider, then press `i` on any log entry to get instant AI analysis, or use `m` to switch between AI models on the fly.
{% endhint %}

### AI Integration Overview

Gonzo supports multiple AI providers and models, giving you flexibility in cost, performance, and privacy:

| Provider                | Cost     |
| ----------------------- | -------- |
| **OpenAI**              | Paid API |
| **Local Ollama**        | Free     |
| **Local** **LM Studio** | Free     |
| **Custom APIs**         | Varies   |

### Core AI Features

#### Intelligent Log Analysis

**Press `i` on any log entry for instant analysis:**

```
Original Log:
{"timestamp":"2024-01-15T10:30:05Z","level":"error","service":"api-gateway","message":"Database connection timeout after 30s","user_id":"12345","endpoint":"/api/users","duration":30542}

AI Analysis:
"This error indicates a database connectivity issue affecting user 12345's request to the /api/users endpoint. The 30-second timeout suggests either:

1. Database server overload or unresponsiveness
2. Network connectivity issues between API gateway and database
3. Potential deadlock or long-running query

Recommended investigation steps:
- Check database server health and active connections
- Review recent database queries for performance issues
- Verify network connectivity between services
- Look for similar timeouts in the same timeframe to identify scope"
```

#### AI-Powered Chat

**Press `c` in log details for interactive analysis:**

```
You: Why are we seeing so many authentication failures?

AI: Based on the logs, I see 156 authentication failures in the last hour. The pattern suggests:

1. Geographic clustering - 80% from IP ranges in Eastern Europe
2. Timing pattern - Bursts every 2-3 minutes, suggesting automation
3. Username patterns - Targeting common usernames (admin, root, user)

This appears to be a coordinated brute force attack. I recommend:
- Implementing rate limiting on authentication endpoints
- Geographic IP blocking for suspicious regions
- Enhanced monitoring for automated attack patterns

Would you like me to help identify the specific IP ranges involved?

You: Yes, show me the top attacking IPs
```

#### Contextual Understanding

AI analyzes logs within context:

* **Service relationships** - Understands how microservices interact
* **Timing correlation** - Connects events across time
* **Pattern significance** - Explains why patterns matter
* **Business impact** - Relates technical issues to user experience

### Getting Started with AI

#### Quick Setup Path

```bash
# 1. Choose your AI provider (OpenAI is easiest to start)
export OPENAI_API_KEY="sk-your-key-here"

# 2. Start Gonzo with AI enabled
gonzo -f your-logs.log --ai-model="gpt-4"

# 3. Try AI features immediately:
# - Press 'i' on any log entry
# - Press 'c' for interactive chat
# - Press 'm' to switch models
```

### OpenAI Setup

#### Step 1: Get Your API Key

1. **Visit** [**OpenAI API Platform**](https://platform.openai.com/)
2. **Create account or sign in**
3. **Navigate to API Keys** (<https://platform.openai.com/api-keys>)
4. **Create new secret key**
5. **Copy the key** (starts with `sk-`)

{% hint style="warning" %}
**Important:** Save your API key securely. OpenAI only shows it once, and you'll need it for Gonzo configuration.
{% endhint %}

#### Step 2: Configure Environment

**Method 1: Environment Variable (Recommended)**

```bash
# Add to your ~/.bashrc, ~/.zshrc, or ~/.profile
export OPENAI_API_KEY="sk-your-actual-api-key-here"

# Reload your shell configuration
source ~/.bashrc  # or ~/.zshrc
```

**Method 2: Session Variable**

```bash
# Set for current session only
export OPENAI_API_KEY="sk-your-actual-api-key-here"

# Verify it's set
echo $OPENAI_API_KEY
```

**Method 3: Configuration File**

```bash
# Create Gonzo config file
mkdir -p ~/.config/gonzo
cat > ~/.config/gonzo/config.yml << EOF
# AI Configuration
ai-model: "gpt-4"

# Environment variables can also be set in config
# But API keys are more secure as environment variables
EOF
```

#### Step 3: Test Your Setup

```bash
# Test with automatic model selection
gonzo -f your-logs.log

# Test with specific model
gonzo -f your-logs.log --ai-model="gpt-4"

# Test with cheaper model for development
gonzo -f your-logs.log --ai-model="gpt-3.5-turbo"
```

#### Step 4: Verify AI Features Work

```bash
# 1. Start Gonzo with your logs
gonzo -f application.log --ai-model="gpt-4"

# 2. Navigate to a log entry and press 'i'
# You should see AI analysis of the log entry

# 3. Try the model switcher with 'm'
# You should see available OpenAI models

# 4. Test AI chat with 'c' in log details
# You should be able to have a conversation about the logs
```

### Local AI Setup (Ollama)

#### Step 1: Install Ollama

{% tabs %}
{% tab title="Linux" %}

```bash
# Install Ollama
curl -fsSL https://ollama.ai/install.sh | sh

# Verify installation
ollama --version
```

{% endtab %}

{% tab title="macOS" %}

```bash
# Option 1: Download from website
# Visit https://ollama.ai/download and download macOS installer

# Option 2: Homebrew
brew install ollama

# Verify installation
ollama --version
```

{% endtab %}

{% tab title="Windows" %}

```bash
# Download from https://ollama.ai/download
# Run the installer
# Open PowerShell or Command Prompt

# Verify installation
ollama --version
```

{% endtab %}
{% endtabs %}

#### Step 2: Start Ollama Service

```bash
# Start Ollama server (required for Gonzo to connect)
ollama serve

# This should show:
# Ollama is running on http://localhost:11434
```

{% hint style="info" %}
**Keep this running:** The `ollama serve` command needs to stay running for Gonzo to access AI features. Consider running it in a separate terminal or as a background service.
{% endhint %}

#### Step 3: Download AI Models

```bash
# Download recommended models for log analysis
ollama pull llama3        # Good general-purpose model (4.7GB)
ollama pull mistral       # Faster, smaller model (4.1GB)
ollama pull codellama     # Good for technical logs (3.8GB)

# Or download a larger, more capable model
ollama pull llama3:70b    # Very capable but requires 40GB+ RAM

# List available models
ollama list
```

#### Step 4: Configure Gonzo for Ollama

```bash
# Set environment variables for Ollama
export OPENAI_API_KEY="ollama"                    # Special key for Ollama
export OPENAI_API_BASE="http://localhost:11434"   # Ollama endpoint

# Verify Ollama is accessible
curl http://localhost:11434/api/tags
```

#### Step 5: Test Ollama Integration

```bash
# Test with automatic model selection
gonzo -f your-logs.log

# Test with specific model
gonzo -f your-logs.log --ai-model="llama3"

# Test model switching
# Press 'm' in Gonzo to see available Ollama models
```

### Local LM Studio Setup

#### Step 1: Install LM Studio

1. **Download LM Studio** from <https://lmstudio.ai/>
2. **Install the application** for your operating system
3. **Launch LM Studio**

#### Step 2: Download Models

1. **Open LM Studio**
2. **Go to "Discover" tab**
3. **Search and download recommended models:**
   * `microsoft/DialoGPT-medium` (lightweight, good for testing)
   * `meta-llama/Llama-2-7b-chat-hf` (balanced performance)
   * `meta-llama/Llama-2-13b-chat-hf` (better quality, needs more RAM)

#### Step 3: Start Model Server

1. **Go to "Local Server" tab in LM Studio**
2. **Select your downloaded model**
3. **Click "Start Server"**
4. **Note the server URL** (usually `http://localhost:1234`)

#### Step 4: Configure Gonzo for LM Studio

```bash
# Set environment variables for LM Studio
export OPENAI_API_KEY="local-key"                     # Any non-empty value
export OPENAI_API_BASE="http://localhost:1234/v1"     # Note the /v1 suffix

# Test connectivity
curl http://localhost:1234/v1/models
```

#### Step 5: Test LM Studio Integration

```bash
# Test with LM Studio
gonzo -f your-logs.log

# The model will be auto-selected from whatever's running in LM Studio
# Use 'm' to see available models
```

### Custom API Setup

#### Enterprise AI Services

**Azure OpenAI Service:**

```bash
export OPENAI_API_KEY="your-azure-key"
export OPENAI_API_BASE="https://your-resource.openai.azure.com/"
export OPENAI_API_TYPE="azure"
export OPENAI_API_VERSION="2023-05-15"
```

**AWS Bedrock (via compatible proxy):**

```bash
export OPENAI_API_KEY="your-aws-access-key"
export OPENAI_API_BASE="https://your-bedrock-proxy.amazonaws.com/v1"
```

**Custom OpenAI-Compatible API:**

```bash
export OPENAI_API_KEY="your-custom-api-key"
export OPENAI_API_BASE="https://your-ai-service.com/v1"
```

#### Testing Custom APIs

```bash
# Test API connectivity
curl -H "Authorization: Bearer $OPENAI_API_KEY" \
     "$OPENAI_API_BASE/models"

# Test with Gonzo
gonzo -f test-logs.log --ai-model="your-model-name"
```

### Real-World Examples

See AI features in action:

* [AI and a TUI: Practical Logging Tools for SREs](https://www.controltheory.com/blog/ai-and-a-tui-practical-logging-tools-for-sres/) - Practical AI use cases for incident response

### AI Features Deep Dive

#### Model Auto-Selection

Gonzo intelligently selects the best available AI model:

**OpenAI Priority:**

```
gpt-4 → gpt-3.5-turbo → first available
```

**Ollama Priority:**

```
gpt-oss:20b → llama3 → mistral → codellama → first available
```

**LM Studio:**

```
First available model loaded in LM Studio
```

#### Runtime Model Switching

**Press `m` anywhere to switch models:**

```
┌─ MODEL SELECTION ─────────────────────┐
│ Available Models:                     │
│                                       │
│ ✓ gpt-4                    (current)  │ ← Currently active
│   gpt-3.5-turbo                       │
│   gpt-3.5-turbo-16k                   │
│   text-davinci-003                    │
│                                       │
│ Navigation: ↑/↓, Enter to select      │
│ ESC to cancel                         │
└───────────────────────────────────────┘
```

**Benefits:**

* **Cost optimization** - Use expensive models only when needed
* **Performance tuning** - Fast models for quick questions, powerful models for complex analysis
* **Experimentation** - Compare responses from different models
* **Fallback options** - Switch if one model is unavailable

#### AI Analysis Types

{% tabs %}
{% tab title="Error Analysis" %}
**Single Log Entry Analysis:**

```bash
# Use case: Understanding specific errors
# Trigger: Press 'i' on error log entry

AI provides:
- Error explanation in plain English
- Potential root causes
- Investigation steps
- Related log patterns to look for
- Business impact assessment
```

**Example Response:**

```
"This NullPointerException in the user authentication service suggests the user profile wasn't properly loaded before authentication validation. This typically happens when:

1. Database query returned null (user doesn't exist)
2. Cache miss during user lookup
3. Race condition during user session creation

Impact: Users can't log in, affecting user experience and potentially revenue.

Next steps: Check user existence in database, verify cache hit rates, examine concurrent authentication requests."
```

{% endtab %}

{% tab title="Pattern Analysis" %}
**Multi-Log Pattern Analysis:**

```bash
# Use case: Understanding recurring issues
# Trigger: Filter logs, then use AI analysis

AI provides:
- Pattern significance explanation
- Trend analysis
- System health implications
- Optimization recommendations
- Preventive measures
```

**Example Response:**

```
"The recurring 'slow query' warnings show a performance degradation pattern:

- Frequency increased 300% in last 2 hours
- Affects primarily user lookup queries
- Correlates with increased user activity

This suggests:
1. Database index degradation
2. Query plan optimization needed
3. Potential need for query caching

Without intervention, this will likely escalate to timeout errors and user impact within 1-2 hours."
```

{% endtab %}

{% tab title="System Analysis" %}
**Overall System Health Analysis:**

```bash
# Use case: Understanding system-wide issues
# Trigger: AI analysis on filtered time ranges

AI provides:
- System health assessment
- Component interaction analysis
- Failure cascade identification
- Recovery recommendations
- Prevention strategies
```

**Example Response:**

```
"System analysis for the last 30 minutes shows a cascade failure pattern:

Timeline:
1. 14:15 - Database slow queries began
2. 14:18 - API gateway timeouts started
3. 14:20 - Authentication service became unresponsive
4. 14:22 - Load balancer began failing health checks

Root cause: Database performance degradation triggered system-wide impact.

Recovery priority:
1. Immediate: Restart database connections
2. Short-term: Scale database resources
3. Long-term: Implement circuit breakers to prevent cascade failures"
```

{% endtab %}
{% endtabs %}

### AI Workflow Integration

#### Development Workflow

```bash
# AI-enhanced development debugging
gonzo -f logs/debug.log --follow --ai-model="gpt-3.5-turbo"

# Workflow:
# 1. Reproduce issue while monitoring
# 2. AI identifies unusual patterns automatically
# 3. Press 'i' on error logs for instant explanation
# 4. Use AI chat to explore root causes
# 5. Get specific debugging recommendations
```

#### Production Monitoring

```bash
# AI-powered production monitoring
gonzo -f /var/log/app/*.log --follow --ai-model="gpt-4"

# Benefits:
# - Automatic anomaly detection
# - Intelligent alert context
# - Root cause hypothesis generation
# - Impact assessment
# - Recovery recommendations
```

#### Incident Response

```bash
# AI-assisted incident response
gonzo -f incident-logs.log --ai-model="gpt-4"

# Capabilities:
# - Rapid timeline reconstruction
# - Intelligent root cause analysis
# - Impact assessment
# - Recovery priority recommendations
# - Post-incident learning extraction
```

### Troubleshooting AI Issues

#### Common Setup Problems

**API Key Issues:**

```bash
# Verify API key is set correctly
echo $OPENAI_API_KEY

# Test API connectivity
curl -H "Authorization: Bearer $OPENAI_API_KEY" https://api.openai.com/v1/models
```

**Model Availability:**

```bash
# Check available models
gonzo --ai-model="test" 2>&1 | grep "available models"

# Test specific model
gonzo -f test.log --ai-model="gpt-3.5-turbo"
```

####

### What's Next?

Ready to set up AI integration? Continue with these detailed guides:

* **Setup & Configuration** - Get your AI provider configured
* **AI Providers Guide** - Detailed setup for each provider
* **Using AI Features** - Master AI-powered workflows

Or explore how AI integrates with other advanced features:

* **Log Analysis** - Combine AI with algorithmic analysis
* **Format Detection** - Optimize data for AI processing

***


# Custom Log Formats

Not every log is the same...

Gonzo supports custom log formats through YAML configuration files, allowing you to parse logs from any application and convert them to OpenTelemetry (OTLP) attributes for analysis.

### Using Built-in Formats

Gonzo includes pre-built formats in the [formats directory](https://github.com/control-theory/gonzo/tree/main/formats):

**Available formats:**

* `loki-stream.yaml` - Grafana Loki streaming (individual entries)
* `loki-batch.yaml` - Loki batch format with multi-entry expansion
* `vercel-stream.yaml` - Vercel logs
* `nodejs.yaml` - Node.js application logs
* `apache-combined.yaml` - Apache/Nginx access logs

**Setup:**

```bash
# Download and install format
mkdir -p ~/.config/gonzo/formats
cp <format-file>.yaml ~/.config/gonzo/formats/

# Use the format
gonzo --format=loki-stream -f logs.json

# List available formats
ls ~/.config/gonzo/formats/
```

**Examples:**

```bash
# Loki with logcli
logcli query --addr=http://localhost:3100 --follow '{service=~".+"}' -o jsonl 2>/dev/null | gonzo --format=loki-stream

# Loki Live Tail API using "wscat" (batch format)
wscat -c 'ws://localhost:3100/loki/api/v1/tail?query={service_name=~".%2B"}&limit=50' | gonzo --format=loki-batch

# Vercel logs
vercel logs <deployment_id> -j | gonzo --format=vercel-stream

# File with custom format
gonzo --format=nodejs -f application.log
```

### Creating Your Own Custom Formats

#### Quick Start

#### 1. Create a Format File

Create a YAML file in `~/.config/gonzo/formats/` directory:

```
mkdir -p ~/.config/gonzo/formats
vim ~/.config/gonzo/formats/myapp.yaml
```

#### 2. Define Your Format

```
name: myapp
description: My Application Log Format
type: text

pattern:
  use_regex: true
  main: '^(?P<timestamp>[\d\-T:\.]+)\s+\[(?P<level>\w+)\]\s+(?P<message>.*)$'

mapping:
  timestamp:
    field: timestamp
    time_format: rfc3339
  severity:
    field: level
  body:
    field: message
```

#### 3. Use the Format

```
gonzo --format=myapp -f application.log
```

#### Basic Structure

```yaml
# Metadata
name: format-name           # Required: Unique identifier
description: Description    # Optional: Human-readable description
author: Your Name           # Optional: Format author
type: text|json|structured  # Required: Format type

# Pattern Configuration (for text/structured types)
pattern:
  use_regex: true|false     # Use regex or template matching
  main: "pattern"           # Main pattern for parsing
  fields:                   # Additional field patterns
    field_name: "pattern"

# JSON Configuration (for json type)
json:
  fields:                   # Field mappings
    internal_name: json_path
  array_path: "path"        # For nested arrays
  root_is_array: true|false # If root is an array

# Field Mapping
mapping:
  timestamp:                # Timestamp extraction
    field: field_name
    time_format: format
    default: value

  severity:                 # Log level/severity
    field: field_name
    transform: operation
    default: value

  body:                     # Main log message
    field: field_name
    template: "{{.field}}"

  attributes:               # Additional attributes
    attr_name:
      field: source_field
      pattern: "regex"
      transform: operation
      default: value
```

#### Format Types

**text** - Plain text logs with regex patterns:

```yaml
type: text
pattern:
  use_regex: true
  main: 'your-regex-pattern-here'
```

**json** - JSON structured logs:

```yaml
type: json
json:
  fields:
    timestamp: $.timestamp
    message: $.msg
```

**structured** - Fixed position logs (Apache-style):

```yaml
type: structured
pattern:
  use_regex: true
  main: 'pattern-with-named-groups'
```

#### Common Regex Patterns

| Pattern       | Description         | Example                 |
| ------------- | ------------------- | ----------------------- |
| `[\d\-T:\.]+` | ISO timestamp       | 2024-01-15T10:30:45.123 |
| `\w+`         | Word characters     | ERROR, INFO             |
| `\d+`         | Digits              | 12345                   |
| `[^\]]+`      | Everything except ] | Content inside brackets |
| `.*`          | Any characters      | Rest of line            |
| `\S+`         | Non-whitespace      | Token or word           |

#### Time Formats

| Format                  | Example              | Description        |
| ----------------------- | -------------------- | ------------------ |
| `rfc3339`               | 2024-01-15T10:30:45Z | ISO 8601           |
| `unix`                  | 1705316445           | Unix seconds       |
| `unix_ms`               | 1705316445123        | Unix milliseconds  |
| `unix_ns`               | 1705316445123456789  | Unix nanoseconds   |
| `auto`                  | Various              | Auto-detect format |
| `"2006-01-02 15:04:05"` | 2024-01-15 10:30:45  | Custom Go format   |

#### Field Transforms

* `uppercase`: Convert to uppercase (info → INFO)
* `lowercase`: Convert to lowercase (ERROR → error)
* `trim`: Remove whitespace (" text " → "text")
* `status_to_severity`: HTTP status to severity (200→INFO, 404→WARN, 500→ERROR)

### Complete Examples

#### Example 1: Node.js Application Logs

**Log format:** `[Backend] 5300 LOG [Module] Message +6ms`

```yaml
# Format for: [Backend] 5300 LOG [Module] Message +6ms
name: nodejs
type: text

pattern:
  use_regex: true
  main: '^\[(?P<project>[^\]]+)\]\s+(?P<pid>\d+)\s+(?P<level>\w+)\s+\[(?P<module>[^\]]+)\]\s+(?P<message>[^+]+?)(?:\s+\+(?P<duration>\d+)ms)?$'

mapping:
  severity:
    field: level
    transform: uppercase
  body:
    field: message
  attributes:
    project:
      field: project
    pid:
      field: pid
    module:
      field: module
    duration_ms:
      field: duration
      default: "0"
```

#### Example 2: Kubernetes/Docker JSON Logs

**Format configuration:**

```yaml
name: k8s-json
type: json

json:
  fields:
    timestamp: time
    message: log
    stream: stream

mapping:
  timestamp:
    field: timestamp
    time_format: rfc3339
  body:
    field: message
  attributes:
    stream:
      field: stream
    container_name:
      field: kubernetes.container_name
    pod_name:
      field: kubernetes.pod_name
    namespace:
      field: kubernetes.namespace_name
```

#### Example 3: Apache Access Logs

**Log format:** `192.168.1.1 - - [14/Oct/2024:10:30:45 +0000] "GET /api/users HTTP/1.1" 200 1234`

```yaml
name: apache-access
type: structured

pattern:
  use_regex: true
  main: '^(?P<ip>[\d\.]+).*?\[(?P<timestamp>[^\]]+)\]\s+"(?P<method>\w+)\s+(?P<path>[^\s]+).*?"\s+(?P<status>\d+)\s+(?P<bytes>\d+)'

mapping:
  timestamp:
    field: timestamp
    time_format: "02/Jan/2006:15:04:05 -0700"
  body:
    template: "{{.method}} {{.path}} - {{.status}}"
  attributes:
    client_ip:
      field: ip
    http_method:
      field: method
    http_path:
      field: path
    http_status:
      field: status
    response_bytes:
      field: bytes
```

### Advanced Features

#### Batch Processing

For logs where a single line contains multiple entries (like Loki batch format):

```yaml
batch:
  enabled: true
  expand_path: "streams[].values[]"    # Arrays to expand
  context_paths: ["streams[].stream"]  # Metadata to preserve
```

**How it works:**

1. Original line: `{"streams":[{"stream":{"service":"app"},"values":[["1234","msg1"],["5678","msg2"]]}]}`
2. Gets expanded to: 2 separate log entries
3. Each entry retains the stream metadata

**Common patterns:**

* `logs[]` - Expand top-level array
* `streams[].values[]` - Expand nested arrays (Loki)
* `events[].entries[]` - Multi-level expansion

#### Nested JSON Fields

Access nested fields using dot notation:

```
attributes:
  user_id:
    field: user.id
  user_name:
    field: user.profile.name
```

#### Pattern Extraction

Extract values from within a field:

```
attributes:
  error_code:
    field: message
    pattern: 'ERROR\[(\d+)\]'  # Extracts code from "ERROR[404]: Not found"
```

#### Conditional Defaults

Use defaults when fields are missing:

```
attributes:
  environment:
    field: env
    default: "production"
```

#### HTTP Status Code to Severity Mapping

For web server logs, use the `status_to_severity` transform:

```
severity:
  field: http_status
  transform: status_to_severity
```

**Status code mapping:**

* 1xx (100-199): DEBUG (Informational)
* 2xx (200-299): INFO (Success)
* 3xx (300-399): INFO (Redirection)
* 4xx (400-499): WARN (Client Error)
* 5xx (500-599): ERROR (Server Error)

#### Multiple Pattern Matching

Define additional patterns for specific fields:

```
pattern:
  use_regex: true
  main: '^(?P<base>.*)'
  fields:
    request_id: 'RequestID:\s*(\w+)'
    user_id: 'UserID:\s*(\d+)'
```

### Testing & Troubleshooting

**Test your format:**

```bash
# Test with small sample
head -n 10 app.log | gonzo --format=myformat

# Test without TUI
gonzo --format=myformat -f app.log --test-mode
```

**Common issues:**

1. **Pattern not matching**: Test regex at regex101.com, verify named groups `(?P<name>...)`
2. **Wrong timestamps**: Check time\_format matches exactly, use Go format syntax
3. **Missing attributes**: Verify field paths (use dot notation for nested: `user.profile.name`)
4. **Performance issues**: Use specific patterns instead of `.*`, avoid overly complex regex

**Debug tips:**

* Start with simple patterns, add complexity gradually
* Use defaults for optional fields
* Test with various log samples
* Check Gonzo output for parsing errors

### Best Practices

* **Document your format**: Add description and example log lines
* **Use meaningful names**: Descriptive field names aid understanding
* **Handle edge cases**: Provide defaults for optional fields
* **Test thoroughly**: Verify with various log samples
* **Version control**: Keep formats in Git for team sharing
* **Optimize patterns**: Specific patterns perform better than generic ones

### Additional Resources

* **Format Examples**: <https://github.com/control-theory/gonzo/tree/main/formats>
* **Full Guide**: <https://github.com/control-theory/gonzo/blob/main/guides/CUSTOM\\_FORMATS.md>
* **Quick Reference**: <https://github.com/control-theory/gonzo/blob/main/guides/FORMAT\\_QUICK\\_REFERENCE.md>
* **Issue Tracker**: <https://github.com/control-theory/gonzo/issues>


# Skins

Get the look you want!

Gonzo supports customizable color schemes (skins) to personalize your terminal UI experience.

<figure><img src="/files/HyG4lOtYZ8klNoC470rF" alt=""><figcaption><p>Gonzo TUI using "dracula" theme skin</p></figcaption></figure>

### Using Built-in Skins

Gonzo includes 11+ pre-built themes in the [skins directory](https://github.com/control-theory/gonzo/tree/main/skins).

#### Available Skins

**Dark Themes 🌙**

* `default` - Original Gonzo dark theme
* `controltheory-dark` - ControlTheory branded dark theme
* `dracula` - Purple-accented vampire theme
* `gruvbox` - Retro groove colors
* `monokai` - Warm high-contrast theme
* `nord` - Arctic blue palette
* `solarized-dark` - Precision colors for reduced eye strain

**Light Themes ☀️**

* `controltheory` - ControlTheory branded light theme
* `github-light` - Clean GitHub-inspired light mode
* `solarized-light` - Precision light colors
* `vs-code-light` - Professional VS Code style
* `spring` - Fresh nature-inspired colors

#### Setup

**Download skins:**

```bash
# Create skins directory
mkdir -p ~/.config/gonzo/skins

# Download a specific skin
curl -o ~/.config/gonzo/skins/dracula.yaml \
  https://raw.githubusercontent.com/control-theory/gonzo/main/skins/dracula.yaml

# Or clone repo and copy all skins
git clone https://github.com/control-theory/gonzo.git
cp gonzo/skins/*.yaml ~/.config/gonzo/skins/
```

#### Usage

**Command line:**

```bash
# Use a skin
gonzo --skin=dracula -f application.log

# Short form
gonzo -s nord
```

**Environment variable:**

```bash
export GONZO_SKIN=github-light
gonzo -f application.log
```

**Configuration file** (`~/.config/gonzo/config.yml`):

```yaml
skin: solarized-dark
```

### Creating Custom Skins

Create a YAML file in `~/.config/gonzo/skins/` with this structure:

#### Basic Structure

```yaml
name: my-custom-skin
description: My awesome custom skin
author: Your Name

colors:
  # UI Components
  primary: "#0066cc"           # Main accent color
  secondary: "#00cc66"         # Secondary accent
  background: "#ffffff"        # Main background
  surface: "#f8f9fa"          # Panel backgrounds
  border: "#dee2e6"           # Section borders
  border_active: "#0066cc"     # Active borders
  text: "#212529"             # Primary text
  text_secondary: "#6c757d"    # Muted text
  text_inverse: "#ffffff"      # Text on colored backgrounds
  
  # Charts
  chart_title: "#0066cc"       # Chart titles
  chart_bar: "#00cc66"        # Bar chart bars
  chart_accent: "#ff6600"      # Chart accents
  
  # Log Entries
  log_timestamp: "#6c757d"     # Timestamps
  log_message: "#212529"       # Message text
  log_background: "#ffffff"    # Entry background
  log_selected: "#e3f2fd"      # Selected entry
  
  # Severity Levels
  severity_trace: "#adb5bd"    # TRACE
  severity_debug: "#6c757d"    # DEBUG
  severity_info: "#0066cc"     # INFO
  severity_warn: "#ff9500"     # WARN/WARNING
  severity_error: "#dc3545"    # ERROR
  severity_fatal: "#6f42c1"    # FATAL/CRITICAL
  
  # Status Indicators
  success: "#00cc66"          # Success states
  warning: "#ff9500"          # Warnings
  error: "#dc3545"            # Errors
  info: "#0066cc"             # Info
  
  # Special Elements
  help: "#6c757d"             # Help text
  highlight: "#fff3cd"        # Search highlights
  disabled: "#adb5bd"         # Disabled elements
```

#### Color Reference

| Category     | Color            | Purpose                              |
| ------------ | ---------------- | ------------------------------------ |
| **UI**       | `primary`        | Main accent color, active highlights |
|              | `secondary`      | Alternative highlights               |
|              | `background`     | Main dashboard background            |
|              | `surface`        | Modal/panel backgrounds              |
|              | `border`         | Default borders                      |
|              | `border_active`  | Active section borders               |
|              | `text`           | Primary readable text                |
|              | `text_secondary` | Timestamps, help text                |
|              | `text_inverse`   | Text on colored backgrounds          |
| **Charts**   | `chart_title`    | Chart section titles                 |
|              | `chart_bar`      | Bar chart elements                   |
|              | `chart_accent`   | Chart highlights                     |
| **Logs**     | `log_timestamp`  | Log timestamps                       |
|              | `log_message`    | Log message text                     |
|              | `log_background` | Log entry background                 |
|              | `log_selected`   | Selected log highlight               |
| **Severity** | `severity_trace` | TRACE level                          |
|              | `severity_debug` | DEBUG level                          |
|              | `severity_info`  | INFO level                           |
|              | `severity_warn`  | WARN/WARNING level                   |
|              | `severity_error` | ERROR level                          |
|              | `severity_fatal` | FATAL/CRITICAL level                 |
| **Status**   | `success`        | Success indicators                   |
|              | `warning`        | Warning indicators                   |
|              | `error`          | Error indicators                     |
|              | `info`           | Information indicators               |
| **Special**  | `help`           | Help text                            |
|              | `highlight`      | Search highlights                    |
|              | `disabled`       | Disabled elements                    |

#### Complete Examples

**Light Theme:**

```yaml
name: clean-light
description: A clean light theme
author: Me

colors:
  primary: "#0066cc"
  secondary: "#00cc66"
  background: "#ffffff"
  surface: "#f8f9fa"
  border: "#dee2e6"
  border_active: "#0066cc"
  text: "#212529"
  text_secondary: "#6c757d"
  text_inverse: "#ffffff"
  
  chart_title: "#0066cc"
  chart_bar: "#00cc66"
  chart_accent: "#ff6600"
  
  log_timestamp: "#6c757d"
  log_message: "#212529"
  log_background: "#ffffff"
  log_selected: "#e3f2fd"
  
  severity_trace: "#adb5bd"
  severity_debug: "#6c757d"
  severity_info: "#0066cc"
  severity_warn: "#fd7e14"
  severity_error: "#dc3545"
  severity_fatal: "#6f42c1"
  
  success: "#00cc66"
  warning: "#fd7e14"
  error: "#dc3545"
  info: "#0066cc"
  
  help: "#6c757d"
  highlight: "#fff3cd"
  disabled: "#adb5bd"
```

**Dark Theme:**

```yaml
name: sleek-dark
description: A sleek dark theme
author: Me

colors:
  primary: "#66d9ef"
  secondary: "#a6e22e"
  background: "#272822"
  surface: "#3e3d32"
  border: "#75715e"
  border_active: "#66d9ef"
  text: "#f8f8f2"
  text_secondary: "#75715e"
  text_inverse: "#272822"
  
  chart_title: "#66d9ef"
  chart_bar: "#a6e22e"
  chart_accent: "#fd971f"
  
  log_timestamp: "#75715e"
  log_message: "#f8f8f2"
  log_background: "#272822"
  log_selected: "#49483e"
  
  severity_trace: "#75715e"
  severity_debug: "#ae81ff"
  severity_info: "#66d9ef"
  severity_warn: "#e6db74"
  severity_error: "#f92672"
  severity_fatal: "#ae81ff"
  
  success: "#a6e22e"
  warning: "#e6db74"
  error: "#f92672"
  info: "#66d9ef"
  
  help: "#75715e"
  highlight: "#49483e"
  disabled: "#75715e"
```

#### Using Your Custom Skin

```bash
# Save as ~/.config/gonzo/skins/my-skin.yaml
gonzo --skin=my-skin -f application.log
```

### Design Guidelines

**Light Themes:**

* Use dark text (#212529) on light backgrounds (#ffffff)
* Ensure contrast ratio ≥ 4.5:1 (WCAG AA)
* Use muted colors for secondary elements
* Prefer subtle grays over pure white

**Dark Themes:**

* Use light text (#f8f8f2) on dark backgrounds (#272822)
* Avoid pure black; use dark grays
* Use vibrant colors for accents
* Ensure readability in low-light

**Accessibility:**

* Test with color blindness simulators
* Maintain adequate contrast ratios
* Don't rely solely on color to convey information

### Troubleshooting

**Skin not loading:**

```bash
# Check if skin exists
ls ~/.config/gonzo/skins/

# Verify YAML syntax
cat ~/.config/gonzo/skins/my-skin.yaml

# Test with default
gonzo --skin=default
```

**Missing colors:** All colors are optional. Unspecified colors use defaults.

**Color formats:** Use hex colors (`#ff0000`, `#RGB`, `#RRGGBB`)

### Contributing Skins

Share your skin with the community! Submit a pull request to the [Gonzo repository](https://github.com/control-theory/gonzo) with:

* Your skin YAML file
* Screenshots (optional but appreciated)
* Description of the theme

### Additional Resources

* **Skin Examples:** <https://github.com/control-theory/gonzo/tree/main/skins>
* **Issue Tracker:** <https://github.com/control-theory/gonzo/issues>


# Configuration

Customize Gonzo to match your workflow, environment, and performance requirements. From simple command-line flags to sophisticated YAML configurations, Gonzo provides flexible options for any use case.

<table data-view="cards"><thead><tr><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><strong>Configuration File</strong></td><td>Details on Gonzo configuration files</td><td><a href="/pages/AMQIbIJesInxp3CxQoI8">/pages/AMQIbIJesInxp3CxQoI8</a></td></tr><tr><td><strong>Command Line Reference</strong></td><td>CLI reference guide for Gonzo</td><td><a href="/pages/rxAj9bfITutsIeqnJGp5">/pages/rxAj9bfITutsIeqnJGp5</a></td></tr></tbody></table>

***

**Start with the defaults, configure when needed, optimize for your workflow.** ⚙️ Gonzo's flexible configuration system grows with your needs, from simple CLI flags to sophisticated production deployments.


# Configuration File

Master YAML-based configuration for persistent Gonzo settings. Configuration files provide a powerful way to manage complex setups, share team standards, and maintain environment-specific configurations.

{% hint style="info" %}
**Quick Start:** Create `~/.config/gonzo/config.yml` and Gonzo will use it automatically. No need to specify the file on every command.
{% endhint %}

### Configuration File Basics

#### File Locations

Gonzo searches for configuration files in this order:

```bash
# 1. Explicit path (highest priority)
gonzo --config /path/to/myconfig.yml

# 2. Current directory
./config.yml
./gonzo.yml

# 3. User config directory (recommended)
~/.config/gonzo/config.yml

# 4. System-wide config
/etc/gonzo/config.yml
```

**Recommended approach:**

```bash
# Create user config directory
mkdir -p ~/.config/gonzo

# Create your configuration file
cat > ~/.config/gonzo/config.yml << 'EOF'
# Your Gonzo configuration
files:
  - "/var/log/app.log"
follow: true
update-interval: 2s
EOF
```

#### Basic Configuration Structure

```yaml
# ~/.config/gonzo/config.yml

# File input configuration
files:
  - "/var/log/app.log"
  - "/var/log/nginx/*.log"
follow: true

# Performance settings
update-interval: 2s
log-buffer: 5000
memory-size: 15000

# AI configuration
ai-model: "gpt-4"

# Display options
show-host: true
show-service: true
```

### Complete Configuration Reference

#### File Input Configuration

**Control which logs to analyze:**

```yaml
# Single file
files:
  - "/var/log/app.log"

# Multiple specific files
files:
  - "/var/log/app.log"
  - "/var/log/error.log"
  - "/var/log/debug.log"

# Glob patterns
files:
  - "/var/log/*.log"
  - "/var/log/app-*.log"
  - "logs/**/*.log"

# Mixed approaches
files:
  - "/var/log/app.log"          # Specific file
  - "/var/log/nginx/*.log"      # Glob pattern
  - "/home/user/debug.log"      # User directory

# Follow mode (like tail -f)
follow: true                     # Enable following
follow: false                    # Disable (default for single files)
```

**Options:**

* `files` (array of strings) - Files or glob patterns to read
* `follow` (boolean) - Enable real-time following (default: `false`)

#### Performance Configuration

**Tune Gonzo's performance characteristics:**

```yaml
# Update frequency
update-interval: 2s              # How often to refresh display
                                 # Options: 1s, 2s, 5s, 10s, 30s
                                 # Lower = more responsive, higher CPU
                                 # Higher = less CPU, less responsive

# Buffer sizes
log-buffer: 5000                 # Maximum log entries to keep in memory
                                 # Default: 1000
                                 # Higher = more history, more memory
                                 # Lower = less memory, less history

memory-size: 15000               # Maximum word frequency entries
                                 # Default: 10000
                                 # Higher = more pattern tracking
                                 # Lower = less memory usage

# Processing options
batch-size: 100                  # Number of logs to process per batch
                                 # Default: 100
                                 # Higher = more efficient, higher latency
                                 # Lower = more responsive, less efficient
```

**Tuning Guidelines:**

{% tabs %}
{% tab title="Development" %}

```yaml
# Optimized for fast iteration
update-interval: 1s              # Fast updates
log-buffer: 2000                # Moderate history
memory-size: 10000              # Sufficient for development
```

{% endtab %}

{% tab title="Production Monitoring" %}

```yaml
# Optimized for reliability and history
update-interval: 5s              # Conservative updates
log-buffer: 10000               # Large history buffer
memory-size: 50000              # Comprehensive pattern tracking
```

{% endtab %}

{% tab title="High Volume" %}

```yaml
# Optimized for processing speed
update-interval: 10s             # Slow updates to reduce overhead
log-buffer: 20000               # Large buffer for throughput
memory-size: 100000             # Extensive pattern capacity
batch-size: 500                 # Large batches for efficiency
```

{% endtab %}

{% tab title="Resource Constrained" %}

```yaml
# Optimized for minimal resource usage
update-interval: 5s              # Moderate updates
log-buffer: 1000                # Minimal buffer
memory-size: 5000               # Reduced memory footprint
batch-size: 50                  # Smaller batches
```

{% endtab %}
{% endtabs %}

#### AI Configuration

**Configure AI analysis features:**

```yaml
# Basic AI settings
ai-model: "gpt-4"                # Default AI model to use
                                 # Options: "gpt-4", "gpt-3.5-turbo", 
                                 # "llama3", "mistral", etc.

ai-auto-select: true             # Automatically select best available model
                                 # Default: true

# AI provider configuration (usually via environment variables)
# These are typically set as env vars, not in config file
# OPENAI_API_KEY="sk-..."
# OPENAI_API_BASE="https://api.openai.com/v1"

# AI performance settings
ai-context-size: 4000            # Maximum context tokens for AI
                                 # Default: 4000
                                 # Higher = better context, more cost
                                 # Lower = less cost, less context

ai-response-timeout: 30s         # Timeout for AI responses
                                 # Default: 30s
                                 # Increase for complex analysis

ai-max-retries: 3                # Retry failed AI requests
                                 # Default: 3

# AI cost management
ai-daily-token-limit: 100000     # Optional daily token budget
ai-warn-at-usage: 80000          # Warning threshold (80%)
```

**AI Configuration Examples:**

{% tabs %}
{% tab title="OpenAI Production" %}

```yaml
# High-quality AI for critical analysis
ai-model: "gpt-4"
ai-context-size: 8000            # Large context for complex issues
ai-response-timeout: 60s         # Allow time for thorough analysis
ai-max-retries: 5                # Ensure reliability
```

{% endtab %}

{% tab title="Cost-Optimized" %}

```yaml
# Balance cost and quality
ai-model: "gpt-3.5-turbo"
ai-context-size: 2000            # Smaller context to reduce tokens
ai-response-timeout: 30s
ai-daily-token-limit: 50000      # Cost control
```

{% endtab %}

{% tab title="Local AI" %}

```yaml
# Privacy-focused local AI
ai-model: "llama3"               # Local Ollama model
ai-context-size: 4000
ai-response-timeout: 60s         # Local inference can be slower
# No token limits needed with local AI
```

{% endtab %}
{% endtabs %}

#### Display Configuration

**Customize the interface appearance:**

```yaml
# Column visibility
show-host: true                  # Show host/source column
                                 # Default: false
show-service: true               # Show service column
                                 # Default: false

# Color and formatting
no-color: false                  # Disable color output
                                 # Default: false
                                 # Useful for logging output to files

# Output options
json-output: false               # Output as JSON instead of TUI
                                 # Default: false
                                 # Useful for scripting

quiet: false                     # Suppress non-essential output
                                 # Default: false
```

#### Stop Words Configuration

**Filter common or domain-specific words from frequency analysis:**

```yaml
# Stop words configuration
stop-words:
  - "debug"                      # Filter log-specific terms
  - "info"
  - "warning"
  - "error"
  - "log"
  - "message"
  - "timestamp"
  - "level"
  - "springframework"            # Filter framework noise
  - "hibernate"
  - "GET"                        # Filter HTTP-related terms
  - "POST"
  - "HTTP"
```

**How Stop Words Work:**

* Filters words from Word Frequency panel analysis
* Case-insensitive matching ("ERROR" and "error" treated the same)
* Added to built-in English stop words (60+ common words like "the", "and", "for")
* Does not affect log display or filtering - only frequency analysis
* Changes take effect immediately when logs are processed

**Use Cases:**

{% tabs %}
{% tab title="Web Server Logs" %}

```yaml
# Filter HTTP-related terms to focus on actual content
stop-words:
  - "GET"
  - "POST"
  - "PUT"
  - "DELETE"
  - "HTTP"
  - "HTTPS"
  - "status"
  - "request"
  - "response"
```

{% endtab %}

{% tab title="Application Logs" %}

```yaml
# Filter framework and logging noise
stop-words:
  - "log"
  - "message"
  - "level"
  - "timestamp"
  - "logger"
  - "springframework"
  - "hibernate"
  - "slf4j"
```

{% endtab %}

{% tab title="Error Analysis" %}

```yaml
# Focus on actual errors, not stack trace noise
stop-words:
  - "stack"
  - "trace"
  - "at"
  - "caused"
  - "exception"
  - "error"
  - "line"
```

{% endtab %}
{% endtabs %}

#### OTLP Configuration

**OpenTelemetry Protocol receiver settings:**

```yaml
# Enable OTLP receiver
otlp-enabled: true               # Start OTLP receiver
                                 # Default: false

# OTLP ports
otlp-grpc-port: 4317             # gRPC endpoint port
                                 # Default: 4317
otlp-http-port: 4318             # HTTP endpoint port  
                                 # Default: 4318

# OTLP processing
otlp-batch-size: 100             # Batch size for OTLP logs
                                 # Default: 100
```

**OTLP Configuration Example:**

```yaml
# Full OTLP receiver setup
otlp-enabled: true
otlp-grpc-port: 5317             # Custom ports to avoid conflicts
otlp-http-port: 5318

# Also analyze local files
files:
  - "/var/log/backup.log"
follow: true

# Performance for OTLP ingestion
log-buffer: 20000                # Large buffer for OTLP volume
update-interval: 5s              # Conservative updates
```

#### Development and Testing Options

**Configuration for testing and development:**

```yaml
# Testing mode
test-mode: true                  # Enable test mode
                                 # Default: false
                                 # Runs without full TUI, good for CI/CD

# Verbose output
verbose: false                   # Enable verbose logging
                                 # Default: false
                                 # Useful for debugging

# Dry run
dry-run: false                   # Show what would be done without doing it
                                 # Default: false
                                 # Good for validating configuration
```

### Complete Configuration Examples

#### Personal Development Setup

```yaml
# ~/.config/gonzo/config.yml
# Personal development configuration

# Development logs
files:
  - "logs/*.log"
  - "debug/*.log"
  - "test-results/*.log"

# Follow for live development
follow: true

# Fast updates for immediate feedback
update-interval: 1s

# Moderate buffers for development
log-buffer: 2000
memory-size: 10000

# Cost-effective AI
ai-model: "gpt-3.5-turbo"
ai-auto-select: true

# Show full context
show-host: true
show-service: true

# Comments are preserved for documentation
# This config optimized for: Fast iteration, cost control
```

#### Production Monitoring

```yaml
# ~/.config/gonzo/prod.yml
# Production monitoring configuration

# Production log locations
files:
  - "/var/log/app/*.log"
  - "/var/log/nginx/access.log"
  - "/var/log/nginx/error.log"
  - "/var/log/postgresql/*.log"

# Real-time monitoring
follow: true

# Conservative updates for reliability
update-interval: 5s

# Large buffers for comprehensive analysis
log-buffer: 10000
memory-size: 50000

# Best quality AI for production
ai-model: "gpt-4"
ai-context-size: 8000
ai-response-timeout: 60s
ai-max-retries: 5

# Full visibility
show-host: true
show-service: true

# Production notes:
# - Uses gpt-4 for best analysis quality
# - Large buffers for comprehensive history
# - Conservative update interval for reliability
# - Monitors all critical services
```

#### CI/CD Pipeline

```yaml
# config/gonzo-ci.yml
# CI/CD automated analysis configuration

# Build and test logs
files:
  - "build-logs/*.log"
  - "test-results/*.log"
  - "integration-tests/*.log"

# Batch processing (not following)
follow: false

# Moderate performance
update-interval: 2s
log-buffer: 5000

# Fast, cost-effective AI
ai-model: "gpt-3.5-turbo"
ai-context-size: 2000
ai-response-timeout: 30s

# CI-friendly output
test-mode: true                  # Non-interactive mode
json-output: false               # Keep TUI output for logs
quiet: false                     # Show all output

# Notes:
# - test-mode enables CI-friendly operation
# - Uses cost-effective AI model
# - Processes logs in batch, not real-time
```

#### Team Standard Configuration

```yaml
# team-standard.yml
# Shared configuration across development team
# Version control this file

# Standard log locations (relative paths)
files:
  - "logs/*.log"

# Standard performance settings
update-interval: 2s
log-buffer: 5000
memory-size: 15000

# Team AI standard
ai-model: "gpt-3.5-turbo"        # Cost-effective default
ai-auto-select: true             # Allow auto-upgrade when needed

# Display standards
show-service: true               # Always show service context

# Team notes:
# - API keys managed via environment variables (not in config)
# - Use gpt-4 for incident response (override with CLI flag)
# - Update this file through pull requests
# - Document reasoning for any changes

# Last updated: 2024-01-15
# Updated by: DevOps team
# Reason: Increased log-buffer for better analysis
```

#### Security Monitoring

```yaml
# ~/.config/gonzo/security.yml
# Security-focused monitoring configuration

# Security-relevant logs
files:
  - "/var/log/auth.log"
  - "/var/log/nginx/access.log"
  - "/var/log/fail2ban.log"
  - "/var/log/app/security.log"

# Real-time monitoring for security
follow: true
update-interval: 2s              # Responsive for security events

# Large buffers for security analysis
log-buffer: 15000
memory-size: 75000

# Best AI for security analysis
ai-model: "gpt-4"
ai-context-size: 8000
ai-response-timeout: 60s

# Full context for security investigations
show-host: true
show-service: true

# Security notes:
# - Monitor all authentication and access logs
# - Use gpt-4 for accurate threat assessment
# - Large buffers for pattern analysis
# - Real-time monitoring for rapid response
```

### Configuration Profiles

#### Managing Multiple Configurations

Create different profiles for different scenarios:

```bash
# Directory structure
~/.config/gonzo/
├── config.yml              # Default configuration
├── dev.yml                 # Development profile
├── prod.yml                # Production profile
├── security.yml            # Security monitoring
├── performance.yml         # Performance analysis
└── incident.yml            # Incident response

# Usage with aliases
alias gonzo-dev='gonzo --config ~/.config/gonzo/dev.yml'
alias gonzo-prod='gonzo --config ~/.config/gonzo/prod.yml'
alias gonzo-security='gonzo --config ~/.config/gonzo/security.yml'
alias gonzo-incident='gonzo --config ~/.config/gonzo/incident.yml'

# Quick switching
gonzo-dev        # Use development config
gonzo-prod       # Use production config
gonzo-security   # Use security monitoring config
```

#### Profile Inheritance Strategy

```yaml
# base.yml - Shared settings
# Include common settings here

update-interval: 2s
log-buffer: 5000
show-service: true

# Then extend in specific profiles:
# dev.yml includes base settings + overrides
# prod.yml includes base settings + overrides
# Use YAML anchors for inheritance (advanced)
```

### Configuration Validation

#### Testing Your Configuration

```bash
# Validate configuration syntax
gonzo --config myconfig.yml --dry-run

# Show what configuration would be used
gonzo --config myconfig.yml --show-config

# Test with verbose output
gonzo --config myconfig.yml --verbose

# Test mode for CI/CD validation
gonzo --config myconfig.yml --test-mode
```

#### Common Configuration Errors

**Invalid YAML Syntax:**

```yaml
# ❌ Wrong - improper indentation
files:
- "/var/log/app.log"
  - "/var/log/error.log"    # Inconsistent indentation

# ✅ Correct - consistent indentation
files:
  - "/var/log/app.log"
  - "/var/log/error.log"
```

**Invalid Data Types:**

```yaml
# ❌ Wrong - string instead of number
log-buffer: "5000"           # Should be number, not string

# ✅ Correct - proper types
log-buffer: 5000             # Number
follow: true                 # Boolean
files:                       # Array
  - "/var/log/app.log"
```

**Invalid Values:**

```yaml
# ❌ Wrong - invalid duration format
update-interval: 2seconds    # Invalid format

# ✅ Correct - proper duration syntax
update-interval: 2s          # Valid: 1s, 2s, 5s, 10s, 30s, 1m
```

### Configuration Best Practices

#### 🎯 **Organization**

```yaml
# Group related settings with comments
# ===== File Input Configuration =====
files:
  - "/var/log/app.log"
follow: true

# ===== Performance Settings =====
update-interval: 2s
log-buffer: 5000
memory-size: 15000

# ===== AI Configuration =====
ai-model: "gpt-4"
ai-context-size: 4000

# ===== Display Options =====
show-host: true
show-service: true
```

#### 🔒 **Security**

```yaml
# ✅ Good - API keys in environment variables
ai-model: "gpt-4"
# OPENAI_API_KEY set via environment variable

# ❌ Bad - API keys in config file
# ai-api-key: "sk-secret-key-here"  # NEVER DO THIS

# ✅ Good - Document expectations
# Required environment variables:
# - OPENAI_API_KEY: OpenAI API key for AI features
# - GONZO_LOG_PATH: Override default log path
```

#### 📝 **Documentation**

```yaml
# Document your configuration choices
# Last updated: 2024-01-15
# Owner: DevOps Team
# Purpose: Production monitoring configuration

# Performance tuning reasoning:
# - update-interval: 5s chosen to balance responsiveness with CPU usage
# - log-buffer: 10000 provides 10-15 minutes of history at typical volume
# - memory-size: 50000 supports comprehensive pattern analysis

files:
  - "/var/log/app/*.log"
update-interval: 5s
log-buffer: 10000
memory-size: 50000
```

#### 🔄 **Version Control**

```bash
# Create a repository for team configurations
mkdir gonzo-configs
cd gonzo-configs
git init

# Add configurations
cp ~/.config/gonzo/team-standard.yml .
cp ~/.config/gonzo/prod.yml .

# Create README documenting each config
cat > README.md << 'EOF'
# Gonzo Configurations

## team-standard.yml
Default configuration for development team

## prod.yml  
Production monitoring configuration
EOF

git add .
git commit -m "Initial Gonzo configurations"
```

### Advanced Configuration Patterns

#### Environment Variable Substitution

```yaml
# Use environment variables in config (if supported)
files:
  - "${LOG_DIR}/*.log"
  - "${APP_LOG_PATH}/application.log"

ai-model: "${GONZO_AI_MODEL:-gpt-3.5-turbo}"  # Default if not set
```

#### Conditional Configuration

```bash
# Use different configs based on environment
GONZO_ENV="${ENVIRONMENT:-development}"
CONFIG_FILE="~/.config/gonzo/${GONZO_ENV}.yml"

gonzo --config "$CONFIG_FILE"
```

#### Configuration Generation

```bash
#!/bin/bash
# generate-config.sh - Dynamic configuration generation

cat > ~/.config/gonzo/config.yml << EOF
# Generated configuration
# Environment: ${ENVIRONMENT}
# Generated: $(date)

files:
  - "${LOG_PATH}/*.log"

update-interval: ${UPDATE_INTERVAL:-2s}
log-buffer: ${LOG_BUFFER:-5000}
ai-model: "${AI_MODEL:-gpt-3.5-turbo}"
EOF
```

### Troubleshooting Configuration

#### Configuration Not Loading

```bash
# Check if config file exists
ls -la ~/.config/gonzo/config.yml

# Check file permissions
chmod 644 ~/.config/gonzo/config.yml

# Test with explicit path
gonzo --config ~/.config/gonzo/config.yml

# Check for YAML syntax errors
# Use a YAML validator or Python
python3 -c "import yaml; yaml.safe_load(open('config.yml'))"
```

#### Settings Not Taking Effect

```bash
# Remember: CLI flags override config file
# If running: gonzo --log-buffer=3000
# Config file log-buffer setting is ignored

# Check actual configuration being used
gonzo --show-config

# Use verbose mode to see configuration loading
gonzo --verbose
```

#### Performance Issues

```bash
# Config might be too aggressive for your system
# Symptoms: High CPU, high memory usage

# Solution: Start with conservative settings
update-interval: 5s              # Slower updates
log-buffer: 2000                # Smaller buffer
memory-size: 10000              # Less memory

# Then gradually increase if needed
```

### What's Next?

Now that you understand configuration files, explore related topics:

* **Command Line Reference** - All CLI flags that can override config settings
* **Advanced Configuration** - Complex setups and optimization techniques
* **Integration Examples** - Configuration in real-world scenarios

Or start creating your own configurations:

```bash
# Create your first config file
mkdir -p ~/.config/gonzo
cat > ~/.config/gonzo/config.yml << 'EOF'
# My Gonzo Configuration
files:
  - "/var/log/app.log"
follow: true
update-interval: 2s
log-buffer: 5000
ai-model: "gpt-3.5-turbo"
EOF

# Test it
gonzo
```

***

**Master configuration files to maintain consistent, powerful Gonzo setups!** 📝 From simple personal configs to sophisticated team standards, configuration files make Gonzo work exactly how you need it.


# Command Line Reference

Complete reference for all Gonzo command-line flags and options. From basic file input to advanced performance tuning, this guide covers every CLI option available.

{% hint style="info" %}
**Quick Reference:** Use `gonzo --help` or `gonzo -h` to see a summary of all available flags at any time.
{% endhint %}

### Command Syntax

```bash
gonzo [flags] [command]

# Basic usage
gonzo -f application.log
gonzo -f logs/*.log --follow

# With multiple options
gonzo -f app.log --follow --log-buffer=5000 --ai-model="gpt-4"

# Using configuration file
gonzo --config ~/.config/gonzo/config.yml

# Piping input
cat logs.log | gonzo
kubectl logs -f pod/my-app | gonzo
```

### Core Flags

#### File Input

**Specify log files or patterns to analyze:**

| Flag       | Short | Type    | Description                  | Example                     |
| ---------- | ----- | ------- | ---------------------------- | --------------------------- |
| `--file`   | `-f`  | string  | File or glob pattern to read | `gonzo -f app.log`          |
| `--follow` |       | boolean | Follow file like `tail -f`   | `gonzo -f app.log --follow` |

**Examples:**

```bash
# Single file
gonzo -f application.log

# Multiple files
gonzo -f api.log -f db.log -f cache.log

# Glob patterns (use quotes)
gonzo -f "/var/log/*.log"
gonzo -f "/var/log/app-*.log"

# Follow mode (real-time)
gonzo -f /var/log/app.log --follow

# Multiple files with follow
gonzo -f "/var/log/*.log" --follow

# Combine specific files and patterns
gonzo -f app.log -f "/var/log/nginx/*.log" --follow
```

**Notes:**

* Can be specified multiple times for multiple sources
* Glob patterns must be quoted to prevent shell expansion
* `--follow` works like `tail -f` for real-time monitoring
* Without `--follow`, Gonzo reads entire file and exits

#### Configuration

**Specify configuration files and options:**

| Flag       | Short | Type   | Description                | Example                   |
| ---------- | ----- | ------ | -------------------------- | ------------------------- |
| `--config` |       | string | Path to configuration file | `gonzo --config prod.yml` |

**Examples:**

```bash
# Use specific config file
gonzo --config ~/.config/gonzo/prod.yml

# Relative path
gonzo --config ./my-config.yml

# Absolute path
gonzo --config /etc/gonzo/system.yml

# CLI flags override config file settings
gonzo --config prod.yml --log-buffer=10000
```

**Config File Search Path:**

1. Path specified with `--config` flag
2. `./config.yml` (current directory)
3. `~/.config/gonzo/config.yml` (user config)
4. `/etc/gonzo/config.yml` (system config)

### Performance Flags

#### Buffer and Memory

**Control memory usage and buffer sizes:**

| Flag                | Short | Type     | Default | Description                 |
| ------------------- | ----- | -------- | ------- | --------------------------- |
| `--log-buffer`      | `-b`  | int      | 1000    | Maximum log entries to keep |
| `--memory-size`     | `-m`  | int      | 10000   | Maximum frequency entries   |
| `--update-interval` | `-u`  | duration | 1s      | Dashboard update interval   |

**Examples:**

```bash
# Increase buffer for more history
gonzo -f app.log --log-buffer=10000

# Reduce memory for constrained systems
gonzo -f app.log --log-buffer=500 --memory-size=2000

# Slower updates for better performance
gonzo -f busy.log --update-interval=5s

# High-performance setup
gonzo -f logs.log \
      --log-buffer=20000 \
      --memory-size=50000 \
      --update-interval=10s

# Memory-constrained setup
gonzo -f logs.log \
      --log-buffer=1000 \
      --memory-size=5000 \
      --update-interval=5s
```

**Guidelines:**

{% tabs %}
{% tab title="Default Settings" %}

```bash
# Good for most use cases
--log-buffer=1000      # ~1-2 minutes of history
--memory-size=10000    # Standard pattern tracking
--update-interval=1s   # Responsive updates
```

{% endtab %}

{% tab title="High Volume" %}

```bash
# For logs with >100 entries/second
--log-buffer=20000     # Larger buffer for throughput
--memory-size=100000   # Extensive pattern tracking
--update-interval=10s  # Reduce update overhead
```

{% endtab %}

{% tab title="Low Memory" %}

```bash
# For systems with <4GB RAM
--log-buffer=500       # Minimal buffer
--memory-size=2000     # Reduced tracking
--update-interval=5s   # Less frequent updates
```

{% endtab %}

{% tab title="Development" %}

```bash
# For fast development iteration
--log-buffer=2000      # Moderate history
--memory-size=10000    # Standard tracking
--update-interval=1s   # Fast updates
```

{% endtab %}
{% endtabs %}

### AI Configuration Flags

#### AI Model Selection

**Configure AI analysis features:**

| Flag         | Type   | Default | Description                  |
| ------------ | ------ | ------- | ---------------------------- |
| `--ai-model` | string | auto    | AI model to use for analysis |

**Examples:**

```bash
# Use specific model
gonzo -f app.log --ai-model="gpt-4"
gonzo -f app.log --ai-model="gpt-3.5-turbo"
gonzo -f app.log --ai-model="llama3"

# Auto-select best available (default)
gonzo -f app.log

# Cost-effective for development
gonzo -f debug.log --ai-model="gpt-3.5-turbo"

# Best quality for production incidents
gonzo -f incident.log --ai-model="gpt-4"

# Local AI for privacy
export OPENAI_API_BASE="http://localhost:11434"
gonzo -f sensitive.log --ai-model="llama3"
```

**Supported Models:**

* **OpenAI:** `gpt-4`, `gpt-4-turbo`, `gpt-3.5-turbo`, `gpt-3.5-turbo-16k`
* **Ollama:** `llama3`, `llama3:70b`, `mistral`, `mixtral`, `codellama`
* **LM Studio:** Any model loaded in LM Studio
* **Auto:** Automatically selects best available model

**AI Environment Variables:**

```bash
# OpenAI
export OPENAI_API_KEY="sk-your-key"
export OPENAI_API_BASE="https://api.openai.com/v1"

# Ollama
export OPENAI_API_KEY="ollama"
export OPENAI_API_BASE="http://localhost:11434"

# LM Studio
export OPENAI_API_KEY="local-key"
export OPENAI_API_BASE="http://localhost:1234/v1"
```

### OTLP Flags

#### OpenTelemetry Protocol

**Configure OTLP log receiver:**

| Flag               | Type    | Default | Description          |
| ------------------ | ------- | ------- | -------------------- |
| `--otlp-enabled`   | boolean | false   | Enable OTLP receiver |
| `--otlp-grpc-port` | int     | 4317    | gRPC endpoint port   |
| `--otlp-http-port` | int     | 4318    | HTTP endpoint port   |

**Examples:**

```bash
# Enable OTLP with default ports
gonzo --otlp-enabled

# Custom ports
gonzo --otlp-enabled \
      --otlp-grpc-port=5317 \
      --otlp-http-port=5318

# OTLP + file backup
gonzo --otlp-enabled -f backup.log --follow

# OTLP with specific configuration
gonzo --otlp-enabled \
      --log-buffer=20000 \
      --update-interval=5s
```

**OTLP Endpoints:**

* **gRPC:** `localhost:4317` (or custom port)
* **HTTP:** `http://localhost:4318/v1/logs` (or custom port)

### Display and Output Flags

#### Interface Customization

**Control display appearance and behavior:**

| Flag              | Short | Type    | Default | Description               |
| ----------------- | ----- | ------- | ------- | ------------------------- |
| `--no-color`      |       | boolean | false   | Disable color output      |
| `-v`, `--version` |       | boolean | false   | Print version information |
| `-h`, `--help`    |       | boolean | false   | Show help message         |

**Examples:**

```bash
# Disable colors (for logging to files)
gonzo -f app.log --no-color > output.txt

# Show version
gonzo --version
gonzo -v

# Show help
gonzo --help
gonzo -h

# Quiet mode (minimal output)
gonzo -f app.log --quiet

# Verbose mode (detailed output)
gonzo -f app.log --verbose
```

### Development and Testing Flags

#### Testing and Debugging

**Options for development and CI/CD:**

| Flag           | Short | Type    | Default | Description                                   |
| -------------- | ----- | ------- | ------- | --------------------------------------------- |
| `--test-mode`  | `-t`  | boolean | false   | Run without TTY for testing                   |
| `--verbose`    |       | boolean | false   | Enable verbose output                         |
| `--dry-run`    |       | boolean | false   | Show config without running                   |
| `--stop-words` |       | strings | \[]     | Additional stop words to filter from analysis |

**Examples:**

```bash
# Test mode (CI/CD friendly)
gonzo -f build.log --test-mode

# Verbose output for debugging
gonzo -f app.log --verbose

# Dry run to validate configuration
gonzo --config prod.yml --dry-run

# Add custom stop words (single)
gonzo -f app.log --stop-words="debug"

# Add multiple stop words
gonzo -f app.log --stop-words="debug" --stop-words="info" --stop-words="warning"

# Stop words in comma-separated format
gonzo -f app.log --stop-words="debug,info,warning"

# Combination for troubleshooting
gonzo -f app.log --verbose --test-mode
```

**Test Mode Features:**

```bash
# Test mode provides CI/CD-friendly output
gonzo --test-mode -f build.log

# Output example:
# 📊 Test Mode Results:
# 
# Total lines: 3
# Unique words: 6
# Unique phrases: 12
# Attribute keys: 0
# 
# Test completed successfully - no crashes!
# Press 'q' to quit or wait 2 seconds for auto-exit.

# Exit code indicates success/failure
if gonzo --test-mode -f build.log; then
    echo "Log analysis passed"
else
    echo "Log analysis failed"
fi
```

**Stop Words Usage:**

```bash
# Filter common log terms
gonzo -f app.log --stop-words="log,message,error,warning,info,debug"

# Filter framework noise
gonzo -f app.log --stop-words="springframework,hibernate,slf4j"

# Filter HTTP terms from web logs
gonzo -f access.log --stop-words="GET,POST,HTTP,status"

# Combine with other options
gonzo -f app.log --follow --stop-words="debug,trace" --ai-model="gpt-4"
```

**Use Cases:**

{% tabs %}
{% tab title="CI/CD Integration" %}

```bash
# Non-interactive mode for automation
build-command 2>&1 | gonzo --test-mode

# Exit code based analysis
gonzo -f build.log --test-mode
if [ $? -ne 0 ]; then
    echo "Build analysis found issues"
fi
```

{% endtab %}

{% tab title="Configuration Validation" %}

```bash
# Validate config file syntax
gonzo --config myconfig.yml --dry-run

# Check what settings would be used
gonzo --config myconfig.yml --show-config

# Debug configuration loading
gonzo --config myconfig.yml --verbose
```

{% endtab %}

{% tab title="Development Testing" %}

```bash
# Test with sample data
echo '{"level":"error","message":"test"}' | gonzo --test-mode

# Verbose output for debugging
gonzo -f test.log --verbose

# Profile performance
time gonzo -f large.log --test-mode
```

{% endtab %}
{% endtabs %}

### Complete Flag Reference Table

#### All Flags Alphabetically

| Flag                | Short | Type     | Default | Description                   |
| ------------------- | ----- | -------- | ------- | ----------------------------- |
| `--ai-model`        |       | string   | auto    | AI model for analysis         |
| `--config`          |       | string   |         | Configuration file path       |
| `--dry-run`         |       | boolean  | false   | Show config without running   |
| `--file`            | `-f`  | string   |         | File or glob pattern to read  |
| `--follow`          |       | boolean  | false   | Follow file like `tail -f`    |
| `--help`            | `-h`  | boolean  | false   | Show help message             |
| `--log-buffer`      | `-b`  | int      | 1000    | Maximum log entries to keep   |
| `--memory-size`     | `-m`  | int      | 10000   | Maximum frequency entries     |
| `--no-color`        |       | boolean  | false   | Disable color output          |
| `--otlp-enabled`    |       | boolean  | false   | Enable OTLP receiver          |
| `--otlp-grpc-port`  |       | int      | 4317    | OTLP gRPC port                |
| `--otlp-http-port`  |       | int      | 4318    | OTLP HTTP port                |
| `--quiet`           |       | boolean  | false   | Suppress non-essential output |
| `--show-config`     |       | boolean  | false   | Display current configuration |
| `--test-mode`       | `-t`  | boolean  | false   | Run without TTY               |
| `--update-interval` | `-u`  | duration | 1s      | Dashboard update interval     |
| `--verbose`         |       | boolean  | false   | Enable verbose output         |
| `--version`         | `-v`  | boolean  | false   | Print version information     |

### Common Command Patterns

#### Development Workflows

```bash
# Basic development monitoring
gonzo -f logs/app.log --follow

# Multi-service development
gonzo -f api.log -f db.log -f cache.log --follow

# With AI for debugging
gonzo -f debug.log --follow --ai-model="gpt-3.5-turbo"

# Fast iteration
gonzo -f logs/*.log --follow --update-interval=1s
```

#### Production Monitoring

```bash
# Single service monitoring
gonzo -f /var/log/app.log --follow --log-buffer=10000

# Multi-service monitoring
gonzo -f "/var/log/app/*.log" --follow \
      --log-buffer=10000 \
      --update-interval=5s

# With premium AI for incidents
gonzo -f /var/log/app.log --follow --ai-model="gpt-4"

# High-availability setup
gonzo -f "/var/log/*.log" --follow \
      --log-buffer=20000 \
      --memory-size=50000 \
      --update-interval=10s
```

#### Analysis and Investigation

```bash
# Analyze archived logs
gonzo -f application.log.1

# Multiple archived files
gonzo -f app.log.* 

# With AI analysis
gonzo -f incident-logs.log --ai-model="gpt-4"

# Performance analysis
gonzo -f app.log --log-buffer=20000
```

#### CI/CD Integration

```bash
# Automated build analysis
build-command 2>&1 | gonzo --test-mode --ai-model="gpt-3.5-turbo"

# Test result analysis
gonzo -f test-results.log --test-mode

# With configuration file
gonzo --config ci-config.yml --test-mode

# Exit on errors
gonzo -f build.log --test-mode || exit 1
```

### Flag Combination Examples

#### Performance Optimization

```bash
# High-volume logs
gonzo -f busy.log --follow \
      --log-buffer=20000 \
      --memory-size=100000 \
      --update-interval=10s

# Low-resource systems
gonzo -f app.log --follow \
      --log-buffer=500 \
      --memory-size=2000 \
      --update-interval=5s

# Balanced setup
gonzo -f app.log --follow \
      --log-buffer=5000 \
      --memory-size=15000 \
      --update-interval=2s
```

#### AI Configuration

```bash
# Cost-optimized development
gonzo -f debug.log --follow --ai-model="gpt-3.5-turbo"

# Production quality analysis
gonzo -f incident.log --ai-model="gpt-4"

# Local AI for privacy
export OPENAI_API_BASE="http://localhost:11434"
gonzo -f sensitive.log --follow --ai-model="llama3"

# No AI (disabled)
unset OPENAI_API_KEY
gonzo -f app.log --follow
```

#### Multi-Source Analysis

```bash
# Application + infrastructure
gonzo -f app.log -f nginx.log -f postgres.log --follow

# Glob patterns + specific files
gonzo -f "/var/log/app-*.log" -f /var/log/critical.log --follow

# OTLP + file backup
gonzo --otlp-enabled -f backup.log --follow

# Multiple sources with custom config
gonzo -f api.log -f db.log \
      --follow \
      --config multi-source.yml
```

### Environment Variables

#### Configuration via Environment

Many flags can be set via environment variables:

```bash
# File configuration
export GONZO_FILES="/var/log/app.log:/var/log/nginx.log"
export GONZO_FOLLOW=true

# Performance settings
export GONZO_UPDATE_INTERVAL=2s
export GONZO_LOG_BUFFER=5000
export GONZO_MEMORY_SIZE=15000

# AI configuration
export GONZO_AI_MODEL="gpt-4"
export OPENAI_API_KEY="sk-your-key"
export OPENAI_API_BASE="https://api.openai.com/v1"

# Display options
export NO_COLOR=1               # Disable colors
export GONZO_TEST_MODE=true    # Enable test mode

# Then run without flags
gonzo
```

**Priority Order:**

1. Command-line flags (highest)
2. Environment variables
3. Configuration file
4. Built-in defaults (lowest)

### Shell Completion

#### Enable Autocomplete

```bash
# Bash
source <(gonzo completion bash)
echo 'source <(gonzo completion bash)' >> ~/.bashrc

# Zsh
source <(gonzo completion zsh)
echo 'source <(gonzo completion zsh)' >> ~/.zshrc

# Fish
gonzo completion fish | source
gonzo completion fish > ~/.config/fish/completions/gonzo.fish

# PowerShell
gonzo completion powershell | Out-String | Invoke-Expression
```

**Benefits:**

* Tab completion for flags
* Completion for flag values
* File path completion
* Command completion

### Troubleshooting CLI Issues

#### Common Problems

**Flag not recognized:**

```bash
# Check flag spelling
gonzo --help | grep flag-name

# Ensure no extra dashes
gonzo --log-buffer=5000     # Correct
gonzo ---log-buffer=5000    # Wrong (three dashes)

# Check flag format
gonzo --log-buffer 5000     # Correct (space)
gonzo --log-buffer=5000     # Correct (equals)
```

**Value not accepted:**

```bash
# Duration format
--update-interval=2s        # Correct
--update-interval=2         # Wrong (no unit)

# Glob patterns must be quoted
gonzo -f "/var/log/*.log"   # Correct
gonzo -f /var/log/*.log     # Wrong (shell expands)

# Boolean flags
--follow                    # Correct (true)
--follow=true              # Also correct
--follow true              # Wrong (no equals)
```

**Configuration conflicts:**

```bash
# CLI flags override config file
# If config has: log-buffer: 2000
# And you run: gonzo --log-buffer=5000
# Result: Uses 5000 (CLI wins)

# Check what's actually being used
gonzo --show-config
```

### Quick Reference Card

#### Most Common Commands

```bash
# Basic file analysis
gonzo -f app.log

# Real-time monitoring
gonzo -f app.log --follow

# Multiple files
gonzo -f "*.log" --follow

# With AI
gonzo -f app.log --follow --ai-model="gpt-4"

# High performance
gonzo -f busy.log --follow --log-buffer=20000 --update-interval=10s

# Using config
gonzo --config prod.yml

# OTLP receiver
gonzo --otlp-enabled

# CI/CD mode
build-cmd | gonzo --test-mode
```

#### Essential Flags

```bash
-f, --file          # Specify log file
    --follow        # Real-time following
-b, --log-buffer    # History buffer size
-u, --update-interval  # Refresh rate
    --ai-model      # AI model selection
    --config        # Config file path
-h, --help          # Show help
-v, --version       # Show version
```

### What's Next?

Now that you know all CLI flags, explore related topics:

* **Configuration File** - Persistent settings via YAML
* **Advanced Configuration** - Complex setups and tuning
* **User Guide** - Master the Gonzo interface

Or start using flags effectively:

```bash
# Create aliases for common patterns
alias gonzo-dev='gonzo --follow --ai-model="gpt-3.5-turbo"'
alias gonzo-prod='gonzo --follow --log-buffer=10000 --ai-model="gpt-4"'
alias gonzo-test='gonzo --test-mode'

# Use them
gonzo-dev -f logs/app.log
gonzo-prod -f /var/log/app.log
```

***

**Master CLI flags for quick, powerful log analysis!** ⚡ From simple file analysis to sophisticated multi-source monitoring, command-line flags give you precise control over every Gonzo session.


# Integration Examples

Learn how to integrate Gonzo with popular tools, platforms, and workflows. From container orchestration to cloud log services, these guides show you how to use Gonzo in real-world production environments.

### Why Integration Matters

Gonzo's power multiplies when integrated into your existing toolchain:

* **🐳 Container Ecosystems** - Seamless log analysis from Docker, Kubernetes, and container platforms
* **☁️ Cloud Services** - Direct integration with AWS CloudWatch, Azure Monitor, and GCP Logging
* **📊 Log Storage Systems** - High-performance analysis of VictoriaLogs, Elasticsearch, and time-series databases
* **🔧 Development Tools** - Integration with CI/CD, monitoring systems, and alerting platforms
* **🖥️ System Administration** - Enhanced workflows for traditional system log analysis

{% hint style="success" %}
**Real-World Focus:** These guides are based on actual production deployments and common use cases from the Gonzo community.
{% endhint %}

### Integration Overview

Gonzo integrates with your infrastructure in three main ways:

| Integration Type  | Method           | Best For                        | Examples                      |
| ----------------- | ---------------- | ------------------------------- | ----------------------------- |
| **Direct Piping** | Stdin processing | Real-time streaming             | Docker logs, kubectl, stern   |
| **File Analysis** | File reading     | Archived logs, batch processing | CloudWatch exports, log files |
| **OTLP Receiver** | Network endpoint | OpenTelemetry integration       | Instrumented applications     |

### Featured Integrations

#### Container Orchestration

**Kubernetes Integration**

Analyze logs from Kubernetes clusters with powerful tooling integration:

* **kubectl logs** - Direct pod log analysis
* **Stern integration** - Multi-pod log streaming with Gonzo
* **Container insights** - Understanding deployment and pod logs
* **Namespace-wide analysis** - Cluster-level log investigation

**Time to complete:** 15-20 minutes\
**Prerequisites:** Kubernetes cluster access, kubectl installed

***

#### Cloud Log Services

**AWS CloudWatch Integration**

Stream and analyze logs from AWS CloudWatch:

* **CloudWatch Logs streaming** - Real-time log analysis from AWS
* **AWS CLI integration** - Efficient log retrieval and processing
* **Log group analysis** - Multi-service AWS monitoring
* **Cost optimization** - Efficient CloudWatch log querying

**Time to complete:** 20-25 minutes\
**Prerequisites:** AWS account, AWS CLI configured

***

#### High-Performance Log Storage

**VictoriaLogs Integration**

Analyze logs from VictoriaLogs time-series database:

* **VictoriaLogs querying** - High-performance log retrieval
* **Time-series analysis** - Historical log investigation
* **Query optimization** - Efficient VictoriaLogs integration
* **Large-scale deployment** - Production-grade log analysis

**Time to complete:** 20-25 minutes\
**Prerequisites:** VictoriaLogs installation or access

***

#### Container Platforms

**Docker Integration**

Seamless integration with Docker container logs:

* **Docker logs command** - Container log analysis
* **Docker Compose** - Multi-container log aggregation
* **Container lifecycle** - Monitoring container events
* **Development workflows** - Local container debugging

**Time to complete:** 15-20 minutes\
**Prerequisites:** Docker installed

***

#### System Administration

**System Log Analysis**

Enhanced workflows for traditional system administration:

* **Syslog integration** - System log monitoring
* **Multiple log sources** - Unified system analysis
* **Security monitoring** - Auth log analysis
* **Performance debugging** - System health investigation

**Time to complete:** 15-20 minutes\
**Prerequisites:** Linux system access

***

#### Development Workflows

**Development Integration**

Integrate Gonzo into development workflows:

* **IDE integration** - Log analysis during development
* **Local debugging** - Application log investigation
* **Test result analysis** - CI/CD test log processing
* **Hot reload monitoring** - Watch mode integration

**Time to complete:** 10-15 minutes\
**Prerequisites:** Development environment

### Integration Patterns

#### Streaming Pattern (Recommended)

**Real-time log analysis through piping:**

```bash
# Kubernetes with kubectl
kubectl logs -f deployment/my-app | gonzo

# Docker containers
docker logs -f my-container 2>&1 | gonzo

# System logs
tail -f /var/log/syslog | gonzo

# Cloud services
aws logs tail /aws/lambda/my-function --follow | gonzo
```

**Benefits:**

* ✅ Real-time analysis as logs are generated
* ✅ No intermediate storage required
* ✅ Works with any tool that outputs to stdout
* ✅ Minimal resource overhead

#### File Analysis Pattern

**Batch processing of log files:**

```bash
# Local files
gonzo -f application.log

# Cloud exports
aws logs tail /aws/lambda/function --since 1h > export.log
gonzo -f export.log

# Archived logs
gonzo -f /var/log/app.log.1

# Multiple sources
gonzo -f app.log -f nginx.log -f db.log
```

**Benefits:**

* ✅ Works with archived logs
* ✅ Repeatable analysis
* ✅ Can combine multiple sources
* ✅ Good for historical investigation

#### OTLP Integration Pattern

**OpenTelemetry Protocol receiver:**

```bash
# Start Gonzo as OTLP receiver
gonzo --otlp-enabled

# Configure your applications to send logs to:
# gRPC: localhost:4317
# HTTP: http://localhost:4318/v1/logs

# Monitor real-time + backup to file
gonzo --otlp-enabled -f backup.log --follow
```

**Benefits:**

* ✅ Native OpenTelemetry integration
* ✅ Structured log data preserved
* ✅ Multiple applications simultaneously
* ✅ Standard protocol

### Quick Start by Use Case

#### "I use Kubernetes"

```bash
# Start here: Kubernetes Integration
# 1. Install stern (optional but recommended)
brew install stern

# 2. Stream logs with stern + Gonzo
stern backend | gonzo --ai-model="gpt-4"

# 3. Or use kubectl directly
kubectl logs -f -l app=backend | gonzo
```

→ **Full Kubernetes Guide**

#### "I use AWS"

```bash
# Start here: CloudWatch Integration
# 1. Install AWS CLI
# 2. Configure credentials

# 3. Stream CloudWatch logs
aws logs tail /aws/lambda/my-function --follow | gonzo

# 4. Or analyze log groups
aws logs tail my-log-group --since 1h | gonzo --ai-model="gpt-4"
```

→ **Full CloudWatch Guide**

#### "I use Docker"

```bash
# Start here: Container Integration
# 1. Start your containers

# 2. Monitor container logs
docker logs -f my-container 2>&1 | gonzo

# 3. Or Docker Compose services
docker-compose logs -f | gonzo --ai-model="gpt-3.5-turbo"
```

→ **Full Docker Guide**

#### "I have traditional servers"

```bash
# Start here: System Administration
# 1. Identify your log files

# 2. Monitor system logs
sudo tail -f /var/log/syslog | gonzo

# 3. Or analyze multiple sources
gonzo -f /var/log/syslog -f /var/log/auth.log --follow
```

→ **Full System Admin Guide**

### Integration Best Practices

#### 🎯 **Choose the Right Integration Method**

1. **Real-time monitoring** → Use streaming (piping)
2. **Historical analysis** → Use file analysis
3. **OpenTelemetry apps** → Use OTLP receiver
4. **Mixed sources** → Combine multiple methods

#### ⚡ **Performance Optimization**

```bash
# For high-volume streams, pre-filter
kubectl logs -f deployment/app | grep -E "(ERROR|WARN)" | gonzo

# Adjust buffer sizes for volume
docker logs -f container | gonzo --log-buffer=20000

# Use appropriate update intervals
tail -f /var/log/busy.log | gonzo --update-interval=5s
```

#### 🔐 **Security Considerations**

```bash
# Use appropriate authentication
export AWS_PROFILE=production
aws logs tail /aws/lambda/function | gonzo

# Handle sensitive data
# Use local AI for sensitive logs
export OPENAI_API_BASE="http://localhost:11434"
kubectl logs sensitive-app | gonzo --ai-model="llama3"

# Respect access controls
# Use proper IAM roles, RBAC, etc.
```

#### 📝 **Documentation and Sharing**

```bash
# Document your integration commands
cat > analyze-prod-logs.sh << 'EOF'
#!/bin/bash
# Production log analysis with Gonzo
# Usage: ./analyze-prod-logs.sh

kubectl logs -f -l app=backend,env=prod | \
gonzo --config prod.yml --ai-model="gpt-4"
EOF

chmod +x analyze-prod-logs.sh

# Share with team
git add analyze-prod-logs.sh
git commit -m "Add production log analysis script"
```

### Common Integration Patterns

#### Multi-Source Aggregation

```bash
# Combine multiple log sources
(kubectl logs -f deploy/api & \
 kubectl logs -f deploy/worker & \
 kubectl logs -f deploy/scheduler) | gonzo

# Multiple containers
docker logs -f api 2>&1 & \
docker logs -f db 2>&1 & \
docker logs -f cache 2>&1 | gonzo

# Multiple files with follow
gonzo -f /var/log/app/*.log --follow
```

#### Filtered Streaming

```bash
# Pre-filter for performance
kubectl logs -f deployment/app | \
grep -v DEBUG | \
gonzo --log-buffer=10000

# Filter by severity
stern backend | \
grep -E "(ERROR|WARN|FATAL)" | \
gonzo --ai-model="gpt-4"

# Combine filters
aws logs tail /aws/lambda/fn --follow | \
jq -r 'select(.level=="error") | .message' | \
gonzo
```

#### Scheduled Analysis

```bash
# Cron job for daily analysis
0 2 * * * /usr/local/bin/analyze-logs.sh

# analyze-logs.sh
#!/bin/bash
aws logs tail /aws/lambda/function \
    --since 24h \
    --format short | \
gonzo --config daily-analysis.yml \
      --ai-model="gpt-4" > /var/log/daily-analysis.txt
```

### Troubleshooting Integrations

#### Connection Issues

```bash
# Test connectivity first
kubectl cluster-info
aws sts get-caller-identity
docker ps

# Verify tool output
kubectl logs pod-name | head -10
aws logs tail log-group --since 5m | head -10

# Then add Gonzo
kubectl logs pod-name | gonzo
```

#### Performance Issues

```bash
# If Gonzo is slow with integration:

# 1. Check log volume
kubectl logs pod-name | wc -l

# 2. Pre-filter if needed
kubectl logs pod-name | grep ERROR | gonzo

# 3. Adjust Gonzo settings
kubectl logs pod-name | gonzo --update-interval=5s --log-buffer=2000
```

#### Format Issues

```bash
# If logs aren't parsing correctly:

# 1. Check log format
kubectl logs pod-name | head -5

# 2. Test format detection
echo '{"test":"log"}' | gonzo

# 3. Ensure proper JSON/logfmt
# Gonzo auto-detects but prefers structured logs
```

### What's Next?

Choose the integration guide that matches your infrastructure:

* **Kubernetes Integration** - K8s clusters with kubectl and stern
* **AWS CloudWatch** - AWS cloud log services
* **VictoriaLogs** - High-performance log storage
* **Docker Containers** - Container log analysis
* **System Administration** - Traditional system logs
* **Development Workflows** - IDE and development integration

Or explore advanced topics:

* **Configuration** - Optimize for your integration
* **Advanced Features** - Powerful analysis techniques
* **Troubleshooting** - Integration-specific issues

***

**Integrate Gonzo into your existing workflows for powerful log analysis anywhere!** 🚀 From cloud platforms to container orchestration, Gonzo adapts to your infrastructure.


# Vercel Logs

Stream Vercel deployment logs into Gonzo for real-time terminal analysis

Stream Vercel deployment logs into Gonzo for real-time terminal analysis — with your app-level fields (service, level, message) unwrapped from Vercel's double-encoded JSON and merged with platform metadata (domain, route, status code).

### How It Works

The Vercel CLI's `-j` flag outputs each log line as JSON, but the actual app log is buried inside the `message` field as a stringified JSON object with a `[function-name]` prefix (e.g. `[orders]` for `/api/orders`). A `jq` normalizer in the pipe strips the prefix, parses the inner JSON, and merges it with the Vercel envelope — so Gonzo sees a flat, clean log line with all fields at the top level.

When you specify a deployment URL, Vercel auto-follows (streams in real time) by default.

### Quick Start

#### Prerequisites

* Gonzo installed
* jq installed (`brew install jq`)
* Vercel CLI installed and authenticated (`npm i -g vercel && vercel login`)
* A Vercel deployment receiving traffic

#### Stream Logs

```bash
vercel logs <deployment_url_or_id> -j | jq --unbuffered '
  (.message | sub("^\\[.*?\\] "; "") | fromjson) + {source, requestPath, domain, requestMethod, responseStatusCode}
' | gonzo
```

Replace `<deployment_url_or_id>` with your deployment URL or ID. Find this in the Vercel dashboard or via `vercel ls`.

> **⚠️ `--unbuffered` on jq is mandatory.** Without it, jq buffers output and the pipe appears to stall. This is the #1 setup issue.

### What Gets Unwrapped

The normalizer produces a flat JSON line combining fields from two layers:

| Source                  | Fields                                                                   | Description                                 |
| ----------------------- | ------------------------------------------------------------------------ | ------------------------------------------- |
| Your app (inner JSON)   | `ts`, `level`, `service`, `msg`, `reqId`, `value`                        | The actual structured log your code emitted |
| Vercel envelope (outer) | `source`, `requestPath`, `domain`, `requestMethod`, `responseStatusCode` | Platform metadata from the edge             |

Gonzo sees the app-level `level` field, not Vercel's outer classification — so severity filtering reflects what your code actually logged.

### Usage Patterns

#### Batch fetch (no streaming):

```bash
vercel logs <deployment_url_or_id> -j --no-follow | jq --unbuffered '
  (.message | sub("^\\[.*?\\] "; "") | fromjson) + {source, requestPath, domain, requestMethod, responseStatusCode}
' | gonzo
```

#### Write to file for external analysis:

```bash
vercel logs <deployment_url_or_id> -j --no-follow | jq --unbuffered '
  (.message | sub("^\\[.*?\\] "; "") | fromjson) + {source, requestPath, domain, requestMethod, responseStatusCode}
' > /tmp/vercel-logs.jsonl
```

#### With AI analysis:

```bash
export OPENAI_API_KEY="sk-your-key"
vercel logs <deployment_url_or_id> -j | jq --unbuffered '
  (.message | sub("^\\[.*?\\] "; "") | fromjson) + {source, requestPath, domain, requestMethod, responseStatusCode}
' | gonzo --ai-model="gpt-4"
```

#### Filter by branch:

```bash
vercel logs --follow -j -b main | jq --unbuffered '
  (.message | sub("^\\[.*?\\] "; "") | fromjson) + {source, requestPath, domain, requestMethod, responseStatusCode}
' | gonzo
```

### Filtering in Gonzo

Press `/` to filter. Useful patterns:

| Filter          | What you'll see                                 |
| --------------- | ----------------------------------------------- |
| `error`         | App-level errors (from the inner `level` field) |
| `payments`      | Logs from the payments service                  |
| `auth`          | Authentication-related logs                     |
| `/api/orders`   | Requests to a specific route                    |
| `edge-function` | Edge function logs only                         |
| `timeout`       | Timeout-related messages                        |

### The `[prefix]` Explained

Vercel prepends the API route name to the `message` field as a bracket prefix:

* `/api/noise` → `[noise] {...}`
* `/api/orders` → `[orders] {...}`
* `/api/auth/login` → `[auth/login] {...}`

The normalizer's `sub("^\\[.*?\\] "; "")` strips any `[...]` prefix automatically, regardless of the route name.

### Notes

* **The `-j` flag is required.** Without it, Vercel outputs plain text and the normalizer has nothing to parse.
* **No log drain required.** This uses the Vercel CLI directly, which is currently free on Hobby and Pro tiers. No Vercel-side configuration needed.
* **Vercel log retention is limited.** Runtime logs are retained for 1 hour (Hobby), 3 days (Pro/Enterprise). For longer retention, consider forwarding to Dstl8.
* **Non-function logs may not have the `[prefix] {json}` format.** Build logs or platform-level messages can appear in the stream without inner JSON. These will cause a `jq` parse error — they're safe to ignore.

### Troubleshooting

| Problem                         | Fix                                                                                                             |
| ------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| Pipe appears to stall           | Make sure `--unbuffered` is on the jq call                                                                      |
| No logs appearing               | Check you're authenticated (`vercel whoami`) and the deployment is receiving traffic                            |
| `vercel: command not found`     | Install the CLI: `npm i -g vercel`                                                                              |
| `jq: error - Could not parse`   | A log line doesn't have the expected `[prefix] {json}` format — likely a build or platform log. Safe to ignore. |
| Logs appear but no inner fields | Make sure you're using the `-j` flag                                                                            |
| Ctrl+C not killing the pipe     | Use `ctrl+\` (SIGQUIT) or `kill $(pgrep -f "vercel logs")` from another terminal                                |

Time to complete: 5 minutes | Prerequisites: Vercel CLI, `jq`, Gonzo installed | Full guide: `guides/VERCEL_USAGE_GUIDE.md`


# Supabase Logs

Stream logs from all 9 Supabase services

Stream logs from all 9 Supabase services into Gonzo for real-time terminal analysis — API gateway, Postgres, Auth, Storage, Realtime, Edge Functions, PostgREST, Supavisor, and function edge logs.

### How It Works

Supabase doesn't expose a streaming log API. The included poller script (`supabase-log-poller.sh`) polls the Management API's SQL-based log query endpoint, normalizes the deeply nested metadata from each service into flat JSONL, and pipes the result into Gonzo. One script covers all 9 sources.

### Quick Start

```bash
# Download the poller script
curl -fsSL https://raw.githubusercontent.com/control-theory/gonzo/main/scripts/supabase-log-poller.sh -o supabase-log-poller.sh
chmod +x supabase-log-poller.sh

# Set credentials
export SUPABASE_ACCESS_TOKEN="sbp_your_token"
export SUPABASE_PROJECT_REF="your_project_ref"

# Pipe into Gonzo
./supabase-log-poller.sh | gonzo
```

### Prerequisites

* Gonzo installed
* `jq` installed (`brew install jq`)
* A Supabase project (free tier works)

### Credentials

**Project Ref** — Found in your dashboard URL (`https://supabase.com/dashboard/project/<ref>`) or under Settings → General.

**Personal Access Token** — Generate at supabase.com/dashboard/account/tokens. Starts with `sbp_`.

### Log Sources

| Source               | Service              | What it captures                              |
| -------------------- | -------------------- | --------------------------------------------- |
| `edge_logs`          | `api-gateway`        | Every API request through the Cloudflare edge |
| `postgres_logs`      | `postgres`           | Queries, connections, errors, pgAudit         |
| `auth_logs`          | `gotrue`             | Sign-ups, logins, token ops, auth errors      |
| `storage_logs`       | `storage`            | Uploads, downloads, bucket operations         |
| `realtime_logs`      | `realtime`           | WebSocket connections, Phoenix events         |
| `function_logs`      | `edge-function/<id>` | Edge Function console output                  |
| `function_edge_logs` | `edge-function/<id>` | Edge Function network request/response        |
| `postgrest_logs`     | `postgrest`          | REST API server lifecycle                     |
| `supavisor_logs`     | `pooler`             | Connection pooler activity                    |

### Usage Patterns

Suppress poller status messages:

```bash
./supabase-log-poller.sh 2>/dev/null | gonzo
```

Write to file (supports auto-rotation at 100MB):

```bash
./supabase-log-poller.sh -o /tmp/supabase-logs/all.jsonl
gonzo -f /tmp/supabase-logs/all.jsonl --follow
```

Faster polling:

```bash
POLL_INTERVAL=10 ./supabase-log-poller.sh | gonzo
```

With AI analysis:

```bash
export OPENAI_API_KEY="sk-your-key"
./supabase-log-poller.sh 2>/dev/null | gonzo --ai-model="gpt-4"
```

### Filtering in Gonzo

Press `/` to filter. Useful patterns:

| Filter          | What you'll see       |
| --------------- | --------------------- |
| `edge_logs`     | API gateway requests  |
| `postgres_logs` | Database activity     |
| `auth_logs`     | Authentication events |
| `gotrue`        | Auth service by name  |
| `ERROR`         | Server errors (5xx)   |
| `WARN`          | Client errors (4xx)   |

### Rate Limits

The Management API allows 120 requests/min per project. The poller makes 9 requests per cycle. At the default 30s interval that's 18 req/min — well within limits. Don't set `POLL_INTERVAL` below 10s.

| POLL\_INTERVAL | Requests/min | Risk                |
| -------------- | ------------ | ------------------- |
| 30s (default)  | 18           | ✅ Safe              |
| 15s            | 36           | ✅ Safe              |
| 10s            | 54           | ⚠️ Use with caution |

### Log Propagation Delay

Supabase logs are ingested via Logflare and typically take 30–90 seconds to appear in the API. The poller's time window overlaps by 5 seconds to avoid gaps.

***

**Time to complete:** 10–15 minutes | **Prerequisites:** Supabase project, `jq`, Gonzo installed | **Full guide:** [`guides/SUPABASE_USAGE_GUIDE.md`](https://github.com/control-theory/gonzo/blob/main/guides/SUPABASE_USAGE_GUIDE.md)


# Railway Logs

Stream logs from Railway services into Gonzo with zero configuration.

Stream logs from Railway services into Gonzo with zero configuration. Railway's CLI outputs JSON over WebSocket. Gonzo auto-detects the format — no poller, no normalizer, no `jq` transforms.

### Quick Start

```bash
railway login
railway link
railway logs --json | gonzo
```

That's it. Works on all Railway plans (Trial, Hobby, Pro).

### Prerequisites

* Gonzo installed
* [Railway CLI](https://docs.railway.com/guides/cli) installed (`brew install railway`)
* A Railway project with at least one deployed service

### Log Types

| Log type       | CLI flag           | Gonzo compatible | What it captures                                 |
| -------------- | ------------------ | ---------------- | ------------------------------------------------ |
| **Deployment** | `--json` (default) | ✅                | App stdout/stderr                                |
| **Build**      | `--build --json`   | ✅                | Dependency installs, compilation, image creation |
| **HTTP**       | Dashboard only     | ❌                | Edge proxy request logs (not available via CLI)  |

### Usage Patterns

**Real-time streaming** (WebSocket, no rate limits):

```bash
railway logs --json | gonzo
```

**Fetch last N lines:**

```bash
railway logs --json --lines 100 | gonzo
```

**Time range:**

```bash
railway logs --json --since 1h | gonzo
```

**Build logs after a failed deploy:**

```bash
railway logs --build --json --lines 100 | gonzo
```

**Filter at source:**

```bash
railway logs --json --filter "@level:error" | gonzo
```

**Write to file:**

```bash
railway logs --json > /tmp/railway-logs.jsonl &
gonzo -f /tmp/railway-logs.jsonl --follow
```

**With local AI (logs never leave your machine):**

```bash
export OPENAI_API_KEY="ollama"
export OPENAI_API_BASE="http://localhost:11434"
railway logs --json | gonzo
```

### Multi-Service Projects

Stream from a specific service:

```bash
railway logs --json --service <service-id> | gonzo
```

### Rate Limits

**Streaming** (`--json | gonzo`) uses WebSocket — **not rate limited**. This is the recommended mode.

**Fetch mode** (`--lines`, `--since`) uses the GraphQL API:

| Plan       | Requests/hour |
| ---------- | ------------- |
| Free/Trial | 100           |
| Hobby      | 1,000         |
| Pro        | 10,000        |

**Platform cap:** 500 log lines/second per replica. Excess is silently dropped. Use minified JSON (not pretty-printed) to stay under the limit.

### Structured Logging Tips

If your app emits structured JSON to stdout, Railway preserves it as-is. Non-JSON is wrapped in `{"message":"...","level":"..."}`. Stderr output is auto-tagged as `level: "error"` — a common gotcha for Python's `logging` library which defaults to stderr.

**Time to complete:** 5 minutes **Prerequisites:** Railway CLI, Gonzo installed **Full guide:** [`guides/RAILWAY_USAGE_GUIDE.md`](https://github.com/control-theory/gonzo/blob/main/guides/RAILWAY_USAGE_GUIDE.md)


# Cloudflare Logs

Stream logs from Cloudflare Workers into Gonzo for real-time analysis, filtering, and AI-powered insights.

Stream Worker invocation traces into Gonzo with a `jq` normalizer. Cloudflare's `wrangler tail` streams pretty-printed JSON envelopes over WebSocket — one per invocation, containing all `console.log` calls and exceptions. The normalizer flattens these into per-line JSONL that Gonzo can parse.

#### Quick Start

```bash
wrangler tail --format json \
  | jq --unbuffered -c '
    . as $inv |
    (.logs[] | {
      timestamp: .timestamp,
      level: .level,
      message: (.message | map(if type == "string" then . else tostring end) | join(" ")),
      script: $inv.scriptName,
      outcome: $inv.outcome,
      url: $inv.event.request.url,
      method: $inv.event.request.method,
      status: ($inv.event.response.status // null),
      colo: $inv.event.request.cf.colo
    }),
    (.exceptions[]? | {
      timestamp: .timestamp,
      level: "error",
      message: (.name + ": " + .message),
      stack: .stack,
      script: $inv.scriptName,
      outcome: $inv.outcome,
      url: $inv.event.request.url,
      method: $inv.event.request.method,
      status: ($inv.event.response.status // null)
    })
  ' \
  | gonzo
```

The `--unbuffered` flag on `jq` is required — without it, output buffers and logs stall in the pipe.

#### Prerequisites

* Gonzo installed
* [Wrangler](https://developers.cloudflare.com/workers/wrangler/) installed (`npm install -g wrangler`)
* `jq` installed (`brew install jq`)
* A Cloudflare account with at least one deployed Worker

#### What's Visible

| Component                     | In tail? | Notes                                     |
| ----------------------------- | -------- | ----------------------------------------- |
| `console.log/warn/error`      | ✅ Yes    | All levels: log, warn, error, debug, info |
| Uncaught exceptions           | ✅ Yes    | With stack traces                         |
| Request/response metadata     | ✅ Yes    | URL, method, status, colo                 |
| Cron trigger invocations      | ✅ Yes    | `url`/`method`/`status` will be null      |
| D1 / KV / R2 / AI / Vectorize | ❌ No     | Instrument manually with `console.log`    |

#### Usage Patterns

**Real-time streaming** (WebSocket, default):

```bash
wrangler tail --format json | jq --unbuffered -c '<normalizer>' | gonzo
```

**Tail a specific Worker by name:**

```bash
wrangler tail my-worker --format json | jq --unbuffered -c '<normalizer>' | gonzo
```

**Filter by status:**

```bash
wrangler tail --format json --status error | jq --unbuffered -c '<normalizer>' | gonzo
```

**Filter by HTTP method:**

```bash
wrangler tail --format json --method GET | jq --unbuffered -c '<normalizer>' | gonzo
```

**Filter by search string:**

```bash
wrangler tail --format json --search "TypeError" | jq --unbuffered -c '<normalizer>' | gonzo
```

**Sample high-traffic Workers:**

```bash
wrangler tail --format json --sampling-rate 0.1 | jq --unbuffered -c '<normalizer>' | gonzo
```

**Capture to file for replay:**

```bash
wrangler tail --format json | jq --unbuffered -c '<normalizer>' > /tmp/cf-logs.jsonl &
gonzo -f /tmp/cf-logs.jsonl --follow
```

**With local AI (logs never leave your machine):**

```bash
export OPENAI_API_KEY="ollama"
export OPENAI_API_BASE="http://localhost:11434"
wrangler tail --format json | jq --unbuffered -c '<normalizer>' | gonzo
```

#### Pages Functions

Pages Functions use the same Worker runtime and produce identical tail output. The normalizer works without modification.

```bash
# Tail latest production deployment
wrangler pages deployment tail --project-name my-site --environment production --format json \
  | jq --unbuffered -c '<normalizer>' \
  | gonzo
```

When piping (non-interactive mode), the `--environment` flag or a deployment ID is required. Static asset requests don't trigger Functions and won't appear in the tail.

#### Rate Limits and Sampling

**Streaming** (`wrangler tail`) uses WebSocket. For high-traffic Workers, Cloudflare may auto-sample, dropping some invocation traces. Use `--sampling-rate` (0.0–1.0) to proactively reduce volume.

**Concurrent sessions:** Maximum 10 tail sessions per Worker.

There is no fetch mode with `--lines` or `--since`. `wrangler tail` is streaming only. For historical queries, use [Workers Logs](https://developers.cloudflare.com/workers/observability/logs/workers-logs/) in the Cloudflare dashboard.

#### Structured Logging Tips

Emit structured JSON via `console.log` for the best Gonzo experience. Objects passed directly also work — the normalizer stringifies them.

```javascript
// Explicit stringify — cleanest message field
console.log(JSON.stringify({
  message: "User signup completed",
  level: "info",
  userId: 123,
  duration_ms: 45
}));

// Direct object — faster to write
console.log({ event: "db_write", table: "users", rows: 1 });
```

#### Troubleshooting

| Symptom                              | Cause & fix                                                                                                 |
| ------------------------------------ | ----------------------------------------------------------------------------------------------------------- |
| Logs not appearing                   | Missing `--unbuffered` on `jq`. Without it, jq buffers output and logs stall.                               |
| "Could not create tail"              | Hit the 10 concurrent tail session limit. Close other `wrangler tail` sessions or dashboard live log views. |
| Cron logs show null fields           | Expected. Cron triggers have no HTTP request — `url`, `method`, `status`, `colo` are null.                  |
| D1/KV operations missing             | Binding operations don't produce tail events. Add `console.log` around binding calls.                       |
| Pretty-printed JSON instead of JSONL | Don't pipe raw `wrangler tail` output to Gonzo. The `jq` normalizer compacts it.                            |
| Out-of-order logs under concurrency  | Workers execute at edge locations globally. Concurrent requests may arrive out of timestamp order.          |

***

**Time to complete:** 5 minutes **Prerequisites:** Wrangler, jq, Gonzo installed **Full guide:** [`guides/CLOUDFLARE_USAGE_GUIDE.md`](https://github.com/control-theory/gonzo/blob/main/guides/CLOUDFLARE_USAGE_GUIDE.md)


# Netlify Logs

Stream serverless function logs from Netlify into Gonzo for real-time analysis, filtering, and AI-powered insights.

Stream function logs into Gonzo with a lightweight `jq` normalizer. Netlify's CLI doesn't have a `--json` flag for function logs — it outputs `LEVEL MESSAGE` text over WebSocket. The normalizer splits the level, promotes any embedded JSON fields, and drops blank lines so Gonzo receives clean JSONL.

#### Quick Start

```bash
netlify login
netlify link
netlify logs:function <function-name> \
  | jq --unbuffered -R '
    select(length > 0) |
    (index(" ")) as $i |
    if $i then
      {level: .[:$i] | ascii_downcase, message: .[($i+1):]}
    else
      {level: "info", message: .}
    end |
    (.message | fromjson? // null) as $json |
    if $json then . + $json else . end |
    select(.message | length > 0)
  ' \
  | gonzo
```

Replace `<function-name>` with your function (e.g. `hello`, `submit-form`). The `--unbuffered` flag on `jq` is required — without it, output buffers and logs stall.

#### Prerequisites

* Gonzo installed
* [Netlify CLI](https://cli.netlify.com/) installed (`npm install -g netlify-cli`)
* `jq` installed (`brew install jq`)
* A Netlify project with at least one deployed serverless function

#### Log Types

| Log type           | CLI access             | Gonzo compatible        | What it captures                                              |
| ------------------ | ---------------------- | ----------------------- | ------------------------------------------------------------- |
| **Function logs**  | `logs:function <name>` | ✅ Yes (with normalizer) | `console.log/warn/error` output + platform invocation metrics |
| **Deploy logs**    | `logs:deploy`          | ⚠️ Limited (plain text) | Build output during git-triggered deploys                     |
| **Edge Functions** | Dashboard only         | ❌ Not via CLI           | Deno-based edge function console output                       |
| **Traffic logs**   | Enterprise Log Drains  | ❌ Not via CLI           | CDN request logs: method, path, status, duration              |

#### Usage Patterns

**Stream a specific function:**

```bash
netlify logs:function hello | jq --unbuffered -R '<normalizer>' | gonzo
```

**Filter by level at the source:**

```bash
netlify logs:function hello --level warn error | jq --unbuffered -R '<normalizer>' | gonzo
```

**Watch a deploy in real time** (plain text, no structured fields):

```bash
netlify logs:deploy | gonzo
```

**Capture to file for replay:**

```bash
netlify logs:function hello | jq --unbuffered -R '<normalizer>' > /tmp/netlify-logs.jsonl &
gonzo -f /tmp/netlify-logs.jsonl --follow
```

**With local AI (logs never leave your machine):**

```bash
export OPENAI_API_KEY="ollama"
export OPENAI_API_BASE="http://localhost:11434"
netlify logs:function hello | jq --unbuffered -R '<normalizer>' | gonzo
```

#### Multiple Functions

The Netlify CLI streams one function at a time — there is no "stream all" mode. To monitor multiple functions, run separate terminal sessions each piping a different function into Gonzo.

#### Platform Latency

Function logs typically appear in the CLI stream **5–15 seconds** after execution. This delay is inherent to Netlify's log delivery and is not affected by the Gonzo pipe or the `jq` normalizer.

#### Structured Logging Tips

Netlify does not add timestamps to function log output. For the best Gonzo experience, emit structured JSON with at least `message`, `level`, and a timestamp:

```javascript
console.log(JSON.stringify({
  message: "User signup completed",
  level: "info",
  ts: new Date().toISOString(),
  userId: 123
}));
```

The normalizer automatically promotes these fields to the top level, giving Gonzo access to timestamps and custom fields for filtering.

Avoid pretty-printed JSON — `JSON.stringify(obj, null, 2)` spans multiple lines and each line becomes a separate log entry. Always use minified: `JSON.stringify(obj)`.

#### Troubleshooting

| Symptom                               | Cause & fix                                                                                                     |
| ------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| "No site linked"                      | Run `netlify link` to connect your terminal session to a project.                                               |
| Function returns 404                  | Verify with `netlify functions:list`. Check `[functions]` directory in `netlify.toml`.                          |
| Logs appear empty                     | Function may not have been invoked. Trigger the endpoint and wait 5–15s for delivery.                           |
| `jq` hangs / no output                | Missing `--unbuffered` on `jq`. Without it, output buffers when writing to a pipe.                              |
| Blank JSON lines in output            | Ensure the full normalizer with `select(length > 0)` and `select(.message \| length > 0)` is included.          |
| `logs:deploy` says "No active builds" | Deploy logs only attach to remote builds (git push / Netlify UI). CLI deploys build locally — no remote stream. |

***

**Time to complete:** 5 minutes **Prerequisites:** Netlify CLI, jq, Gonzo installed **Full guide:** [`guides/NETLIFY_USAGE_GUIDE.md`](https://github.com/control-theory/gonzo/blob/main/guides/NETLIFY_USAGE_GUIDE.md)


# Render Logs

Stream logs from Render services into Gonzo.

Stream logs from Render services into Gonzo. Render's CLI streams over WebSocket; a lightweight `jq` + `sed` pipe flattens label metadata and strips ANSI codes.

### Quick Start

```bash
render logs -r <service-id> -o json --tail \
  | jq --unbuffered -c '{timestamp: .timestamp, message: .message} + ([.labels[] | {(.name): .value}] | add)' \
  | sed -u 's/\\u001b\[[0-9;]*m//g; s/\\u001b(B//g' \
  | gonzo
```

### Prerequisites

* Gonzo installed
* [Render CLI](https://render.com/docs/cli) installed (`brew install render`)
* `jq` installed (`brew install jq`)

### Setup

```bash
# Authenticate
render login

# Find your service ID (starts with srv-)
render services -o json | jq '.[].service | {id, name}'
```

### Why the Pipe?

Render nests metadata in a `labels` array rather than top-level fields. The `jq` transform flattens all labels dynamically — if Render adds new labels (e.g. `method`, `path`, `status_code` on Professional plans), they appear automatically. The `sed -u` strips ANSI color codes that Render injects into build/deploy messages. The `-u` flag disables sed's output buffering to prevent log stalling.

### Log Phases

Build, deploy, and runtime logs come through a single stream:

| Phase       | How to identify                                     | Example                               |
| ----------- | --------------------------------------------------- | ------------------------------------- |
| **Build**   | Has `resource`, `level`, `type` labels              | `==> Running build command 'yarn'...` |
| **Deploy**  | Has `resource`, `type` but no `level` or `instance` | `==> Your service is live`            |
| **Runtime** | Has `resource`, `instance`, `level`, `type`         | Your app's structured output          |

### Usage Patterns

**Multiple services:**

```bash
render logs -r srv-XXXXX,srv-YYYYY -o json --tail \
  | jq --unbuffered -c '{timestamp: .timestamp, message: .message} + ([.labels[] | {(.name): .value}] | add)' \
  | sed -u 's/\\u001b\[[0-9;]*m//g; s/\\u001b(B//g' \
  | gonzo
```

**Historical query:**

```bash
render logs -r srv-XXXXX -o json --limit 100 \
  --start 2026-03-27T14:00:00Z --end 2026-03-27T15:00:00Z \
  | jq -c '{timestamp: .timestamp, message: .message} + ([.labels[] | {(.name): .value}] | add)' \
  | sed -u 's/\\u001b\[[0-9;]*m//g; s/\\u001b(B//g' \
  | gonzo
```

**Filter at source:**

```bash
render logs -r srv-XXXXX -o json --tail --level error | ...
render logs -r srv-XXXXX -o json --tail --text "timeout" | ...
```

### Rate Limits

**Streaming** (`--tail`) uses WebSocket — **not rate limited**. Recommended mode.

**Fetch mode** (`--limit`, `--start`, `--end`) uses the REST API and is subject to plan-based limits.

**Platform cap:** 6,000 log lines/minute per instance. Excess is silently dropped.

### Structured Logging Tips

Render maps the `level` field from your app's stdout to its internal severity. Emit structured JSON for best results. Same stderr gotcha as Railway — Python's `logging` defaults to stderr, so `logging.info()` calls show up as errors. Use structured JSON to override.

**Time to complete:** 10 minutes **Prerequisites:** Render CLI, `jq`, Gonzo installed **Full guide:** [`guides/RENDER_USAGE_GUIDE.md`](https://github.com/control-theory/gonzo/blob/main/guides/RENDER_USAGE_GUIDE.md)


# Fly.io Logs

Stream logs from Fly.io apps into Gonzo for real-time analysis, filtering, and AI-powered insights.

Stream logs from Fly.io apps into Gonzo with a lightweight `jq` transform. Fly's CLI streams structured JSON over NATS, but your app's output is double-encoded inside the `message` field. The pipe below unwraps it so Gonzo sees clean, flat JSON.

#### Quick Start

```bash
fly logs -a <app-name> -j \
  | jq --unbuffered -c '
    {timestamp, region, instance}
    + (try (.message | fromjson) // empty)' \
  | gonzo
```

The `-j` flag gives you structured JSON. The `jq` transform extracts `timestamp`, `region`, and `instance` from the envelope, parses the inner message for your app's real fields (`level`, `message`, custom fields), and silently drops non-JSON lines (init logs, Firecracker boot messages).

#### Prerequisites

* Gonzo installed
* [Fly CLI](https://fly.io/docs/flyctl/) installed (`brew install flyctl`)
* `jq` installed (`brew install jq`)

#### Log Sources

Fly streams multiple sources through a single pipe. The `jq` transform with `// empty` keeps only your app's JSON output.

| Source     | Provider | What it captures                                    |
| ---------- | -------- | --------------------------------------------------- |
| **App**    | `app`    | Your app's stdout/stderr, plus Fly init messages    |
| **Runner** | `runner` | Image pulls, Firecracker config, machine start/stop |
| **Proxy**  | `proxy`  | Machine reachability, startup timing                |

To **include platform logs** (useful during deploy debugging), swap `// empty` for `// {message: .message}`:

```bash
fly logs -a my-app -j \
  | jq --unbuffered -c '
    {timestamp, region, instance, provider: .meta.Event.Provider}
    + (try (.message | fromjson) // {message: .message})' \
  | gonzo
```

#### Usage Patterns

**Real-time streaming** (default):

```bash
fly logs -a my-app -j \
  | jq --unbuffered -c '{timestamp, region, instance}
    + (try (.message | fromjson) // empty)' \
  | gonzo
```

**Filter by region:**

```bash
fly logs -a my-app -j --region lhr | ...
```

**Filter by machine:**

```bash
fly logs -a my-app -j --machine 6835d41f765168 | ...
```

**Buffer dump (no streaming):**

```bash
fly logs -a my-app -j --no-tail \
  | jq -c '{timestamp, region, instance}
    + (try (.message | fromjson) // empty)' \
  | gonzo
```

`--no-tail` dumps the current log buffer and exits. For historical queries with date ranges, use Fly's [Grafana log search](https://fly.io/docs/monitoring/search-logs/) (30-day retention).

**With local AI (logs never leave your machine):**

```bash
export OPENAI_API_KEY="ollama"
export OPENAI_API_BASE="http://localhost:11434"
fly logs -a my-app -j \
  | jq --unbuffered -c '{timestamp, region, instance}
    + (try (.message | fromjson) // empty)' \
  | gonzo
```

#### Machines and Auto-Stop

Fly Machines [auto-stop](https://fly.io/docs/launch/autostop-autostart/) when there's no inbound traffic. Log streams end when machines stop — this is expected, not a Gonzo or pipe issue. Machines restart on the next request. To keep logs flowing, send periodic requests or set `auto_stop_machines = false` in `fly.toml`.

#### Structured Logging Tips

Emit single-line JSON to stdout for the best Gonzo experience. Multi-line JSON objects are split into separate log entries by Fly's pipeline.

Fly tags all stderr output with `"level": "info"` at the envelope level, same as stdout. If you rely on stderr for error output (e.g. Python's `logging` defaults), the envelope level won't reflect real severity. Use structured JSON with an explicit `level` field instead.

#### Troubleshooting

| Symptom                                | Cause & fix                                                                                            |
| -------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| No logs appearing                      | Check `fly status -a <app>`. Machines may be stopped — hit your app's URL to wake them.                |
| Only build/boot logs, no app logs      | Firecracker VM boot takes a few seconds. Wait 10–15s after deploy.                                     |
| Envelope `level` always "info"         | Expected. Fly doesn't map app log level to envelope. The `jq` transform extracts the real level.       |
| Logs stall in the pipe                 | Add `--unbuffered` to `jq`. Without it, output buffers and logs appear in delayed bursts.              |
| Init messages mixed with app logs      | Fly's init process is tagged `provider: "app"`. The `// empty` pattern drops these (they're not JSON). |
| Trial account machines killed after 5m | Add a payment method at [fly.io/trial](https://fly.io/trial). Free allowance covers small apps.        |

***

**Time to complete:** 5 minutes **Prerequisites:** Fly CLI, jq, Gonzo installed **Full guide:** [`guides/FLY_USAGE_GUIDE.md`](https://github.com/control-theory/gonzo/blob/main/guides/FLY_USAGE_GUIDE.md)


# AWS CloudWatch Logs

## AWS CloudWatch Integration

Analyze AWS CloudWatch Logs with Gonzo for powerful, interactive log analysis right from your terminal. Stream logs in real-time or analyze historical data with AI-powered insights.

{% hint style="info" %}
**Prerequisites:** AWS CLI installed and configured with appropriate credentials. Use `aws configure` to set up your AWS access.
{% endhint %}

### Why Use Gonzo with CloudWatch?

AWS CloudWatch Logs is a powerful log aggregation service, but analyzing logs in the console can be limiting. Gonzo brings:

* **🎨 Visual Analysis** - Beautiful terminal interface vs web console
* **🤖 AI Insights** - Intelligent pattern recognition and root cause analysis
* **⚡ Real-Time Streaming** - Live log analysis as events occur
* **🔍 Advanced Filtering** - Powerful regex and search capabilities
* **📊 Pattern Detection** - Automatic clustering of similar log entries
* **💰 Cost Efficiency** - Analyze logs locally without CloudWatch Insights costs

### Quick Start

#### Getting Your Log Groups

First, discover what log groups are available in your AWS region:

```bash
# List all log groups with names and ARNs
aws logs describe-log-groups \
  --query 'logGroups[*].{Name:logGroupName,ARN:arn}' \
  --output json

# List log groups in table format
aws logs describe-log-groups \
  --query 'logGroups[*].{Name:logGroupName,ARN:arn}' \
  --output table

# Filter by prefix
aws logs describe-log-groups \
  --log-group-name-prefix /aws/lambda/ \
  --query 'logGroups[*].logGroupName' \
  --output text
```

#### Basic Log Tailing with Gonzo

The simplest way to use Gonzo with CloudWatch Logs is to pipe `aws logs tail` output:

```bash
# Basic tail (default: last 10 minutes)
aws logs tail "/aws/eks/stage/cluster" --follow | gonzo

# Tail with JSON output for better attribute extraction
aws logs tail "/aws/eks/stage/cluster" --follow --format json | gonzo

# Tail with AI analysis
aws logs tail "/aws/eks/stage/cluster" --follow --format json | \
gonzo --ai-model="gpt-4"
```

{% hint style="info" %}
**Output Format:** The default "detailed" format outputs one log per line (non-JSON). Use `--format json` to gain attribute visibility in Gonzo, though each JSON log message spans two lines.
{% endhint %}

#### Multiple Log Groups

Monitor multiple log groups simultaneously:

```bash
# Method 1: Using process substitution
gonzo - < <(
  aws logs tail "/aws/eks/stage/cluster" --follow --format json &
  aws logs tail "RDS" --follow --format json &
  wait
)

# Method 2: Named pipes (alternative)
mkfifo log_stream
(aws logs tail "/aws/eks/stage/cluster" --follow --format json &
 aws logs tail "RDS" --follow --format json) > log_stream &
gonzo - < log_stream

# Method 3: File-based aggregation
aws logs tail "/aws/eks/stage/cluster" --follow --format json > logs1.txt &
aws logs tail "RDS" --follow --format json > logs2.txt &
gonzo -f logs1.txt -f logs2.txt --follow
```

**How This Works:**

* Starts multiple `aws logs tail` processes in the background (`&`)
* Combines their output streams
* Pipes the combined output to Gonzo
* Uses `wait` to ensure all background processes complete properly

### AWS CLI Live Tail Integration

Live Tail provides near real-time streaming of log events as they are ingested into CloudWatch.

#### Basic Live Tail Usage

```bash
# Single log group with ARN
aws logs start-live-tail --log-group-identifiers \
  "arn:aws:logs:us-east-1:767397775588:log-group:/aws/eks/stage/cluster" | gonzo

# Multiple log groups
aws logs start-live-tail --log-group-identifiers \
  "arn:aws:logs:us-east-1:767397775588:log-group:/aws/eks/stage/cluster" \
  "arn:aws:logs:us-east-1:767397775588:log-group:RDS" | gonzo

# With AI analysis
aws logs start-live-tail --log-group-identifiers \
  "arn:aws:logs:us-east-1:767397775588:log-group:/aws/eks/stage/cluster" | \
gonzo --ai-model="gpt-4"
```

**Live Tail Benefits:**

* ✅ Near real-time streaming (lower latency than `tail`)
* ✅ Native JSON output (better attribute extraction)
* ✅ Supports multiple log groups natively
* ✅ Automatic handling of high-throughput log groups

#### Live Tail vs Regular Tail

| Feature                 | `aws logs tail`            | `aws logs start-live-tail` |
| ----------------------- | -------------------------- | -------------------------- |
| **Latency**             | \~1-2 seconds              | Near real-time (<1 second) |
| **Multiple Log Groups** | Requires workarounds       | Native support             |
| **Output Format**       | Detailed (default) or JSON | JSON (default)             |
| **Historical Logs**     | Yes (--since flag)         | No (only new logs)         |
| **Best For**            | Historical analysis        | Real-time monitoring       |

**Choose Live Tail When:**

* Monitoring production incidents in real-time
* Need lowest possible latency
* Monitoring multiple log groups simultaneously
* JSON output is preferred

**Choose Regular Tail When:**

* Need historical log analysis
* Want to start from specific time (--since)
* Need simple single log group monitoring

### AWS CLI Integration

#### Installing and Configuring AWS CLI

```bash
# Install AWS CLI (if not already installed)
# macOS
brew install awscli

# Linux
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install

# Windows
# Download from: https://awscli.amazonaws.com/AWSCLIV2.msi

# Configure AWS CLI
aws configure
# Enter:
#   AWS Access Key ID
#   AWS Secret Access Key
#   Default region (e.g., us-east-1)
#   Default output format (json recommended)

# Verify configuration
aws sts get-caller-identity
```

#### Essential CloudWatch Logs Commands

{% tabs %}
{% tab title="Listing Log Groups" %}

```bash
# List all log groups
aws logs describe-log-groups

# List with specific prefix
aws logs describe-log-groups --log-group-name-prefix /aws/lambda/

# Get specific log group details
aws logs describe-log-groups --log-group-name-prefix /aws/lambda/my-function

# Count log groups
aws logs describe-log-groups --query 'length(logGroups)'
```

{% endtab %}

{% tab title="Tailing Logs" %}

```bash
# Basic tail (last 10 minutes)
aws logs tail /aws/lambda/my-function

# Follow in real-time
aws logs tail /aws/lambda/my-function --follow

# Since specific time
aws logs tail /aws/lambda/my-function --since 1h
aws logs tail /aws/lambda/my-function --since 30m
aws logs tail /aws/lambda/my-function --since 2024-01-15T10:00:00

# Filter pattern
aws logs tail /aws/lambda/my-function --filter-pattern "ERROR"

# Format options
aws logs tail /aws/lambda/my-function --format short
aws logs tail /aws/lambda/my-function --format detailed
```

{% endtab %}

{% tab title="Filtering Logs" %}

```bash
# Filter by pattern
aws logs tail /aws/lambda/my-function --filter-pattern "ERROR"

# Multiple terms (AND logic)
aws logs tail /aws/lambda/my-function --filter-pattern "ERROR timeout"

# JSON field filtering
aws logs tail /aws/lambda/my-function --filter-pattern '{ $.level = "error" }'

# Numeric filtering
aws logs tail /aws/lambda/my-function --filter-pattern '{ $.duration > 1000 }'

# Combined with Gonzo
aws logs tail /aws/lambda/my-function --filter-pattern "ERROR" --follow | gonzo
```

{% endtab %}
{% endtabs %}

### Real-World Integration Patterns

#### Lambda Function Monitoring

```bash
# Monitor specific Lambda function
aws logs tail /aws/lambda/my-function --follow | gonzo

# Monitor with AI for error analysis
aws logs tail /aws/lambda/my-function --follow | \
gonzo --ai-model="gpt-4"

# Monitor multiple Lambda functions
(aws logs tail /aws/lambda/function1 --follow & \
 aws logs tail /aws/lambda/function2 --follow) | gonzo

# Focus on errors only
aws logs tail /aws/lambda/my-function --follow | \
grep -i error | \
gonzo --log-buffer=5000
```

#### ECS/Fargate Container Logs

```bash
# ECS task logs
aws logs tail /ecs/my-service --follow | gonzo

# Filter by container
aws logs tail /ecs/my-service --follow | \
grep "container-name" | \
gonzo

# Multiple ECS services
(aws logs tail /ecs/api --follow & \
 aws logs tail /ecs/worker --follow) | \
gonzo --log-buffer=10000
```

#### API Gateway Logs

```bash
# API Gateway execution logs
aws logs tail /aws/apigateway/my-api --follow | gonzo

# Filter by HTTP status
aws logs tail /aws/apigateway/my-api --follow | \
grep -E "(4[0-9]{2}|5[0-9]{2})" | \
gonzo --ai-model="gpt-4"

# Access logs analysis
aws logs tail /aws/apigateway/my-api/access --since 1h | \
gonzo --log-buffer=20000
```

#### RDS Database Logs

```bash
# RDS error logs
aws logs tail /aws/rds/instance/my-db/error --follow | gonzo

# Slow query logs
aws logs tail /aws/rds/instance/my-db/slowquery --follow | \
gonzo --ai-model="gpt-4"

# General logs
aws logs tail /aws/rds/instance/my-db/general --since 1h | gonzo
```

#### CloudTrail Logs

```bash
# Monitor CloudTrail events
aws logs tail aws-cloudtrail-logs --follow | gonzo

# Security-focused monitoring
aws logs tail aws-cloudtrail-logs --follow | \
grep -E "(unauthorized|denied|failed)" | \
gonzo --ai-model="gpt-4"

# Specific service events
aws logs tail aws-cloudtrail-logs --follow | \
grep "ec2.amazonaws.com" | \
gonzo
```

### Advanced Usage Patterns

#### Multi-Account Monitoring

```bash
# Switch AWS profiles
export AWS_PROFILE=production
aws logs tail /aws/lambda/function --follow | gonzo

# Monitor multiple accounts simultaneously
AWS_PROFILE=prod aws logs tail /aws/lambda/api --follow > prod-logs.txt &
AWS_PROFILE=staging aws logs tail /aws/lambda/api --follow > staging-logs.txt &
gonzo -f prod-logs.txt -f staging-logs.txt --follow

# Account-specific aliases
alias gonzo-prod='AWS_PROFILE=production aws logs tail'
alias gonzo-staging='AWS_PROFILE=staging aws logs tail'

# Usage
gonzo-prod /aws/lambda/function --follow | gonzo
```

#### Cost-Optimized Analysis

```bash
# Export logs once, analyze multiple times
aws logs tail /aws/lambda/function --since 24h > logs-$(date +%Y%m%d).txt

# Analyze without streaming (no ongoing CloudWatch costs)
gonzo -f logs-20240115.txt --ai-model="gpt-4"

# Batch processing for cost savings
for log_group in $(aws logs describe-log-groups --query 'logGroups[*].logGroupName' --output text); do
    echo "Analyzing $log_group..."
    aws logs tail "$log_group" --since 1h > "logs/${log_group//\//_}.txt"
done

# Analyze all exported logs
gonzo -f logs/*.txt
```

#### Automated Monitoring Scripts

```bash
#!/bin/bash
# monitor-cloudwatch.sh
# Continuous monitoring with alerting

LOG_GROUP="$1"
ALERT_PATTERN="${2:-ERROR}"
ALERT_WEBHOOK="${3}"

echo "Monitoring $LOG_GROUP for pattern: $ALERT_PATTERN"

aws logs tail "$LOG_GROUP" --follow | \
while IFS= read -r line; do
    echo "$line"
    
    # Check for alert pattern
    if echo "$line" | grep -qi "$ALERT_PATTERN"; then
        # Send alert
        if [ -n "$ALERT_WEBHOOK" ]; then
            curl -X POST "$ALERT_WEBHOOK" \
                -H "Content-Type: application/json" \
                -d "{\"text\": \"Alert: $line\"}"
        fi
        
        # Analyze with Gonzo + AI
        echo "$line" | gonzo --ai-model="gpt-4"
    fi
done
```

#### Performance Analysis

```bash
# Analyze Lambda cold starts
aws logs tail /aws/lambda/function --since 1h | \
grep "Init Duration" | \
gonzo --ai-model="gpt-4"

# Memory usage analysis
aws logs tail /aws/lambda/function --since 1h | \
grep "Max Memory Used" | \
gonzo

# Duration analysis
aws logs tail /aws/lambda/function --since 1h | \
grep "Duration" | \
gonzo --log-buffer=20000
```

### CloudWatch Logs Insights Integration

#### Export Insights Query Results

```bash
# Run CloudWatch Logs Insights query
query_id=$(aws logs start-query \
    --log-group-name /aws/lambda/my-function \
    --start-time $(date -u -d '1 hour ago' +%s) \
    --end-time $(date -u +%s) \
    --query-string 'fields @timestamp, @message | filter @message like /ERROR/ | sort @timestamp desc | limit 1000' \
    --query 'queryId' \
    --output text)

# Wait for query to complete
aws logs wait query-complete --query-id "$query_id"

# Get results and analyze with Gonzo
aws logs get-query-results --query-id "$query_id" | \
jq -r '.results[] | .[1].value' | \
gonzo --ai-model="gpt-4"
```

### Configuration for CloudWatch

#### Optimized Configuration File

```yaml
# ~/.config/gonzo/cloudwatch.yml
# Optimized for CloudWatch Logs

# CloudWatch logs are streamed via stdin
# No file configuration needed

# Performance for CloudWatch streaming
update-interval: 2s              # Responsive updates
log-buffer: 10000               # Large buffer for CloudWatch volume
memory-size: 50000              # Extensive pattern tracking

# AI configuration for AWS analysis
ai-model: "gpt-4"               # Best for complex AWS issues
ai-context-size: 8000           # Large context for AWS logs

# Display
show-service: true              # Show AWS service context
```

**Usage:**

```bash
aws logs tail /aws/lambda/function --follow | \
gonzo --config ~/.config/gonzo/cloudwatch.yml
```

#### Environment-Specific Aliases

```bash
# Add to ~/.bashrc or ~/.zshrc

# Production monitoring
alias gonzo-prod='AWS_PROFILE=production aws logs tail --follow'

# Development monitoring
alias gonzo-dev='AWS_PROFILE=development aws logs tail --follow'

# Lambda-specific
alias gonzo-lambda='aws logs tail --follow'

# With AI analysis
alias gonzo-lambda-ai='aws logs tail --follow | gonzo --ai-model="gpt-4"'

# Usage
gonzo-lambda /aws/lambda/my-function
gonzo-lambda-ai /aws/lambda/critical-function
```

### Complete Guide

For step-by-step CloudWatch integration: 📖 [**Gonzo: A Better Way to Tail AWS CloudWatch Logs**](https://www.controltheory.com/blog/gonzo-a-better-way-to-tail-aws-cloudwatch-logs/)

### Best Practices

#### 🎯 **Efficient Log Retrieval**

```bash
# Use time ranges to limit data
aws logs tail /aws/lambda/function --since 1h    # Last hour only

# Use filter patterns for pre-filtering
aws logs tail /aws/lambda/function --filter-pattern "ERROR" --follow

# Export for repeated analysis
aws logs tail /aws/lambda/function --since 24h > daily-export.txt
gonzo -f daily-export.txt  # No repeated CloudWatch API calls
```

### Cost Considerations

{% hint style="warning" %}
**Important:** AWS costs may be incurred for using the AWS CLI `tail` or `start-live-tail` commands. Please consult the [AWS CloudWatch Logs pricing documentation](https://aws.amazon.com/cloudwatch/pricing/) for details on potential charges related to log data retrieval.
{% endhint %}

#### Understanding CloudWatch Logs Pricing

**Data Retrieval Costs:**

* **GetLogEvents API**: Used by `aws logs tail` - included with storage
* **StartLiveTail API**: Used by `aws logs start-live-tail` - additional charges may apply
* **Data Transfer**: Egress charges may apply for large volumes

#### Cost Optimization Strategies

```bash
# 1. Use time-based filtering to reduce data volume
aws logs tail /aws/lambda/function --since 1h --follow | gonzo  # Last hour only

# 2. Use filter patterns at the source
aws logs tail /aws/lambda/function --filter-pattern "ERROR" --follow | gonzo

# 3. Export once, analyze multiple times (no repeated API calls)
aws logs tail /aws/lambda/function --since 24h > daily-export.txt
gonzo -f daily-export.txt  # Analyze locally
gonzo -f daily-export.txt --ai-model="gpt-4"  # Re-analyze with AI

# 4. Use regular tail instead of live tail when real-time isn't critical
aws logs tail /aws/lambda/function --follow | gonzo  # Lower cost

# 5. Monitor specific log groups instead of all logs
aws logs tail "/aws/lambda/critical-function" --follow | gonzo  # Focused monitoring
```

**Cost Comparison Example:**

```bash
# Higher cost: Live tail multiple groups for 24 hours
aws logs start-live-tail --log-group-identifiers arn1 arn2 arn3 | gonzo

# Lower cost: Regular tail with filtering
aws logs tail "/aws/lambda/function" --filter-pattern "ERROR" --follow | gonzo

# Lowest cost: Export and analyze locally
aws logs tail "/aws/lambda/function" --since 1h > export.txt
gonzo -f export.txt  # No ongoing API costs
```

#### 🔒 **Security Best Practices**

```bash
# Use IAM roles instead of access keys
aws configure set role_arn arn:aws:iam::123456789012:role/LogAnalyst
aws configure set source_profile default

# Least privilege IAM policy for Gonzo usage:
# {
#   "Version": "2012-10-17",
#   "Statement": [{
#     "Effect": "Allow",
#     "Action": [
#       "logs:DescribeLogGroups",
#       "logs:DescribeLogStreams",
#       "logs:GetLogEvents",
#       "logs:FilterLogEvents"
#     ],
#     "Resource": "arn:aws:logs:*:*:log-group:/aws/lambda/*"
#   }]
# }

# Use MFA for production access
aws configure set mfa_serial arn:aws:iam::123456789012:mfa/user

# Audit log access
aws cloudtrail lookup-events --lookup-attributes AttributeKey=ResourceName,AttributeValue=/aws/lambda/function
```

#### ⚡ **Performance Optimization**

```bash
# Pre-filter for performance
aws logs tail /aws/lambda/function --filter-pattern "ERROR" --follow | gonzo

# Adjust Gonzo buffers for volume
aws logs tail /aws/lambda/high-traffic --follow | \
gonzo --log-buffer=20000 --update-interval=5s

# Use local AI for sensitive logs
export OPENAI_API_BASE="http://localhost:11434"
aws logs tail /aws/lambda/sensitive --follow | \
gonzo --ai-model="llama3"
```

### Troubleshooting

#### Common Issues

**Authentication Errors:**

```bash
# Verify AWS credentials
aws sts get-caller-identity

# Check IAM permissions
aws iam get-user

# Use specific profile
AWS_PROFILE=your-profile aws logs tail /aws/lambda/function
```

**Log Group Not Found:**

```bash
# List available log groups
aws logs describe-log-groups | grep logGroupName

# Search for specific pattern
aws logs describe-log-groups --log-group-name-prefix /aws/lambda/

# Verify log group name (case-sensitive)
aws logs describe-log-groups --log-group-name /aws/lambda/my-function
```

**No Logs Appearing:**

```bash
# Check if logs exist
aws logs tail /aws/lambda/function --since 24h

# Verify time range
aws logs tail /aws/lambda/function --since 5m  # Last 5 minutes

# Check filter pattern
aws logs tail /aws/lambda/function --filter-pattern ""  # All logs
```

**Performance Issues:**

```bash
# Reduce log volume
aws logs tail /aws/lambda/function --filter-pattern "ERROR"

# Increase Gonzo buffers
aws logs tail /aws/lambda/function --follow | \
gonzo --log-buffer=20000 --memory-size=50000

# Use longer update intervals
aws logs tail /aws/lambda/function --follow | \
gonzo --update-interval=10s
```

### What's Next?

Now that you've mastered CloudWatch integration, explore related topics:

* **Kubernetes Integration** - Analyze EKS cluster logs
* **Configuration** - Optimize for CloudWatch workflows
* **AI Integration** - Enhanced AWS log analysis
* **Advanced Features** - Pattern detection in AWS logs

Or try these advanced CloudWatch patterns:

```bash
# Multi-region monitoring
for region in us-east-1 us-west-2 eu-west-1; do
    AWS_REGION=$region aws logs tail /aws/lambda/function --follow > logs-${region}.txt &
done
gonzo -f logs-*.txt --follow

# Cross-account analysis
AWS_PROFILE=account1 aws logs tail /aws/lambda/function --since 1h > account1.txt
AWS_PROFILE=account2 aws logs tail /aws/lambda/function --since 1h > account2.txt
gonzo -f account1.txt -f account2.txt --ai-model="gpt-4"
```

***

**Unlock the full potential of AWS CloudWatch Logs with Gonzo!** ☁️ From real-time Lambda monitoring to comprehensive AWS infrastructure analysis, Gonzo brings powerful log analysis to your CloudWatch workflows.


# Container Environments

Have container, will stream.

Gonzo works great with container environments including Docker and Kubernetes, as well as various tooling such as "kubectl", "Stern" and "k9s".


# Docker 🐳

Gonzo transforms Docker log analysis by providing real-time visual insights into container behavior. Instead of grep-ing through text streams, you get severity distribution charts, pattern detection, and AI-powered anomaly analysis — perfect for debugging multi-container applications.

### Docker Container Logs

#### Single Container

Stream logs from a running container:

```bash
docker logs -f my-container 2>&1 | gonzo
```

The `2>&1` ensures both stdout and stderr are captured.

#### Specific Time Range

Analyze logs from a specific period:

```bash
docker logs --since 1h my-container 2>&1 | gonzo
docker logs --since 2024-01-01T10:00:00 my-container 2>&1 | gonzo
```

#### With Gonzo AI Analysis

Enable AI-powered insights:

```bash
export OPENAI_API_KEY=sk-your-key-here
docker logs -f my-container 2>&1 | gonzo --ai-model="gpt-4"
```

### Docker Compose

#### All Services

Analyze logs from all services in your compose stack:

```bash
docker compose logs -f 2>&1 | gonzo
```

#### Specific Service

Analyze logs from a single service:

```bash
docker compose logs -f web 2>&1 | gonzo
docker compose logs -f database 2>&1 | gonzo
```

#### Multiple Services

Combine logs from multiple services:

```bash
docker compose logs -f web api worker 2>&1 | gonzo
```

#### Filter by Time

Recent logs only:

```bash
docker compose logs --since 30m -f web 2>&1 | gonzo
```

### Common Patterns

#### Debugging Failed Container

Analyze logs from a container that exited:

```bash
docker logs my-failed-container 2>&1 | gonzo
```

#### Comparing Services

Run multiple Gonzo instances in separate terminals:

```bash
# Terminal 1
docker compose logs -f frontend 2>&1 | gonzo

# Terminal 2
docker compose logs -f backend 2>&1 | gonzo
```


# Kubernetes ⎈

Using Gonzo with Kubernetes

Gonzo can now (as of version 0.3.0) natively stream logs from your Kubernetes clusters (using a `kubeconfig`) — no `kubectl logs`, no stern, no piping required. This guide covers the essential setup, commands, and filters you need to get started.

***

### **Overview**

With Kubernetes mode enabled, Gonzo supports:

* Direct log streaming from pods
* Multiple namespaces at once
* Kubernetes label selectors
* Automatic namespace + pod columns
* Interactive namespace/pod filtering (`Ctrl+k`)
* Real-time updates with reconnection

***

### **Prerequisites**

Before you begin, ensure:

* You have access to a Kubernetes cluster
* Your `kubeconfig` is valid
* Your account has read access to pod logs

#### **Required RBAC**

```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: gonzo-log-reader
rules:
- apiGroups: [""]
  resources: ["pods", "pods/log"]
  verbs: ["get", "list", "watch"]
- apiGroups: [""]
  resources: ["namespaces"]
  verbs: ["get", "list"]
```

***

### **Quick Start**

#### **Stream logs from all pods**

```bash
gonzo --k8s-enabled=true
```

#### **Start with the last 50 log lines**

```bash
gonzo --k8s-enabled=true --k8s-tail=50
```

#### **Watch a specific namespace**

```bash
gonzo --k8s-enabled=true --k8s-namespace=production
```

#### **Watch multiple namespaces**

```bash
gonzo --k8s-enabled \
  --k8s-namespace=production \
  --k8s-namespace=staging
```

#### **Filter by label selector**

```bash
gonzo --k8s-enabled --k8s-selector="app=myapp"
```

**Set-based selectors**

```bash
gonzo --k8s-enabled --k8s-selector="environment in (prod,staging)"
```

***

### **Common Configuration Options**

| Flag                | Description                    |
| ------------------- | ------------------------------ |
| `--k8s-enabled`     | Enable Kubernetes integration  |
| `--k8s-namespace N` | Set namespace(s) to watch      |
| `--k8s-selector`    | Kubernetes label selector      |
| `--k8s-tail N`      | Number of historic log lines   |
| `--k8s-since N`     | Only logs newer than N seconds |
| `--k8s-context`     | Use a specific kube context    |
| `--k8s-kubeconfig`  | Path to kubeconfig file        |

#### **Example: Namespace + Selector + Tail**

```bash
gonzo --k8s-enabled \
  --k8s-namespace=production \
  --k8s-selector="app=api" \
  --k8s-tail=100
```

***

### **Interactive Filtering (Ctrl+k)**

Inside Gonzo, press **Ctrl+k** to open the Kubernetes filter modal.

You can:

* Select **namespaces**
* Select **pods**
* Apply changes instantly

**Navigation:**\
↑/↓ to move • Space to toggle • Enter to apply • ESC to cancel

<figure><img src="/files/YVeu0Jhzmw6EuUDzhfpZ" alt=""><figcaption></figcaption></figure>

***

### **Kubernetes Display Mode**

Gonzo automatically switches into K8s column mode when logs contain Kubernetes attributes.

```
Time     Level Namespace        Pod                   Message
15:04:05 INFO  production       api-5c44d7f-xkr2p      Started worker process
```

Press **c** to toggle Kubernetes columns on/off.

<figure><img src="/files/arCBWLHVxrIaDMWAxKrD" alt=""><figcaption></figcaption></figure>

***

### **Example Workflows**

#### **Troubleshoot a new deployment**

```bash
gonzo --k8s-enabled \
  --k8s-namespace=production \
  --k8s-selector="app=api,version=v2.0.0" \
  --k8s-since=300
```

#### **Monitor both staging + prod backend pods**

```bash
gonzo --k8s-enabled \
  --k8s-namespace=production \
  --k8s-namespace=staging \
  --k8s-selector="tier=backend"
```

***

### **Troubleshooting**

#### **No logs appear**

Verify kubectl access:

```bash
kubectl get pods -A
kubectl logs <pod> -n <namespace>
```

#### **Selector not matching**

```bash
kubectl get pods --selector="app=myapp" -A
```

#### **Wrong context**

```bash
gonzo --k8s-context=my-cluster
```

#### **High log volume**

* Narrow your label selector
* Limit historic logs (`--k8s-tail`)
* Limit time window (`--k8s-since`)

***

### **Best Practices**

* Start with **specific namespaces/selectors**
* Use **Ctrl+k** to refine quickly
* Toggle columns with **c** when needed
* Save common setups in config files
* Use contexts to switch clusters cleanly


# Stern ⛵ Integration

Use Gonzo across multiple pod logs with ease

Stream and analyze Kubernetes logs with Gonzo using kubectl and [Stern](https://github.com/stern/stern). Monitor pods, deployments, and entire namespaces with powerful real-time analysis and AI-powered insights.

{% hint style="info" %}
**Prerequisites:** Kubernetes cluster access with kubectl configured. Stern is optional but highly recommended for advanced use cases.
{% endhint %}

### Basic Examples

```bash
# Get logs from all pods, all namespaces
stern . --all-namespaces --output json | gonzo

# Monitor specific namespace
stern . -n kube-system --output json | gonzo

# Get last 100 logs from namespace
stern . -n kube-system --tail 100 --output json | gonzo

# Monitor pods matching pattern
stern "api-*" -n production --output json | gonzo

# Get logs from last hour
stern . -n production --since 1h --output json | gonzo
```

### Key Options

* `--output json` - Preferred for Gonzo compatibility (populating attributes)
* `--tail N` - Limit historical logs
* `--since TIME` - Time-based filtering (1h, 30m, etc.)
* `-n NAMESPACE` - Target specific namespace
* `--all-namespaces` - Monitor all namespaces

### Tips

* Use specific pod patterns instead of `.` for better performance
* Always include `--output json` for proper Gonzo (attribute) processing
* Consider `--tail` to limit log volume for large clusters

### Deep Dive Tutorial

For a comprehensive guide on using Gonzo with Kubernetes: 📖 [**Using Gonzo with k9s and Stern: Supercharge Your Kubernetes Log Tailing**](https://www.controltheory.com/blog/using-gonzo-with-k9s-and-stern-supercharge-your-kubernetes-log-tailing/)


# K9s 🐶 Integration

k9s + Gonzo = Awesome

Gonzo integrates seamlessly with [k9s](https://github.com/derailed/k9s) (via the k9s plugin framework) to provide real-time log analysis with visual charts, AI-powered pattern detection, and severity tracking — all in the same familiar terminal UI you already use for cluster management. Instead of just scrolling through text, you get instant insights into error spikes, word frequencies, and anomalies.

### Plugin Configuration

Add this to your `$XDG_CONFIG_HOME/k9s/plugins.yaml` file:

```yaml
plugins:
  gonzo:
    shortCut: Ctrl-L
    description: "Gonzo log analysis"
    scopes:
      - po
    command: sh
    background: false
    args:
      - -c
      - "kubectl logs -f --tail=0 $NAME -n $NAMESPACE --context $CONTEXT | gonzo"
```

> **Note for macOS users:** Although not required, defining `XDG_CONFIG_HOME=~/.config` is recommended to maintain consistency with Linux configuration practices.

### Usage

1. Launch k9s and navigate to pods (`:pods` or `:po`)
2. Select a pod
3. Press `Ctrl-L`
4. Gonzo opens with live log streaming and analysis

### Available k9s Variables

The following environment variables are available in k9s plugins:

* `$NAME` - Pod name
* `$NAMESPACE` - Pod namespace
* `$CONTEXT` - Current cluster context
* `$CLUSTER` - Cluster name

### Verify Plugin Location

Check where k9s expects your plugins file:

```bash
k9s info
```

Look for the `Plugins:` line in the output.


# VictoriaLogs 🪵

Stream and analyze logs directly from VictoriaLogs with Gonzo's native integration. Leverage VictoriaLogs' high-performance log storage with Gonzo's powerful analysis capabilities, including AI insights and pattern detection.

{% hint style="info" %}
**Native Integration:** Gonzo has built-in VictoriaLogs support with custom field parsing that properly maps VictoriaLogs format to Gonzo's internal log representation.
{% endhint %}

### Why Use Gonzo with VictoriaLogs?

VictoriaLogs is a high-performance, cost-effective log database. Combining it with Gonzo provides:

* **🚀 High-Performance Streaming** - Direct streaming from VictoriaLogs without intermediaries
* **🤖 AI-Powered Analysis** - Intelligent insights on your stored logs
* **📊 Pattern Detection** - Automatic clustering of similar log entries
* **🔍 LogsQL Queries** - Powerful query language for precise log filtering
* **🏷️ Smart Field Mapping** - Automatic mapping of VictoriaLogs fields to Gonzo attributes
* **⚡ Real-Time Analysis** - Live streaming and analysis of logs as they arrive

### Features

#### Custom Field Parsing

Gonzo automatically maps VictoriaLogs fields to provide optimal display and analysis:

| VictoriaLogs Field   | Gonzo Mapping  | Description                              |
| -------------------- | -------------- | ---------------------------------------- |
| `_msg`               | **Log Body**   | Displayed as main message (not raw JSON) |
| `_time`              | **Timestamp**  | Parsed as log timestamp                  |
| `_stream`            | **Attribute**  | Stream identifier                        |
| `_stream_id`         | **Attribute**  | Stream ID                                |
| **All other fields** | **Attributes** | Available in Attributes panel            |

#### Special Field Mappings

**Host Detection** - Checked in priority order:

1. `k8s.node.name` (Kubernetes node)
2. `kubernetes.pod_node_name` (Alternative K8s format)
3. `kubernetes_pod_node_name` (Underscore format)

**Severity Detection** - Checked in priority order:

* `level`
* `severity`
* `log.level`
* `log_level`
* `loglevel`
* `levelname`

#### Format Transformation Example

**VictoriaLogs JSON Input:**

```json
{
  "_msg": "Database connection established",
  "_stream": "app-logs",
  "_stream_id": "stream-001",
  "_time": "2024-01-15T10:30:46.456Z",
  "level": "INFO",
  "k8s.node.name": "node-02",
  "service": "database",
  "pool_size": 10
}
```

**Gonzo Display:**

* **Message:** "Database connection established" ✅ (clean message, not raw JSON)
* **Severity:** INFO (with appropriate color coding)
* **Timestamp:** 2024-01-15T10:30:46.456Z
* **Host:** node-02 (mapped from `k8s.node.name`)
* **Attributes Panel:**
  * `service` = "database"
  * `pool_size` = 10
  * `_stream` = "app-logs"
  * `_stream_id` = "stream-001"

### Configuration

#### Command Line Options

```bash
# Required
--vmlogs-url        # Victoria Logs URL endpoint

# Optional
--vmlogs-user       # Basic auth username
--vmlogs-password   # Basic auth password
--vmlogs-query      # LogsQL query (default: "*")
```

#### Environment Variables

```bash
# Set VictoriaLogs connection parameters
export GONZO_VMLOGS_URL="http://localhost:9428"
export GONZO_VMLOGS_USER="myuser"
export GONZO_VMLOGS_PASSWORD="mypass"
export GONZO_VMLOGS_QUERY="service:'my-app'"

# Then run Gonzo
gonzo
```

#### Configuration File

```yaml
# ~/.config/gonzo/victorialogs.yml
vmlogs-url: "http://localhost:9428"
vmlogs-user: "myuser"
vmlogs-password: "mypass"
vmlogs-query: "*"

# Performance settings for VictoriaLogs
update-interval: 2s
log-buffer: 20000
memory-size: 100000

# AI configuration
ai-model: "gpt-4"
```

**Usage:**

```bash
gonzo --config ~/.config/gonzo/victorialogs.yml
```

### Usage Examples

#### Basic Streaming

```bash
# Stream all logs from VictoriaLogs
gonzo --vmlogs-url="http://localhost:9428" --vmlogs-query="*"

# Stream with AI analysis
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query="*" \
      --ai-model="gpt-4"

# Stream with custom configuration
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query="*" \
      --log-buffer=20000 \
      --update-interval=2s
```

#### Authenticated Access

```bash
# Basic authentication
gonzo --vmlogs-url="https://vmlogs.example.com" \
      --vmlogs-user="myuser" \
      --vmlogs-password="mypass" \
      --vmlogs-query="*"

# With specific query
gonzo --vmlogs-url="https://vmlogs.example.com" \
      --vmlogs-user="myuser" \
      --vmlogs-password="mypass" \
      --vmlogs-query='level:error'

# Using environment variables for credentials
export GONZO_VMLOGS_USER="myuser"
export GONZO_VMLOGS_PASSWORD="mypass"
gonzo --vmlogs-url="https://vmlogs.example.com" \
      --vmlogs-query='level:error'
```

#### LogsQL Query Examples

{% tabs %}
{% tab title="Service Filtering" %}

```bash
# Specific service
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='service:"payment-processor"'

# Service with severity
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='service:"payment-processor" AND level:error'

# Multiple services
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='service:("api" OR "worker")'
```

{% endtab %}

{% tab title="Severity Filtering" %}

```bash
# Error logs only
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='level:error'

# Errors and warnings
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='level:(error OR warning)'

# Exclude debug logs
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='NOT level:debug'
```

{% endtab %}

{% tab title="Field-Based Queries" %}

```bash
# Kubernetes node filtering
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='k8s.node.name:"node-01"'

# Container name
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='kubernetes.container_name:"nginx"'

# Namespace filtering
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='kubernetes.namespace:"production"'

# Combined filters
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='kubernetes.namespace:"production" AND level:error'
```

{% endtab %}

{% tab title="Text Search" %}

```bash
# Message contains text
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='_msg:"database connection"'

# Pattern matching
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='_msg:*timeout*'

# Complex text search
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='_msg:("error" OR "failed") AND service:"api"'
```

{% endtab %}
{% endtabs %}

### Real-World Integration Patterns

#### Production Monitoring

```bash
# Monitor production errors with AI
gonzo --vmlogs-url="http://vmlogs.prod.company.com" \
      --vmlogs-user="$PROD_USER" \
      --vmlogs-password="$PROD_PASS" \
      --vmlogs-query='kubernetes.namespace:"production" AND level:error' \
      --ai-model="gpt-4"

# Multi-service monitoring
gonzo --vmlogs-url="http://vmlogs.prod.company.com" \
      --vmlogs-query='service:("api" OR "worker" OR "scheduler") AND level:(error OR warning)' \
      --log-buffer=20000
```

#### Kubernetes Log Analysis

```bash
# Specific namespace
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='kubernetes.namespace:"production"'

# Pod pattern matching
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='kubernetes.pod_name:*backend*'

# Node-specific logs
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='k8s.node.name:"node-01" AND level:error'

# Container-specific analysis
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='kubernetes.container_name:"nginx" AND level:warning'
```

#### Time-Based Analysis

```bash
# Recent logs (VictoriaLogs handles time filtering)
# Use VictoriaLogs Web UI or API to export specific time ranges
# Then analyze with Gonzo

# Stream recent logs
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='_time:>now-1h'

# Specific time range (if supported by your VictoriaLogs version)
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='_time:>2024-01-15T10:00:00Z AND _time:<2024-01-15T11:00:00Z'
```

#### Performance Troubleshooting

```bash
# High-duration operations
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='duration:>1000'  # Duration > 1000ms

# Slow queries
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='_msg:*slow* AND service:"database"'

# Memory warnings
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='_msg:(*memory* OR *oom*) AND level:warning'
```

### Implementation Details

#### VictoriaLogs Client Architecture

Gonzo's VictoriaLogs integration includes:

1. **Streaming Client** (`internal/vmlogs/client.go`)
   * Connects to VictoriaLogs `/select/logsql/tail` endpoint
   * Maintains persistent streaming connection
   * Handles reconnection on failures
2. **Format Converter**
   * Transforms VictoriaLogs JSON to OTLP format
   * Preserves all field information
   * Optimizes for Gonzo display
3. **Field Mapper**
   * Handles special fields (`_msg`, `_time`, etc.)
   * Maps host fields in priority order
   * Extracts all attributes automatically
4. **Severity Detector**
   * Identifies log levels from various field names
   * Provides consistent severity detection
   * Enables proper color coding

#### Streaming Endpoint

Gonzo uses the VictoriaLogs streaming tail endpoint:

```
http://victorialogs:9428/select/logsql/tail?query=<logsql_query>
```

This provides:

* Real-time log streaming
* Efficient resource usage
* Native LogsQL query support
* Automatic format conversion

### Configuration Optimization

#### High-Performance Setup

```yaml
# ~/.config/gonzo/vmlogs-production.yml
vmlogs-url: "http://vmlogs.company.com:9428"
vmlogs-user: "production-reader"
vmlogs-password: "${VMLOGS_PASSWORD}"  # From environment
vmlogs-query: "kubernetes.namespace:production AND level:(error OR warning)"

# Optimized for high volume
update-interval: 5s
log-buffer: 50000
memory-size: 200000

# Best AI for production
ai-model: "gpt-4"
ai-context-size: 8000
```

#### Development Setup

```yaml
# ~/.config/gonzo/vmlogs-dev.yml
vmlogs-url: "http://localhost:9428"
vmlogs-query: "*"  # All logs in development

# Fast updates for development
update-interval: 1s
log-buffer: 5000
memory-size: 20000

# Cost-effective AI
ai-model: "gpt-3.5-turbo"
```

### Best Practices

#### 🎯 **Efficient Querying**

```bash
# ✅ Good: Specific queries
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='service:"api" AND level:error'

# ❌ Avoid: Overly broad queries
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='*'  # All logs (high volume)

# ✅ Good: Use field filters
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='kubernetes.namespace:"production"'

# ✅ Good: Combine multiple filters
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='service:"api" AND level:error AND kubernetes.namespace:"production"'
```

#### 🔒 **Security Best Practices**

```bash
# Use environment variables for credentials
export GONZO_VMLOGS_USER="readonly-user"
export GONZO_VMLOGS_PASSWORD="secure-password"

# Don't hardcode passwords in commands
gonzo --vmlogs-url="https://vmlogs.company.com"  # Credentials from env

# Use HTTPS for remote connections
gonzo --vmlogs-url="https://vmlogs.company.com" \
      --vmlogs-query='level:error'

# Least privilege: Use read-only credentials
# Create VictoriaLogs user with SELECT-only permissions
```

#### ⚡ **Performance Optimization**

```bash
# For high-volume logs, adjust buffers
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='kubernetes.namespace:"production"' \
      --log-buffer=50000 \
      --update-interval=10s

# Use specific queries to reduce volume
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='level:(error OR warning)'  # Less volume

# Filter at source when possible
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='service:"critical-api" AND level:error'
```

### Troubleshooting

#### Connection Issues

```bash
# Test VictoriaLogs connectivity
curl "http://localhost:9428/select/logsql/query?query=*&limit=10"

# Verify authentication
curl -u myuser:mypass "http://localhost:9428/select/logsql/query?query=*&limit=10"

# Check VictoriaLogs is running
curl "http://localhost:9428/health"

# Test with verbose output
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query="*" \
      --verbose
```

#### Query Issues

```bash
# Test LogsQL query directly
curl "http://localhost:9428/select/logsql/query?query=level:error&limit=10"

# Verify field names
curl "http://localhost:9428/select/logsql/query?query=*&limit=1" | jq .

# Check query syntax in VictoriaLogs docs
# https://docs.victoriametrics.com/VictoriaLogs/LogsQL.html

# Start with simple query
gonzo --vmlogs-url="http://localhost:9428" --vmlogs-query="*"

# Then add complexity
gonzo --vmlogs-url="http://localhost:9428" --vmlogs-query="level:error"
```

#### Performance Issues

```bash
# Reduce query scope
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='service:"specific-service"'

# Increase update interval
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query="*" \
      --update-interval=10s

# Increase buffer sizes
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query="*" \
      --log-buffer=50000 \
      --memory-size=100000
```

#### Field Mapping Issues

```bash
# Check raw VictoriaLogs output
curl "http://localhost:9428/select/logsql/query?query=*&limit=5" | jq .

# Verify field names in Gonzo
# Press Tab to navigate to Attributes panel
# Check if expected fields are present

# Ensure using JSON output (default for VictoriaLogs)
# Gonzo automatically handles VictoriaLogs JSON format
```

### What's Next?

Now that you've mastered VictoriaLogs integration, explore related topics:

* **Configuration** - Optimize for VictoriaLogs workflows
* **AI Integration** - Enhanced log analysis with AI
* **Advanced Features** - Pattern detection in VictoriaLogs data
* **Kubernetes Integration** - Combine with K8s log analysis

Or try these advanced VictoriaLogs patterns:

```bash
# Multi-environment monitoring
gonzo --vmlogs-url="http://vmlogs.company.com" \
      --vmlogs-query='kubernetes.namespace:("production" OR "staging") AND level:error' \
      --ai-model="gpt-4"

# Service mesh analysis
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='service:"istio-proxy" AND level:warning'

# Custom field analysis
gonzo --vmlogs-url="http://localhost:9428" \
      --vmlogs-query='response_time:>1000 AND service:"api"'
```

***

**Unlock powerful log analysis with VictoriaLogs and Gonzo!** 📊 Native integration, intelligent field mapping, and AI-powered insights make VictoriaLogs logs easy to analyze and understand.


# Grafana Loki Integration 🔥

Integrate Gonzo with Grafana Loki for powerful live log tailing and analysis. Use Loki as your log store and Gonzo as your real-time terminal lens.

### Overview

Grafana Loki is a powerful log aggregation system designed for storing and querying logs at scale. While Loki excels at long-term retention and powerful queries via LogQL, live tailing logs for debugging and troubleshooting can be challenging. Gonzo fills this gap by providing a real-time, terminal-based interface for Loki logs.

**Why use Gonzo with Loki?**

* **Debug in real time**: Watch logs as code changes roll out
* **Validate pipelines**: Ensure OpenTelemetry agents ship logs correctly to Loki
* **Shorten feedback loops**: Catch issues instantly without switching tools
* **Stay in-flow**: Operate inside your terminal alongside kubectl, stern, and k9s
* **AI-powered insights**: Optional AI analysis of Loki logs

### Integration Methods

Gonzo supports two primary methods for accessing Loki logs:

1. **logcli** - Using Loki's official CLI tool
2. **Live Tail API** - Direct connection to Loki's live tailing endpoint

### Method 1: Using logcli

The easiest way to get started is using Loki's official `logcli` tool.

#### Install logcli

```bash
# macOS via Homebrew
brew install logcli

# Linux - download binary
curl -O -L "https://github.com/grafana/loki/releases/download/v2.9.0/logcli-linux-amd64.zip"
unzip "logcli-linux-amd64.zip"
chmod a+x logcli-linux-amd64
sudo mv logcli-linux-amd64 /usr/local/bin/logcli

# Verify installation
logcli --version
```

#### Configure logcli

Set up your Loki connection:

```bash
# Local Loki instance
export LOKI_ADDR=http://localhost:3100

# Remote Loki (with auth)
export LOKI_ADDR=https://loki.example.com
export LOKI_USERNAME=your-username
export LOKI_PASSWORD=your-password

# Or use Grafana Cloud
export LOKI_ADDR=https://logs-prod-us-central1.grafana.net
export LOKI_USERNAME=your-user-id
export LOKI_PASSWORD=your-api-key
```

#### Query and Tail with Gonzo

```bash
# Basic query with follow
logcli query --follow '{app="myapp"}' --output=jsonl | gonzo

# Filter by namespace
logcli query --follow '{namespace="production"}' --output=jsonl | gonzo

# Multiple labels
logcli query --follow '{app="api",env="prod"}' --output=jsonl | gonzo

# With LogQL filters
logcli query --follow '{job="varlogs"} |= "error"' --output=jsonl | gonzo

# Time-based query
logcli query --since=1h '{app="myapp"}' --output=jsonl | gonzo
```

#### Common LogQL Queries

**By application**:

```bash
logcli query --follow '{app="nginx"}' --output=jsonl | gonzo
```

**By severity**:

```bash
logcli query --follow '{job="app"} |= "ERROR"' --output=jsonl | gonzo
```

**Exclude patterns**:

```bash
logcli query --follow '{app="api"} != "healthcheck"' --output=jsonl | gonzo
```

**JSON parsing**:

```bash
logcli query --follow '{app="api"} | json' --output=jsonl | gonzo
```

**Regular expressions**:

```bash
logcli query --follow '{app="web"} |~ "user.*login"' --output=jsonl | gonzo
```

### Method 2: Live Tail API

For more direct integration, use Loki's Live Tail API with Gonzo's custom format support.

#### Set Up Custom Format

Gonzo includes a built-in Loki format. Download the format file to your config directory:

```bash
# Create formats directory
mkdir -p ~/.config/gonzo/formats

# Download Loki format (if not included)
# Or create custom format based on Loki's JSON structure
```

#### Live Tail API Connection

```bash
# Direct connection to Loki's live tail endpoint
curl -s "http://localhost:3100/loki/api/v1/tail?query={app=\"myapp\"}" | gonzo --format=loki-stream

# With authentication
curl -s -u "$LOKI_USERNAME:$LOKI_PASSWORD" \
  "https://loki.example.com/loki/api/v1/tail?query={app=\"myapp\"}" | gonzo --format=loki-stream

# Multiple labels
curl -s "http://localhost:3100/loki/api/v1/tail?query={app=\"api\",env=\"prod\"}" | gonzo --format=loki-stream
```

#### Using a Shell Function

Create a convenient shell function for repeated use:

```bash
# Add to ~/.bashrc or ~/.zshrc
loki-tail() {
  local query="${1:-{app=\"myapp\"}}"
  logcli query --follow "$query" --output=jsonl | gonzo
}

# Usage
loki-tail '{namespace="production"}'
loki-tail '{app="api",level="error"}'
```

### Loki Log Format

Loki outputs logs in a specific JSON structure. Gonzo's Loki format handles:

```json
{
  "stream": {
    "app": "my-application",
    "namespace": "production",
    "pod": "my-app-abc123",
    "container": "app"
  },
  "values": [
    [
      "1705315805000000000",
      "2024-01-15T10:30:05Z ERROR Failed to connect to database"
    ]
  ]
}
```

**Gonzo extracts**:

* **Labels** (`stream`) → Attributes panel
* **Timestamp** → Log timestamp
* **Log line** → Message
* **Severity** → Detected from message

### Kubernetes + Loki Workflow

Combine Loki with Kubernetes for powerful log analysis:

#### 1. Query Kubernetes Logs in Loki

```bash
# All pods in namespace
logcli query --follow '{namespace="production"}' --output=jsonl | gonzo

# Specific deployment
logcli query --follow '{namespace="prod",app="api"}' --output=jsonl | gonzo

# With error filter
logcli query --follow '{namespace="prod"} |= "ERROR"' --output=jsonl | gonzo
```

#### 2. Compare with kubectl

Use both tools side by side:

```bash
# Terminal 1: Live kubectl logs
kubectl logs -f deployment/my-app | gonzo

# Terminal 2: Historical Loki logs
logcli query --since=1h '{app="my-app"}' --output=jsonl | gonzo
```

#### 3. Integration with Stern

For multi-pod analysis:

```bash
# Stern for live
stern --namespace production api --output json | gonzo

# Loki for historical
logcli query --since=1h '{namespace="production",app="api"}' --output=jsonl | gonzo
```

### Advanced Use Cases

#### Pipeline Validation

Verify that logs are flowing correctly into Loki:

```bash
# Check recent logs
logcli query --since=5m '{app="myapp"}' --output=jsonl | gonzo

# Verify all expected labels exist
logcli labels | grep app
logcli label app | grep myapp
```

#### Pattern Detection

Use Gonzo's pattern detection on Loki logs:

```bash
# Load logs and analyze patterns
logcli query --since=1h '{app="api"}' --output=jsonl | gonzo

# Press Enter on "Counts" panel to see:
# - Pattern extraction
# - Error clustering
# - Service distribution
```

#### AI Analysis

Combine Loki queries with AI analysis:

```bash
# Set up AI
export OPENAI_API_KEY="sk-your-key"

# Query and analyze
logcli query --follow '{app="api"} |= "ERROR"' --output=jsonl | gonzo --ai-model="gpt-4"

# In Gonzo:
# 1. Navigate to an error
# 2. Press Enter for details
# 3. Press 'i' for AI analysis
```

#### Time-Range Analysis

Analyze specific time periods:

```bash
# Last hour
logcli query --since=1h '{app="api"}' --output=jsonl | gonzo

# Specific time range
logcli query --from="2024-01-15T10:00:00Z" --to="2024-01-15T11:00:00Z" \
  '{app="api"}' --output=jsonl | gonzo

# Today's errors
logcli query --since=0h '{app="api"} |= "ERROR"' --output=jsonl | gonzo
```

### Configuration Examples

#### Persistent Configuration

Create a config for Loki integration:

```yaml
# ~/.config/gonzo/loki-config.yml
update-interval: 1s
log-buffer: 5000
memory-size: 20000
skin: dracula

# AI analysis for errors
ai-model: "gpt-4"
```

Use with:

```bash
logcli query --follow '{app="api"}' --output=jsonl | gonzo --config ~/.config/gonzo/loki-config.yml
```

#### Shell Aliases

Add to `~/.bashrc` or `~/.zshrc`:

```bash
# Loki + Gonzo aliases
alias loki-prod='logcli query --follow '"'"'{env="production"}'"'"' --output=jsonl | gonzo'
alias loki-errors='logcli query --follow '"'"'{level="error"}'"'"' --output=jsonl | gonzo'
alias loki-api='logcli query --follow '"'"'{app="api"}'"'"' --output=jsonl | gonzo'

# With AI
alias loki-ai='logcli query --follow --output=jsonl | gonzo --ai-model="gpt-4"'
```

### Troubleshooting

#### logcli Not Connecting

**Check Loki address**:

```bash
echo $LOKI_ADDR
curl $LOKI_ADDR/ready
```

**Test connection**:

```bash
logcli labels
logcli query --limit=5 '{job="varlogs"}'
```

#### No Logs Appearing in Gonzo

**Verify logcli output**:

```bash
# Test without Gonzo first
logcli query --follow '{app="myapp"}' --output=jsonl

# Check format
logcli query --limit=1 '{app="myapp"}' --output=jsonl | jq .
```

**Check Gonzo format**:

```bash
# Ensure using jsonl output
logcli query --follow '{app="myapp"}' --output=jsonl | gonzo

# Not json (wrong format)
logcli query --follow '{app="myapp"}' --output=json | gonzo
```

#### Authentication Issues

**Grafana Cloud**:

```bash
# Ensure credentials are set
echo $LOKI_USERNAME
echo $LOKI_PASSWORD

# Test auth
logcli labels
```

**TLS Issues**:

```bash
# Skip TLS verify for testing (not for production)
export LOKI_TLS_SKIP_VERIFY=true
```

#### Performance Issues

**Reduce query scope**:

```bash
# Add more specific labels
logcli query --follow '{app="api",namespace="prod"}' --output=jsonl | gonzo

# Limit throughput
logcli query --follow --limit=100 '{app="api"}' --output=jsonl | gonzo
```

**Adjust Gonzo buffers**:

```bash
logcli query --follow '{app="api"}' --output=jsonl | \
  gonzo --log-buffer=10000 --update-interval=2s
```

### Best Practices

#### 1. Use Specific Label Selectors

```bash
# ❌ Too broad
logcli query --follow '{}' --output=jsonl | gonzo

# ✅ Specific
logcli query --follow '{app="api",env="prod"}' --output=jsonl | gonzo
```

#### 2. Combine with Filters

```bash
# Filter in LogQL for efficiency
logcli query --follow '{app="api"} |= "ERROR" != "healthcheck"' --output=jsonl | gonzo
```

#### 3. Leverage Gonzo's Features

* **Pause** (`Space`) during investigation
* **Filter** (`/`) to narrow further
* **AI Analysis** (`i`) for complex errors
* **Patterns** (Counts modal) for trends

#### 4. Save Common Queries

```bash
# Create query scripts
cat > ~/loki-queries/prod-errors.sh << 'EOF'
#!/bin/bash
logcli query --follow '{env="production"} |= "ERROR"' --output=jsonl | gonzo
EOF

chmod +x ~/loki-queries/prod-errors.sh
```

### Complete Tutorial

For a comprehensive walkthrough of using Gonzo with Loki, including:

* Detailed setup instructions
* Real-world examples
* Advanced LogQL patterns
* Custom format configuration
* Integration patterns

**Read the full guide**: [Live Tailing Grafana Loki Logs with Gonzo](https://www.controltheory.com/blog/live-tailing-grafana-loki-logs-with-gonzo/)

### Related Resources

#### Documentation

* Custom Formats - Creating format parsers
* Kubernetes Integration - K8s log tailing
* AI Integration - AI-powered analysis

#### External Links

* [Grafana Loki Documentation](https://grafana.com/docs/loki/)
* [logcli Documentation](https://grafana.com/docs/loki/latest/tools/logcli/)
* [LogQL Guide](https://grafana.com/docs/loki/latest/logql/)

#### Blog Posts

* [Live Tailing Grafana Loki Logs with Gonzo](https://www.controltheory.com/blog/live-tailing-grafana-loki-logs-with-gonzo/)
* [Using Gonzo with k9s and Stern](https://www.controltheory.com/blog/using-gonzo-with-k9s-and-stern-supercharge-your-kubernetes-log-tailing/)

### Support

Having issues with Loki integration?

* Check Troubleshooting Guide
* Ask in [GitHub Discussions](https://github.com/control-theory/gonzo/discussions)
* Report bugs in [GitHub Issues](https://github.com/control-theory/gonzo/issues)

{% hint style="success" %}
**Pro Tip**: Use `logcli` with `--output=jsonl` (JSON Lines) for best compatibility with Gonzo. Each log entry is a separate JSON object on its own line.
{% endhint %}

{% hint style="info" %}
**Learn More**: Read the complete tutorial on [Live Tailing Grafana Loki Logs with Gonzo](https://www.controltheory.com/blog/live-tailing-grafana-loki-logs-with-gonzo/) for advanced patterns and real-world examples.
{% endhint %}


# Blogs, Resources & Videos

Learn more about Gonzo through in-depth blog posts, tutorials, and real-world use cases from the ControlTheory blog.

### Featured Blog Posts

#### :telescope: [Observability-Driven Development with Gonzo](https://www.controltheory.com/blog/observability-driven-development-with-gonzo/)

Learn how to tighten your development feedback loop by integrating observability directly into your coding workflow with Gonzo, a terminal-native log viewer.

Topics covered:

* Shifting from deploy-then-observe to observe-while-building
* Using Gonzo with Docker, Node.js, and local files
* Acting as an OTLP receiver for OpenTelemetry logs
* Validating instrumentation and log schemas before deployment

Good for: Developers looking to improve their feedback loops, teams adopting OpenTelemetry, anyone wanting to catch logging issues earlier in the development cycle

#### 📝 [A Tale of Two Log Types: Gonzo in Action](https://www.controltheory.com/blog/a-tale-of-two-log-types-gonzo-in-action/)

Learn how Gonzo handles different log formats and see real-world examples of parsing JSON, logfmt, and plain text logs.

**Topics covered**:

* Understanding different log formats
* Format detection and parsing
* Practical examples
* Best practices for structured logging

**Good for**: Users new to Gonzo, understanding log format handling

***

#### ☁️ [Vercel Logs Meet Gonzo](https://www.controltheory.com/blog/vercel-logs-meet-gonzo/)

Discover how to use Gonzo for analyzing Vercel deployment logs and debugging serverless applications.

**Topics covered**:

* Analyzing Vercel logs
* Debugging serverless functions
* Real-time log monitoring
* Troubleshooting deployments

**Good for**: Vercel users, serverless developers

***

#### 🔥 [Live Tailing Grafana Loki Logs with Gonzo](https://www.controltheory.com/blog/live-tailing-grafana-loki-logs-with-gonzo/)

Deep dive into integrating Gonzo with Grafana Loki for powerful log aggregation and live tailing.

**Topics covered**:

* Loki integration setup
* Custom format configuration
* Live log streaming
* LogQL query integration

**Good for**: Loki users, observability engineers

**Related docs**: Custom Formats

***

#### ☸️ [Using Gonzo with k9s and Stern: Supercharge Your Kubernetes Log Tailing](https://www.controltheory.com/blog/using-gonzo-with-k9s-and-stern-supercharge-your-kubernetes-log-tailing/)

Master Kubernetes log analysis by combining Gonzo with k9s and Stern for the ultimate debugging workflow.

**Topics covered**:

* Kubernetes log tailing
* Integration with k9s
* Using Stern with Gonzo
* Multi-pod log analysis
* Kubernetes troubleshooting workflows

**Good for**: Kubernetes operators, platform engineers, DevOps teams

**Related docs**: Kubernetes Integration

***

#### ☁️ [Gonzo: A Better Way to Tail AWS CloudWatch Logs](https://www.controltheory.com/blog/gonzo-a-better-way-to-tail-aws-cloudwatch-logs/)

Learn how Gonzo transforms CloudWatch log analysis with real-time visualization and AI-powered insights.

**Topics covered**:

* AWS CloudWatch integration
* Streaming CloudWatch logs
* Pattern detection in AWS logs
* Cost-effective log analysis
* CloudWatch Logs Insights alternative

**Good for**: AWS users, cloud engineers, SREs

**Related docs**: CloudWatch Integration

***

#### 🤖 [AI and a TUI: Practical Logging Tools for SREs](https://www.controltheory.com/blog/ai-and-a-tui-practical-logging-tools-for-sres/)

Explore how AI-powered log analysis in a terminal UI revolutionizes SRE workflows and incident response.

**Topics covered**:

* AI-powered log analysis
* SRE workflows and best practices
* Incident response improvements
* Practical AI use cases
* Terminal-first workflows

**Good for**: SREs, incident responders, operations teams

**Related docs**: AI Integration

***

### Browse All Blog Posts

Visit the [ControlTheory Blog](https://www.controltheory.com/blog/) for more articles, tutorials, and updates about Gonzo and log analysis.

**Popular topics**:

* Integration guides
* Use case studies
* Performance optimization
* Best practices
* Product updates
* Industry insights

### Use Case Studies

#### By Industry

**DevOps & SRE**:

* [AI and a TUI: Practical Logging Tools for SREs](https://www.controltheory.com/blog/ai-and-a-tui-practical-logging-tools-for-sres/)
* Incident response workflows
* Performance monitoring

**Cloud Platforms**:

* [Vercel Logs Meet Gonzo](https://www.controltheory.com/blog/vercel-logs-meet-gonzo/)
* [Gonzo: A Better Way to Tail AWS CloudWatch Logs](https://www.controltheory.com/blog/gonzo-a-better-way-to-tail-aws-cloudwatch-logs/)
* Multi-cloud deployments

**Container Orchestration**:

* [Using Gonzo with k9s and Stern](https://www.controltheory.com/blog/using-gonzo-with-k9s-and-stern-supercharge-your-kubernetes-log-tailing/)
* Docker container logs
* Service mesh debugging

**Observability**:

* [Live Tailing Grafana Loki Logs](https://www.controltheory.com/blog/live-tailing-grafana-loki-logs-with-gonzo/)
* OpenTelemetry integration
* Distributed tracing

### Video Tutorials

Check the videos on our YouTube channel here <https://www.youtube.com/@controltheoryinc>

### Community Resources

#### Community Blog Posts

Have you written about Gonzo? [Let us know](https://github.com/control-theory/gonzo/discussions) and we'll feature your post here!

#### Presentations & Talks

Share your Gonzo presentations with the community via [GitHub Discussions](https://github.com/control-theory/gonzo/discussions).

### Stay Updated

#### Newsletter

Get the latest Gonzo updates, tips, and tutorials delivered to your inbox.

[**Subscribe to ControlTheory Newsletter →**](https://www.controltheory.com/newsletter)

#### Social Media

**Follow us for updates**:

* Twitter/X: [@ControlTheoryHQ](https://x.com/Ctrl_Theory)
* LinkedIn: [ControlTheory](https://www.linkedin.com/company/controltheory)
* GitHub: [control-theory](https://github.com/control-theory)

### Request Content

#### What Would You Like to Learn?

Help us create content you need:

* [Request a tutorial](https://github.com/control-theory/gonzo/discussions)
* [Suggest a use case](https://github.com/control-theory/gonzo/discussions)
* [Share your story](mailto:hello@controltheory.com)

#### Topics We're Planning

**Upcoming blog posts**:

* Advanced pattern detection techniques
* Scaling Gonzo for enterprise use
* Custom format development guide
* Performance tuning deep dive
* Security best practices

### External Resources

#### Mentioned In

Gonzo has been featured in:

* [Awesome TUIs](https://github.com/rothgar/awesome-tuis)
* [Awesome CLI Agents](https://github.com/e2b-dev/awesome-cli-agents)

#### Related Tools

**Complementary tools mentioned in our blog**:

* [k9s](https://k9scli.io/) - Kubernetes TUI
* [stern](https://github.com/stern/stern) - Multi-pod log tailing
* [Grafana Loki](https://grafana.com/oss/loki/) - Log aggregation
* [OpenTelemetry](https://opentelemetry.io/) - Observability framework

### Documentation

#### Official Docs

* Quick Start Guide
* User Guide
* Integration Examples
* API & Architecture

#### GitHub

* [Repository](https://github.com/control-theory/gonzo)
* [Issues](https://github.com/control-theory/gonzo/issues)
* [Discussions](https://github.com/control-theory/gonzo/discussions)
* [Releases](https://github.com/control-theory/gonzo/releases)

### Support

#### Get Help

* [Documentation](https://docs.controltheory.com/gonzo)
* [GitHub Discussions](https://github.com/control-theory/gonzo/discussions)
* [Support Email](mailto:support@controltheory.com)

#### Commercial Support

Enterprise support and custom features available. Contact <partnerships@controltheory.com> for details.

***

### Explore More

**Latest blog posts**: [ControlTheory Blog](https://www.controltheory.com/blog/)

**Product updates**: Changelog

**Community**: [GitHub Discussions](https://github.com/control-theory/gonzo/discussions)

{% hint style="info" %}
**New blog posts weekly!** Check the [ControlTheory Blog](https://www.controltheory.com/blog/) regularly for new tutorials, use cases, and tips.
{% endhint %}

{% hint style="success" %}
**Share your story**: Using Gonzo in production? We'd love to feature your use case on our blog. [Get in touch →](mailto:hello@controltheory.com)
{% endhint %}


# Troubleshooting

Having issues with Gonzo? You're in the right place! This section helps you diagnose and resolve common problems quickly.

### Quick Problem Solver

#### Installation Issues

**Problem**: Can't install or run Gonzo\
**Solution**: Common Issues - Installation

#### Display Problems

**Problem**: Broken UI, garbled text, or no colors\
**Solution**: Common Issues - Display

#### Logs Not Showing

**Problem**: Gonzo starts but no logs appear\
**Solution**: Common Issues - Log Processing

#### AI Not Working

**Problem**: AI features don't respond or show errors\
**Solution**: AI-Specific Issues

#### Format Not Parsing

**Problem**: Logs appear as plain text instead of structured\
**Solution**: Log Format Issues

#### Performance Issues

**Problem**: High CPU/memory usage or slow performance\
**Solution**: Common Issues - Performance

### Troubleshooting Guides

#### Common Issues

The most frequently encountered problems and their solutions:

**Installation & Setup**:

* Command not found
* Permission denied
* Build failures
* Shell completion

**Display & UI**:

* Garbled characters
* Missing colors
* Mouse not working
* Terminal too small

**Log Processing**:

* No logs appearing
* Logs not following
* Mixed format issues
* Slow processing

**Performance**:

* High CPU usage
* High memory usage
* Slow with large files
* Dashboard not updating

**Configuration**:

* Config file not loading
* Environment variables ignored
* Settings not applied

#### AI-Specific Issues

Troubleshooting AI integration and analysis features:

**General AI Problems**:

* AI features not working
* No response from AI
* Model selection empty
* Analysis returns errors

**OpenAI Issues**:

* Authentication failed
* Model access denied
* Rate limit errors
* API key problems

**LM Studio Issues**:

* Cannot connect
* Model not loading
* Wrong model selected
* URL format errors

**Ollama Issues**:

* Service not running
* Model not found
* Connection timeouts
* URL configuration

**Performance**:

* AI analysis very slow
* High memory with AI
* Provider timeouts

#### Log Format Issues

Problems with log parsing and format detection:

**Format Detection**:

* Logs not being parsed
* Mixed format logs
* Attributes not extracted
* Wrong format detected

**JSON Problems**:

* Malformed JSON
* Multi-line JSON
* JSON with metadata prefix
* Escaped JSON strings

**Logfmt Issues**:

* Logfmt not detected
* Spaces in values
* Nested structures

**Plain Text**:

* No structure extracted
* Severity not detected
* Custom format needed

**OTLP Format**:

* OTLP logs not appearing
* Attributes missing
* Connection issues

**Custom Formats**:

* Format not working
* Regex not matching
* Parser errors

### Diagnostic Tools

#### Check Your Setup

**Verify installation**:

```bash
# Check version
gonzo --version

# Check help
gonzo --help

# Test with simple input
echo '{"level":"info","msg":"test"}' | gonzo
```

**Check environment**:

```bash
# View configuration
env | grep GONZO
env | grep OPENAI

# Check terminal
echo $TERM
echo $LANG
```

**Test components**:

```bash
# Test file input
gonzo -f test.log

# Test OTLP receiver
gonzo --otlp-enabled

# Test AI (if configured)
# Press 'i' on a log entry
```

#### Enable Debug Mode

Get detailed troubleshooting information:

```bash
# Run with verbose flag
gonzo -v -f application.log 2> debug.log

# Check debug output
tail -f debug.log
```

#### Collect System Information

When reporting issues, gather this information:

```bash
# System details
uname -a
echo $TERM

# Gonzo version
gonzo --version

# Go version (if building from source)
go version

# Configuration
cat ~/.config/gonzo/config.yml

# Environment variables
env | grep -E '(GONZO|OPENAI|TERM|LANG)'
```

### Common Patterns

#### Error Messages

**"command not found"**

**Meaning**: Gonzo is not in your PATH\
**Fix**: Installation Issues

**"permission denied"**

**Meaning**: File is not executable or not readable\
**Fix**: Permission Issues

**"invalid API key"**

**Meaning**: OpenAI API key is incorrect or missing\
**Fix**: AI Issues - Authentication

**"address already in use"**

**Meaning**: OTLP port is already taken\
**Fix**: Common Issues - OTLP

**"cannot parse JSON"**

**Meaning**: Log format is invalid\
**Fix**: Format Issues - JSON

#### Behavior Patterns

**Logs appear but no structure**

**Symptom**: Everything shows as plain text\
**Likely cause**: Format not detected\
**Solution**: Format Detection Issues

**Works locally, fails in container**

**Symptom**: Different behavior in Docker/Kubernetes\
**Likely cause**: Environment or terminal differences\
**Solution**: Check environment variables and terminal settings

**Intermittent failures**

**Symptom**: Sometimes works, sometimes doesn't\
**Likely cause**: Race condition or timing issue\
**Solution**: Check logs with verbose mode, report to GitHub

**Slow performance after time**

**Symptom**: Starts fast, gets slower over time\
**Likely cause**: Buffer full, memory pressure\
**Solution**: Performance Issues

### Troubleshooting Workflow

Follow this systematic approach:

#### 1. Identify the Problem

**Questions to ask**:

* What were you trying to do?
* What actually happened?
* When did it start happening?
* Can you reproduce it?
* What error messages appear?

#### 2. Check the Basics

**Quick checks**:

* ✅ Is Gonzo installed and in PATH?
* ✅ Is the log file readable?
* ✅ Is the terminal adequate?
* ✅ Are environment variables set?
* ✅ Is the config file valid?

#### 3. Review Relevant Guide

**Match your issue**:

* Installation/setup → Common Issues
* AI features → AI-Specific Issues
* Log parsing → Log Format Issues

#### 4. Try Solutions

**Test systematically**:

* Try simplest solution first
* Test one change at a time
* Document what works
* Verify the fix persists

#### 5. Get Help

**If still stuck**:

* Search [GitHub Issues](https://github.com/control-theory/gonzo/issues)
* Check [GitHub Discussions](https://github.com/control-theory/gonzo/discussions)
* Ask in community channels
* Open a new issue with details

### Prevention Tips

#### Avoid Common Mistakes

**Installation**:

* ✅ Use correct Go version (1.21+)
* ✅ Add Gonzo to PATH
* ✅ Set proper permissions

**Configuration**:

* ✅ Quote glob patterns
* ✅ Use valid YAML syntax
* ✅ Check file paths are absolute
* ✅ Verify API keys are correct

**Log Files**:

* ✅ Ensure files are readable
* ✅ Use consistent log format
* ✅ Avoid mixing formats in same file

**AI Integration**:

* ✅ Set API key correctly
* ✅ Use correct API base URL
* ✅ Check provider-specific requirements

**OTLP**:

* ✅ Use standard ports (4317, 4318)
* ✅ Match protocol (gRPC vs HTTP)
* ✅ Verify endpoint URLs

#### Best Practices

**For reliability**:

* Use config files for persistent settings
* Test with small samples first
* Monitor resource usage
* Keep Gonzo updated

**For debugging**:

* Enable verbose mode when testing
* Save debug output
* Create minimal reproduction cases
* Document your setup

**For performance**:

* Adjust buffer sizes appropriately
* Increase update interval if needed
* Filter logs before Gonzo when possible
* Monitor memory usage

### Getting Additional Help

#### Documentation

**Reference guides**:

* Common Issues - General troubleshooting
* AI-Specific Issues - AI integration
* Log Format Issues - Parsing problems
* Configuration Reference - Config options
* Environment Variables - Env var reference

#### Community Support

**Ask for help**:

* **GitHub Discussions**: <https://github.com/control-theory/gonzo/discussions>
* **GitHub Issues**: <https://github.com/control-theory/gonzo/issues>
* **Email**: <support@controltheory.com>

**When asking for help, include**:

* Gonzo version (`gonzo --version`)
* Operating system and version
* What you're trying to do
* What actually happens
* Error messages (if any)
* Minimal reproduction steps
* Sample logs (sanitized)

#### Reporting Bugs

**Before reporting**:

1. Search existing issues
2. Update to latest version
3. Test with minimal configuration
4. Create reproduction steps

**Good bug report includes**:

* Clear title
* Detailed description
* Steps to reproduce
* Expected vs actual behavior
* Environment details
* Logs and screenshots

**Template**:

```markdown
**Describe the bug**
A clear description of what the bug is.

**To Reproduce**
1. Run command '...'
2. Press key '...'
3. See error

**Expected behavior**
What you expected to happen.

**Environment:**
- OS: [e.g., macOS 14.0]
- Gonzo Version: [e.g., 0.1.6]
- Go Version: [e.g., 1.21.5]
- Terminal: [e.g., iTerm2]

**Logs/Screenshots**
[Attach relevant output]
```

[Open an issue →](https://github.com/control-theory/gonzo/issues/new)

### Known Issues

#### Current Known Issues

Check [GitHub Issues](https://github.com/control-theory/gonzo/issues) for the latest list of known issues.

**Common known issues**:

* Some older terminals have limited mouse support
* Very large OTLP batches may cause memory spikes
* Custom format regex can be slow with complex patterns

See Changelog for issues fixed in recent releases.

### Quick Reference

#### Troubleshooting Checklist

When something goes wrong:

* [ ] Check Gonzo is installed: `gonzo --version`
* [ ] Verify file/input exists and is readable
* [ ] Check terminal is adequate (80x24 min, 256 colors)
* [ ] Review environment variables: `env | grep GONZO`
* [ ] Test with minimal example
* [ ] Check relevant troubleshooting guide
* [ ] Enable verbose mode: `gonzo -v`
* [ ] Search existing issues
* [ ] Ask for help if needed

#### Most Common Fixes

**90% of issues are solved by**:

1. Adding Gonzo to PATH
2. Using proper file permissions
3. Setting environment variables correctly
4. Using valid configuration syntax
5. Updating to latest version

***

### Start Troubleshooting

Choose the guide that matches your problem:

**📋 Common Issues** - General problems and solutions

**🤖 AI-Specific Issues** - AI integration troubleshooting

**📝 Log Format Issues** - Parsing and format problems

{% hint style="info" %}
**Quick tip**: Most problems can be diagnosed by running `gonzo -v` to enable verbose mode. Check the output for detailed error messages.
{% endhint %}

{% hint style="success" %}
**Can't find your issue?** Search [GitHub Issues](https://github.com/control-theory/gonzo/issues) or [open a new one](https://github.com/control-theory/gonzo/issues/new) with details about your problem.
{% endhint %}


# Common Issues

This guide covers the most frequently encountered issues when using Gonzo and their solutions. For AI-specific or format-specific issues, see the dedicated troubleshooting pages.

### Installation Problems

#### Command Not Found After Installation

**Symptom**: Running `gonzo` returns "command not found" error.

**Causes & Solutions**:

1. **Go installation - PATH not configured**

   ```bash
   # Check if GOPATH/bin is in PATH
   echo $PATH | grep -q "$(go env GOPATH)/bin" && echo "Found" || echo "Missing"

   # Fix: Add to your shell profile
   echo 'export PATH=$PATH:$(go env GOPATH)/bin' >> ~/.bashrc
   source ~/.bashrc

   # Or for zsh
   echo 'export PATH=$PATH:$(go env GOPATH)/bin' >> ~/.zshrc
   source ~/.zshrc
   ```
2. **Binary installation - not in PATH**

   ```bash
   # Move to standard location
   sudo mv gonzo /usr/local/bin/

   # Or add current directory to PATH
   export PATH=$PATH:$(pwd)
   ```
3. **Verify installation**

   ```bash
   which gonzo
   gonzo --version
   ```

#### Permission Denied When Running Binary

**Symptom**: `permission denied` when trying to execute gonzo.

**Solution**:

```bash
# Make executable
chmod +x gonzo

# If in system directory
sudo chmod +x /usr/local/bin/gonzo

# Verify permissions
ls -l $(which gonzo)
# Should show: -rwxr-xr-x
```

#### Build Failures

**Symptom**: `go install` or `make build` fails.

**Common causes**:

1. **Go version too old**

   ```bash
   # Check version (need 1.21+)
   go version

   # Update via Homebrew
   brew upgrade go

   # Or download from https://golang.org/dl/
   ```
2. **Missing dependencies**

   ```bash
   # Clean and retry
   go clean -modcache
   go mod download
   go install github.com/control-theory/gonzo/cmd/gonzo@latest
   ```
3. **Network issues**

   ```bash
   # Use proxy if behind firewall
   export GOPROXY=https://proxy.golang.org,direct
   go install github.com/control-theory/gonzo/cmd/gonzo@latest
   ```

### Display Issues

#### Garbled or Broken Interface

**Symptom**: Strange characters, broken borders, or corrupted display.

**Solutions**:

1. **Check terminal compatibility**
   * ✅ Works well: iTerm2, Alacritty, Windows Terminal, GNOME Terminal, Kitty
   * ⚠️ May have issues: Very old terminals, basic xterm
2. **Enable UTF-8 encoding**

   ```bash
   # Add to shell profile
   export LANG=en_US.UTF-8
   export LC_ALL=en_US.UTF-8

   # Verify
   locale
   ```
3. **Check TERM variable**

   ```bash
   # Should show 256 color support
   echo $TERM
   # Should be: xterm-256color, screen-256color, etc.

   # Set if incorrect
   export TERM=xterm-256color
   ```
4. **Use appropriate font**
   * Install a font with good Unicode support
   * Recommended: JetBrains Mono, Fira Code, Cascadia Code, Hack

#### No Colors Displayed

**Symptom**: All text appears in same color, no syntax highlighting.

**Solutions**:

1. **Check color support**

   ```bash
   # Test color capability
   tput colors
   # Should show 256
   ```
2. **Force color mode**

   ```bash
   export TERM=xterm-256color
   gonzo -f logs.log
   ```
3. **Check NO\_COLOR variable**

   ```bash
   # Unset if present
   unset NO_COLOR

   # Verify it's gone
   env | grep NO_COLOR
   ```
4. **Try different skin**

   ```bash
   # Some terminals work better with specific skins
   gonzo --skin=github-light -f logs.log
   ```

#### Terminal Too Small

**Symptom**: Interface is cramped or panels overlap.

**Solution**:

Gonzo requires minimum terminal size of 80x24 characters.

```bash
# Check current size
tput cols  # Width
tput lines # Height

# Resize terminal to at least 80x24
# Or use fullscreen mode: Cmd/Ctrl + Enter (terminal dependent)
```

**Recommended**: 120x40 or larger for best experience.

#### Mouse Not Working

**Symptom**: Clicking doesn't select items or switch panels.

**Solutions**:

1. **Verify terminal supports mouse**
   * Most modern terminals do
   * Check terminal settings/preferences
2. **Use keyboard navigation instead**

   ```
   Tab         - Switch panels
   ↑↓ or k/j   - Navigate items
   Enter       - Select/open
   ```
3. **Known limitations**:
   * SSH sessions may not pass mouse events
   * Tmux/Screen require special configuration
   * Some older terminals lack mouse support

### Log Processing Issues

#### No Logs Appearing

**Symptom**: Gonzo starts but dashboard remains empty.

**Diagnosis & Solutions**:

1. **Verify input source exists**

   ```bash
   # For files
   ls -la application.log
   file application.log

   # Check file has content
   wc -l application.log
   head application.log
   ```
2. **Check file permissions**

   ```bash
   # Ensure readable
   chmod +r application.log

   # Verify
   cat application.log | head
   ```
3. **Test with simple input**

   ```bash
   # Create test file
   echo '{"level":"info","message":"test"}' | gonzo

   # If this works, issue is with your log file
   ```
4. **Check for active filters**
   * Press `ESC` to clear any filters
   * Look for filter indicator in status bar
5. **Verify stdin is producing output**

   ```bash
   # Test the source directly
   kubectl logs deployment/app | head

   # If empty, source is the problem
   ```

#### Logs Appear Truncated

**Symptom**: Long log lines are cut off or abbreviated.

**Solutions**:

1. **Use horizontal scrolling**

   ```
   ← → or h l  - Scroll left/right
   ```
2. **Open detail view**

   ```
   Enter - View full log entry
   ```
3. **Increase terminal width**
   * Make terminal wider
   * Use full screen mode

#### Mixed Format Logs Not Parsing

**Symptom**: Some logs parse correctly, others show as plain text.

**Explanation**: Gonzo detects format per line. Mixed format files will show inconsistent parsing.

**Solutions**:

1. **Pre-filter by format**

   ```bash
   # Extract only JSON lines
   grep '^{' mixed.log | gonzo

   # Or use jq
   cat mixed.log | jq -c 'select(type == "object")' | gonzo
   ```
2. **Use custom format**

   ```bash
   gonzo --format=my-custom-format -f logs.txt
   ```
3. **Accept mixed display**
   * Structured logs: parsed as JSON/logfmt
   * Unstructured logs: shown as plain text
   * Both viewable, just different presentation

#### Logs Not Following in Real-Time

**Symptom**: Using `--follow` but new logs don't appear.

**Diagnosis**:

1. **Verify file is being written**

   ```bash
   # In another terminal
   tail -f /var/log/app.log

   # Or watch file size
   watch -n 1 'ls -lh /var/log/app.log'
   ```
2. **Check auto-scroll status**
   * Press `End` to jump to latest and resume auto-scroll
   * Look for `FOLLOWING` indicator in status bar
3. **Verify Gonzo isn't paused**
   * Press `Space` to unpause if showing `⏸ PAUSED`
4. **Test follow with known-working source**

   ```bash
   # In terminal 1
   gonzo -f /tmp/test.log --follow

   # In terminal 2
   while true; do echo "test $(date)" >> /tmp/test.log; sleep 1; done
   ```

#### Log Rotation Issues

**Symptom**: Logs stop appearing after log rotation.

**Explanation**: When files are rotated (moved/renamed), Gonzo may lose the file handle.

**Solutions**:

1. **Restart Gonzo after rotation**

   ```bash
   # Simple approach
   gonzo -f /var/log/app.log --follow
   ```
2. **Use stdin with tail**

   ```bash
   # tail -F follows through rotation
   tail -F /var/log/app.log | gonzo
   ```
3. **For production**: Use OTLP or log shipping

   ```bash
   # More reliable for long-running monitoring
   gonzo --otlp-enabled
   ```

### Performance Issues

#### High CPU Usage

**Symptom**: Gonzo consumes excessive CPU.

**Causes & Solutions**:

1. **Very high log volume**

   ```bash
   # Reduce update frequency
   gonzo -f logs.log --update-interval=5s

   # Default is 1s; try 2s, 5s, or 10s
   ```
2. **Large buffer processing**

   ```bash
   # Reduce buffer sizes
   gonzo -f logs.log --log-buffer=500 --memory-size=5000
   ```
3. **Complex regex filters**
   * Simplify regex patterns
   * Use simpler string matches when possible
4. **AI analysis running**
   * AI queries can be CPU intensive
   * Wait for analysis to complete
   * Use lighter models (gpt-3.5-turbo vs gpt-4)

#### High Memory Usage

**Symptom**: Gonzo consumes too much RAM.

**Solutions**:

1. **Reduce log buffer**

   ```bash
   # Default: 1000 entries
   gonzo -f logs.log --log-buffer=500
   ```
2. **Reduce frequency tracking**

   ```bash
   # Default: 10000 words
   gonzo -f logs.log --memory-size=5000
   ```
3. **Process logs in chunks**

   ```bash
   # Instead of entire file
   tail -n 10000 large.log | gonzo

   # Or specific time range
   grep "2024-01-15" large.log | gonzo
   ```
4. **Use config file for persistent settings**

   ```yaml
   # ~/.config/gonzo/config.yml
   log-buffer: 500
   memory-size: 5000
   ```

#### Slow Performance with Large Files

**Symptom**: Gonzo is sluggish when loading large log files.

**Solutions**:

1. **Pre-filter before Gonzo**

   ```bash
   # Filter by severity
   grep -E "(ERROR|WARN)" large.log | gonzo

   # Filter by time range
   awk '/10:00/,/11:00/' large.log | gonzo

   # Last N lines
   tail -n 5000 large.log | gonzo
   ```
2. **Use streaming instead of file**

   ```bash
   # Stream rather than load entire file
   cat large.log | gonzo
   ```
3. **Increase update interval**

   ```bash
   gonzo -f large.log --update-interval=3s
   ```
4. **Split large files**

   ```bash
   # Split into smaller files
   split -l 10000 large.log chunk_

   # Analyze chunks individually
   gonzo -f chunk_aa
   ```

#### Dashboard Not Updating

**Symptom**: Interface appears frozen, no updates.

**Diagnosis**:

1. **Check if paused**
   * Look for `⏸ PAUSED` in status bar
   * Press `Space` to unpause
2. **Verify input is flowing**

   ```bash
   # Check source directly
   tail -f /var/log/app.log
   ```
3. **Check update interval**

   ```bash
   # May be set very high
   # Press 'u' to cycle to faster update
   ```
4. **Try reset**

   ```bash
   # Press 'r' to reset dashboard
   ```
5. **Restart Gonzo**
   * Sometimes a clean restart resolves issues
   * `q` to quit, then restart

### File Input Issues

#### Glob Pattern Not Working

**Symptom**: `gonzo -f "/var/log/*.log"` doesn't find expected files.

**Solutions**:

1. **Always quote glob patterns**

   ```bash
   # ✅ Correct - Gonzo handles expansion
   gonzo -f "/var/log/*.log"

   # ❌ Wrong - Shell expands before Gonzo sees it
   gonzo -f /var/log/*.log
   ```
2. **Verify files exist**

   ```bash
   ls /var/log/*.log
   ```
3. **Check permissions**

   ```bash
   # Ensure files are readable
   ls -la /var/log/*.log
   ```
4. **Use absolute paths**

   ```bash
   # More reliable than relative
   gonzo -f "/var/log/*.log"  # ✅
   gonzo -f "../logs/*.log"    # May have issues
   ```

#### Multiple File Sources Not Merging

**Symptom**: Only seeing logs from one file when multiple specified.

**Solution**:

```bash
# Specify each file/pattern separately
gonzo -f file1.log -f file2.log -f file3.log

# Multiple patterns work too
gonzo -f "/var/log/app/*.log" -f "/var/log/nginx/*.log"
```

Logs will be merged in the order received (by timestamp if available).

#### Cannot Read File - Permission Denied

**Symptom**: Error message about insufficient permissions.

**Solutions**:

1. **Check file permissions**

   ```bash
   ls -la /var/log/app.log
   ```
2. **Add read permission**

   ```bash
   chmod +r /var/log/app.log
   ```
3. **Run with appropriate user**

   ```bash
   # If log requires special permissions
   sudo gonzo -f /var/log/secure
   ```
4. **Copy to accessible location**

   ```bash
   # Last resort
   cp /var/log/app.log ~/app.log
   gonzo -f ~/app.log
   ```

### Configuration Issues

#### Config File Not Loading

**Symptom**: Settings in config file are ignored.

**Diagnosis**:

1. **Check config location**

   ```bash
   # Default location
   ls -la ~/.config/gonzo/config.yml

   # Should exist and be readable
   ```
2. **Verify YAML syntax**

   ```bash
   # Use yamllint if available
   yamllint ~/.config/gonzo/config.yml

   # Or check with cat
   cat ~/.config/gonzo/config.yml
   ```
3. **Common YAML mistakes**

   ```yaml
   # ❌ Wrong - underscores not supported
   log_buffer: 2000
   update_interval: 2s

   # ✅ Correct - use hyphens
   log-buffer: 2000
   update-interval: 2s
   ```
4. **Specify config explicitly**

   ```bash
   gonzo --config ~/.config/gonzo/config.yml -f logs.log
   ```

#### Environment Variables Not Working

**Symptom**: Environment variables like `GONZO_FILES` are ignored.

**Solutions**:

1. **Verify export**

   ```bash
   # Check if set
   env | grep GONZO

   # Set if missing
   export GONZO_FILES="/var/log/app.log"
   ```
2. **Add to shell profile**

   ```bash
   # For persistent settings
   echo 'export GONZO_FILES="/var/log/app.log"' >> ~/.bashrc
   source ~/.bashrc
   ```
3. **Command line flags override env vars**

   ```bash
   # Flag takes precedence
   GONZO_FILES="file1.log" gonzo -f file2.log
   # Will use file2.log, not file1.log
   ```

### Getting Additional Help

#### Enable Verbose Logging

For detailed troubleshooting:

```bash
# Run with verbose flag
gonzo -v -f application.log 2> gonzo-debug.log

# Check debug output
cat gonzo-debug.log
```

#### Gather System Information

When reporting issues, collect:

```bash
# System info
uname -a
echo $TERM
echo $SHELL

# Gonzo version
gonzo --version

# Go version (if relevant)
go version

# Terminal info
echo $COLUMNS x $LINES
```

#### Test with Minimal Example

Create a minimal reproduction:

```bash
# Simple test case
echo '{"level":"info","message":"test log"}' > test.log
gonzo -f test.log

# If this works, issue is with your specific logs
```

### Related Resources

* **AI-Specific Issues** - Troubleshooting AI integration
* **Log Format Issues** - Problems with log parsing
* [**GitHub Issues**](https://github.com/control-theory/gonzo/issues) - Report bugs or request features

{% hint style="info" %}
**Can't find your issue?** Search existing [GitHub issues](https://github.com/control-theory/gonzo/issues) or [open a new one](https://github.com/control-theory/gonzo/issues/new).
{% endhint %}


# AI-Specific Issues

Troubleshooting guide for AI integration problems in Gonzo. This covers issues with OpenAI, LM Studio, Ollama, and other AI providers.

### General AI Issues

#### AI Features Not Working

**Symptom**: Pressing `i` or `c` does nothing, or shows "AI not configured" error.

**Diagnosis & Solutions**:

1. **Verify API key is set**

   ```bash
   # Check if key exists
   echo $OPENAI_API_KEY
   # Should show: sk-... or your provider's key format

   # If empty, set it
   export OPENAI_API_KEY="sk-your-actual-key-here"
   ```
2. **Test API key validity**

   ```bash
   # For OpenAI
   curl https://api.openai.com/v1/models \
     -H "Authorization: Bearer $OPENAI_API_KEY"

   # Should return list of models, not an error
   ```
3. **Specify model explicitly**

   ```bash
   # Instead of auto-select
   gonzo -f logs.log --ai-model="gpt-3.5-turbo"
   ```
4. **Check API base URL**

   ```bash
   # Should be set for custom providers
   echo $OPENAI_API_BASE

   # Unset for OpenAI (uses default)
   unset OPENAI_API_BASE
   ```

#### No Response from AI

**Symptom**: AI analysis appears to hang or never returns.

**Causes & Solutions**:

1. **Network connectivity**

   ```bash
   # Test internet connection
   ping api.openai.com

   # Test API endpoint
   curl -I https://api.openai.com
   ```
2. **API rate limits**
   * Wait a minute and try again
   * Check your provider's rate limit status
   * Use a different model (some have higher limits)
3. **Large log context**
   * Very long logs may timeout
   * Try analyzing smaller log entries
   * Increase timeout (provider dependent)
4. **Provider service outage**

   ```bash
   # Check status
   # OpenAI: https://status.openai.com
   # Provider-specific status pages
   ```

#### Model Selection Modal Empty

**Symptom**: Pressing `m` shows empty modal or "No models available".

**Diagnosis & Solutions**:

1. **Verify AI service is configured**

   ```bash
   # Check all AI-related env vars
   env | grep OPENAI

   # Should show:
   # OPENAI_API_KEY=...
   # OPENAI_API_BASE=... (if using custom provider)
   ```
2. **Test API endpoint**

   ```bash
   # For OpenAI
   curl https://api.openai.com/v1/models \
     -H "Authorization: Bearer $OPENAI_API_KEY" | jq '.data[].id'

   # For LM Studio
   curl http://localhost:1234/v1/models | jq '.data[].id'

   # For Ollama
   curl http://localhost:11434/api/tags | jq '.models[].name'
   ```
3. **Provider-specific fixes**:
   * See sections below for each provider

#### AI Analysis Returns Errors

**Symptom**: Error messages when attempting AI analysis.

**Common Error Messages**:

1. **"Invalid API key"**
   * Key is incorrect or expired
   * Regenerate key from provider dashboard
   * Ensure no extra spaces in key
2. **"Model not found"**
   * Specified model doesn't exist or you don't have access
   * Use auto-select instead: remove `--ai-model` flag
   * Check available models: press `m` in Gonzo
3. **"Rate limit exceeded"**
   * You've hit API rate limits
   * Wait and try again
   * Upgrade your provider plan
   * Switch to local model (Ollama/LM Studio)
4. **"Context length exceeded"**
   * Log entry is too long for model
   * Try analyzing a shorter log
   * Use a model with larger context window (gpt-4 vs gpt-3.5)

### OpenAI Issues

#### Authentication Failed

**Symptom**: "Incorrect API key provided" or 401 errors.

**Solutions**:

1. **Verify key format**

   ```bash
   # OpenAI keys start with sk-
   echo $OPENAI_API_KEY | grep -E '^sk-'
   ```
2. **Check for whitespace**

   ```bash
   # Trim any whitespace
   export OPENAI_API_KEY=$(echo $OPENAI_API_KEY | tr -d ' \t\n\r')
   ```
3. **Generate new key**
   * Go to <https://platform.openai.com/api-keys>
   * Create new key
   * Update environment variable
4. **Verify account status**
   * Check billing at <https://platform.openai.com/account/billing>
   * Ensure you have credits or valid payment method

#### Model Access Denied

**Symptom**: "You don't have access to model gpt-4" or similar.

**Solutions**:

1. **Use available model**

   ```bash
   # Try gpt-3.5-turbo (widely available)
   gonzo -f logs.log --ai-model="gpt-3.5-turbo"
   ```
2. **Check model availability**

   ```bash
   curl https://api.openai.com/v1/models \
     -H "Authorization: Bearer $OPENAI_API_KEY" \
     | jq '.data[].id'
   ```
3. **GPT-4 access**
   * GPT-4 requires separate approval
   * Check <https://platform.openai.com/account/limits>
   * Use gpt-3.5-turbo as alternative

#### Rate Limit Errors

**Symptom**: "Rate limit exceeded" or 429 errors.

**Solutions**:

1. **Wait and retry**
   * Limits reset after time period
   * Wait 1-2 minutes
2. **Use lower tier model**

   ```bash
   # gpt-3.5-turbo has higher rate limits
   gonzo -f logs.log --ai-model="gpt-3.5-turbo"
   ```
3. **Upgrade plan**
   * Free tier has low limits
   * Pay-as-you-go has higher limits
   * Check <https://platform.openai.com/account/limits>
4. **Switch to local model**
   * Use Ollama or LM Studio (no rate limits)
   * See sections below

### LM Studio Issues

#### Cannot Connect to LM Studio

**Symptom**: Connection refused or timeout errors.

**Diagnosis & Solutions**:

1. **Verify LM Studio is running**
   * Open LM Studio application
   * Ensure a model is loaded
   * Check server is started (green indicator)
2. **Check URL format** (CRITICAL)

   ```bash
   # ✅ CORRECT - must include /v1
   export OPENAI_API_BASE="http://localhost:1234/v1"

   # ❌ WRONG - missing /v1
   export OPENAI_API_BASE="http://localhost:1234"
   ```
3. **Test server is responding**

   ```bash
   curl http://localhost:1234/v1/models

   # Should return JSON with model list
   ```
4. **Check port number**

   ```bash
   # Default is 1234, verify in LM Studio settings
   # If different, update URL
   export OPENAI_API_BASE="http://localhost:PORT/v1"
   ```
5. **Firewall issues**

   ```bash
   # Ensure port is open
   # macOS
   sudo lsof -i :1234

   # Linux
   sudo netstat -tulpn | grep 1234
   ```

#### LM Studio Model Not Loading

**Symptom**: Server starts but model doesn't load.

**Solutions**:

1. **Check model is downloaded**
   * In LM Studio, verify model is in "My Models"
   * Download if missing
2. **Insufficient RAM**
   * Large models need significant RAM
   * Try smaller model variant
   * Close other applications
3. **Restart LM Studio**
   * Quit completely
   * Reopen and load model fresh

#### Wrong Model Selected in Gonzo

**Symptom**: Gonzo uses wrong LM Studio model.

**Solutions**:

1. **Specify exact model name**

   ```bash
   # List available models
   curl http://localhost:1234/v1/models | jq '.data[].id'

   # Use exact name
   gonzo -f logs.log --ai-model="openai/gpt-oss-120b"
   ```
2. **Load only one model in LM Studio**
   * Unload other models to avoid confusion
   * Load desired model only
3. **Use model selection in Gonzo**
   * Start Gonzo
   * Press `m` to select model interactively

### Ollama Issues

#### Ollama Service Not Running

**Symptom**: Connection refused to localhost:11434.

**Solutions**:

1. **Start Ollama service**

   ```bash
   ollama serve

   # Or as background service (Linux)
   systemctl start ollama

   # macOS
   # Ollama usually runs as application
   ```
2. **Verify service is running**

   ```bash
   curl http://localhost:11434/api/tags

   # Should return list of models
   ```
3. **Check for port conflicts**

   ```bash
   # See what's using port 11434
   lsof -i :11434
   ```

#### Model Not Found

**Symptom**: "Model 'llama3' not found" or similar.

**Solutions**:

1. **List installed models**

   ```bash
   ollama list
   ```
2. **Pull missing model**

   ```bash
   # Pull specific model
   ollama pull llama3

   # Or the one you need
   ollama pull mistral
   ollama pull gpt-oss:20b
   ```
3. **Use exact model name**

   ```bash
   # Include tag if needed
   gonzo -f logs.log --ai-model="llama3:8b"
   ```

#### Wrong Ollama URL Format

**Symptom**: Errors about invalid endpoint or /v1 path.

**CRITICAL**: Ollama URL format is different from OpenAI/LM Studio.

```bash
# ✅ CORRECT - NO /v1 suffix for Ollama
export OPENAI_API_BASE="http://localhost:11434"

# ❌ WRONG - don't add /v1
export OPENAI_API_BASE="http://localhost:11434/v1"
```

#### Ollama API Timeouts

**Symptom**: Analysis hangs or times out with Ollama.

**Solutions**:

1. **Check model size vs RAM**

   ```bash
   # Large models need more RAM
   # Check system memory
   free -h  # Linux
   vm_stat  # macOS
   ```
2. **Use smaller model variant**

   ```bash
   # Instead of 70b, try 13b or 7b
   ollama pull llama3:8b
   gonzo -f logs.log --ai-model="llama3:8b"
   ```
3. **Reduce concurrent requests**
   * Only analyze one log at a time
   * Wait for previous analysis to complete
4. **Check GPU utilization**

   ```bash
   # If using GPU
   nvidia-smi  # NVIDIA GPU

   # May need to configure Ollama for GPU
   ```

### Custom Provider Issues

#### Custom API Endpoint Not Working

**Symptom**: Errors connecting to custom OpenAI-compatible API.

**Solutions**:

1. **Verify endpoint URL**

   ```bash
   # Check URL is correct and accessible
   curl $OPENAI_API_BASE/models
   ```
2. **Check authentication method**

   ```bash
   # Most use Bearer token
   curl $OPENAI_API_BASE/models \
     -H "Authorization: Bearer $OPENAI_API_KEY"
   ```
3. **Verify API compatibility**
   * Must be OpenAI-compatible API
   * Should support /v1/chat/completions endpoint
4. **Test with known working example**

   ```bash
   curl $OPENAI_API_BASE/v1/chat/completions \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer $OPENAI_API_KEY" \
     -d '{
       "model": "gpt-3.5-turbo",
       "messages": [{"role": "user", "content": "Hello"}]
     }'
   ```

#### SSL/TLS Certificate Errors

**Symptom**: Certificate verification failed errors.

**Solutions**:

1. **For local development only**

   ```bash
   # Disable certificate verification (NOT for production)
   export OPENAI_SKIP_VERIFY=true
   ```
2. **Install proper certificates**

   ```bash
   # Better: Fix the certificate issue
   # Install CA certificate for your provider
   ```
3. **Use HTTP for local services**

   ```bash
   # If running locally, use http instead of https
   export OPENAI_API_BASE="http://localhost:8080/v1"
   ```

### Performance Issues

#### AI Analysis Very Slow

**Symptom**: AI analysis takes very long to complete.

**Causes & Solutions**:

1. **Using large model**

   ```bash
   # Switch to faster model
   gonzo -f logs.log --ai-model="gpt-3.5-turbo"  # Fast
   # Instead of gpt-4 (slower but better)
   ```
2. **Network latency**
   * Use local model (Ollama/LM Studio)
   * Check internet speed
3. **Large log context**
   * Analyzing very long logs takes time
   * Break into smaller chunks
4. **Local model on CPU**
   * Local models slow on CPU
   * Use GPU if available
   * Use smaller model variants

#### AI Consumes Too Much Memory

**Symptom**: High memory usage when using AI features.

**Solutions**:

1. **Use cloud API instead of local**

   ```bash
   # Cloud APIs don't use local RAM
   export OPENAI_API_KEY="sk-..."
   unset OPENAI_API_BASE
   ```
2. **Use smaller local model**

   ```bash
   # Instead of 70b parameter model
   ollama pull llama3:8b  # Much smaller
   ```
3. **Close other applications**
   * Local LLMs need substantial RAM
   * Close unnecessary programs

### Debugging AI Issues

#### Enable Verbose Logging

```bash
# See detailed AI interactions
gonzo -v -f logs.log --ai-model="gpt-3.5-turbo" 2> ai-debug.log

# Check debug output
cat ai-debug.log
```

#### Test AI Provider Independently

Before using with Gonzo, verify your AI setup works:

**OpenAI**:

```bash
curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-3.5-turbo",
    "messages": [{"role": "user", "content": "Say hello"}]
  }'
```

**LM Studio**:

```bash
curl http://localhost:1234/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "local-model",
    "messages": [{"role": "user", "content": "Say hello"}]
  }'
```

**Ollama**:

```bash
curl http://localhost:11434/api/generate \
  -d '{
    "model": "llama3",
    "prompt": "Say hello"
  }'
```

#### Quick Reference: Provider URLs

| Provider  | Base URL                 | /v1 Suffix?      | Default Port |
| --------- | ------------------------ | ---------------- | ------------ |
| OpenAI    | <https://api.openai.com> | ✅ Yes (auto)     | 443 (HTTPS)  |
| LM Studio | <http://localhost:1234>  | ✅ Yes (must add) | 1234         |
| Ollama    | <http://localhost:11434> | ❌ No             | 11434        |
| Custom    | (varies)                 | ⚠️ Usually yes   | (varies)     |

### Getting Help

#### Provide This Info When Reporting AI Issues

```bash
# Provider info
echo "Provider: [OpenAI/LM Studio/Ollama/Other]"
echo "API Base: $OPENAI_API_BASE"
echo "Model: [model name]"

# Test connection
curl -I $OPENAI_API_BASE/models

# Gonzo version
gonzo --version

# Error message
# [paste complete error]
```

#### Related Resources

* **Common Issues** - General troubleshooting
* **AI Setup Guide** - Initial configuration
* **AI Providers Guide** - Provider-specific setup
* [**GitHub Issues**](https://github.com/control-theory/gonzo/issues) - Report bugs

{% hint style="warning" %}
**Never share your actual API keys** when reporting issues. Use placeholders like `sk-...` or `<redacted>`.
{% endhint %}


# Log Format Issues

Troubleshooting guide for log parsing and format detection problems in Gonzo.

### Format Detection Issues

#### Logs Not Being Parsed

**Symptom**: Structured logs appear as plain text instead of being parsed.

**Diagnosis**:

Gonzo automatically detects formats per line based on these rules:

* **JSON**: Lines starting with `{`
* **Logfmt**: Lines containing `key=value` patterns
* **Plain text**: Everything else

**Solutions**:

1. **Verify JSON is valid**

   ```bash
   # Test each line individually
   head -1 logs.json | jq .

   # If error, JSON is malformed
   ```
2. **Check line starts with `{`**

   ```bash
   # JSON must start with opening brace
   head logs.json

   # ✅ Good: {"level":"info"...
   # ❌ Bad: 2024-01-15 {"level":"info"...
   ```
3. **Inspect logfmt format**

   ```bash
   # Should have key=value pairs
   head logs.txt

   # ✅ Good: level=info service=api msg="started"
   # ❌ Bad: [INFO] service api started
   ```
4. **Use custom format for non-standard logs**

   ```bash
   gonzo --format=my-custom-format -f logs.txt
   ```

#### Mixed Format Logs

**Symptom**: Some lines parse correctly, others don't.

**Explanation**: Gonzo detects format per line, so mixed formats will have inconsistent parsing.

**Example**:

```
{"level":"info","msg":"API started"}     ← Parsed as JSON
level=info msg="processing request"     ← Parsed as logfmt  
[ERROR] Connection timeout              ← Plain text
```

**Solutions**:

1. **Accept mixed display**
   * This is expected behavior
   * Each format renders appropriately
2. **Pre-filter to single format**

   ```bash
   # Extract only JSON lines
   grep '^{' mixed.log | gonzo

   # Or only logfmt
   grep '=' mixed.log | gonzo
   ```
3. **Convert to uniform format**

   ```bash
   # Convert all to JSON with jq
   cat mixed.log | jq -R -c '. | fromjson? // {"message": .}' | gonzo
   ```

#### Attributes Not Extracted

**Symptom**: Logs parse but attributes panel is empty.

**Causes & Solutions**:

1. **Plain text logs have no structured attributes**
   * Plain text can't be parsed into fields
   * Only JSON and logfmt have attributes
2. **Check JSON structure**

   ```bash
   # Verify JSON has expected fields
   head -1 logs.json | jq .

   # Should show key-value pairs
   ```
3. **Nested JSON**

   ```json
   {
     "log": {
       "level": "info",
       "service": "api"
     }
   }
   ```

   * Gonzo extracts nested attributes
   * May need to check nested paths
4. **Missing common attribute names**
   * Gonzo looks for common fields: `level`, `service`, `host`, etc.
   * Custom fields may not be highlighted

### JSON Issues

#### Malformed JSON

**Symptom**: JSON logs show as plain text or cause errors.

**Common JSON Issues**:

1. **Trailing commas**

   ```json
   {"level":"info","msg":"test",}  ❌ Invalid
   {"level":"info","msg":"test"}   ✅ Valid
   ```
2. **Single quotes instead of double**

   ```json
   {'level':'info'}     ❌ Invalid
   {"level":"info"}     ✅ Valid
   ```
3. **Unescaped quotes in strings**

   ```json
   {"msg":"He said "hi""}           ❌ Invalid
   {"msg":"He said \"hi\""}         ✅ Valid
   {"msg":"He said 'hi'"}           ✅ Valid (single quotes in string)
   ```
4. **Missing quotes on keys**

   ```json
   {level:"info"}       ❌ Invalid
   {"level":"info"}     ✅ Valid
   ```

**Validate & Fix**:

```bash
# Validate JSON
cat logs.json | jq . > /dev/null
# If errors, shows line number

# Pretty-print to find issues
jq . logs.json

# Fix and re-format
jq -c . logs.json > fixed.json
gonzo -f fixed.json
```

#### Multi-line JSON

**Symptom**: JSON objects span multiple lines, not parsed correctly.

**Example**:

```json
{
  "level": "info",
  "message": "test"
}
```

**Solution**:

Gonzo expects one JSON object per line (JSONL/NDJSON format).

```bash
# Compact multi-line JSON to single lines
jq -c . pretty.json > compact.json
gonzo -f compact.json

# Or pipe directly
jq -c . pretty.json | gonzo
```

#### JSON with Metadata Prefix

**Symptom**: Lines have timestamp or metadata before JSON.

**Example**:

```
2024-01-15 10:30:05 {"level":"info","msg":"test"}
```

**Solution**:

Remove prefix before piping to Gonzo:

```bash
# Remove timestamp prefix
sed 's/^[0-9-]* [0-9:]* //' logs.txt | gonzo

# Or use awk
awk '{$1=$2=""; print}' logs.txt | gonzo

# Extract just JSON part
grep -o '{.*}' logs.txt | gonzo
```

#### Escaped JSON in Strings

**Symptom**: JSON contains escaped JSON strings.

**Example**:

```json
{"log":"{\"level\":\"info\",\"msg\":\"test\"}"}
```

**Solution**:

```bash
# Unescape inner JSON
jq -r '.log | fromjson' logs.json | gonzo

# Or handle both levels
jq -c '.log | fromjson? // .' logs.json | gonzo
```

### Logfmt Issues

#### Logfmt Not Detected

**Symptom**: Key=value logs appear as plain text.

**Requirements for logfmt detection**:

* Must have `key=value` patterns
* Multiple pairs per line
* Values can be quoted: `key="value with spaces"`

**Example**:

```
level=info service=api user=123 msg="request completed"  ✅ Detected
INFO service api user 123 request completed              ❌ Not logfmt
```

**Solutions**:

1. **Verify format**

   ```bash
   # Check for key=value pattern
   grep -E '\w+=\w+' logs.txt | head
   ```
2. **Add more key=value pairs**
   * Single pair may not trigger detection
   * Multiple pairs more reliably detected
3. **Use custom format**

   ```bash
   gonzo --format=my-logfmt -f logs.txt
   ```

#### Spaces in Logfmt Values

**Symptom**: Values with spaces not parsed correctly.

**Examples**:

```
msg=hello world         ❌ Breaks: "world" seen as separate key
msg="hello world"       ✅ Correct: quotes preserve spaces
msg=hello\ world        ✅ Correct: escape preserves spaces
```

**Solution**:

Ensure spaces in values are properly quoted or escaped:

```bash
# Fix unquoted spaces (requires log generation fix)
# Or accept partial parsing of problematic lines
```

#### Logfmt with Nested Structures

**Symptom**: Nested objects in logfmt don't parse well.

**Example**:

```
user.id=123 user.name=john
```

**Explanation**: Logfmt is flat by design. Nested structures need JSON.

**Solution**:

1. **Accept flat representation**
   * Gonzo extracts `user.id` and `user.name` as separate attributes
2. **Convert to JSON if needed**

   ```bash
   # If you control log format, use JSON for nested data
   ```

### Plain Text Issues

#### No Structure Extracted from Text Logs

**Symptom**: Plain text logs show no attributes.

**Explanation**: Plain text logs can't be parsed into structured fields automatically.

**Examples**:

```
[2024-01-15 10:30:05] ERROR: Connection failed
INFO - api-service - User login successful
```

**Solutions**:

1. **Accept plain text display**
   * Logs still searchable and analyzable
   * Just no structured attributes
2. **Create custom format parser**

   ```bash
   # Define regex-based parser
   # See Custom Formats Guide
   gonzo --format=my-text-format -f logs.txt
   ```
3. **Convert logs to structured format**
   * Modify application to output JSON/logfmt
   * Use log shipper to add structure (Fluent Bit, Logstash)

#### Severity Not Detected in Text Logs

**Symptom**: Plain text logs don't show color-coded severity.

**Explanation**: Gonzo looks for common severity keywords in text logs:

* ERROR, FATAL, CRITICAL → Red
* WARN, WARNING → Yellow
* INFO → Green
* DEBUG → Blue
* TRACE → White

**Solutions**:

1. **Include severity keywords**

   ```
   [ERROR] Connection failed       ✅ Detected
   Connection failed              ❌ Not detected

   WARN: Low disk space           ✅ Detected  
   Disk space is low              ❌ Not detected
   ```
2. **Use consistent format**
   * Put severity at start of line
   * Use standard keywords (ERROR, WARN, INFO, DEBUG)
3. **Create custom format**
   * Define severity extraction pattern
   * Map custom levels to standard severities

### OTLP Format Issues

#### OTLP Logs Not Appearing

**Symptom**: OTLP receiver running but no logs in Gonzo.

**Diagnosis**:

1. **Verify receiver is enabled**

   ```bash
   # Check Gonzo started with OTLP
   gonzo --otlp-enabled

   # Should show listening on ports 4317 and 4318
   ```
2. **Check sender configuration**

   ```yaml
   # Verify endpoint in sender
   endpoint: localhost:4317      # gRPC
   endpoint: http://localhost:4318/v1/logs  # HTTP
   ```
3. **Test with curl (HTTP)**

   ```bash
   curl -X POST http://localhost:4318/v1/logs \
     -H "Content-Type: application/json" \
     -d '{"resourceLogs":[]}'

   # Should return 200 OK
   ```
4. **Check for port conflicts**

   ```bash
   lsof -i :4317
   lsof -i :4318
   ```

**Solutions**:

See Common Issues - OTLP Receiver for detailed fixes.

#### OTLP Attributes Missing

**Symptom**: OTLP logs appear but without expected attributes.

**Causes**:

1. **Attributes in resource vs log record**
   * Resource attributes: service.name, host, etc.
   * Log record attributes: user\_id, request\_id, etc.
   * Both should be extracted
2. **Verify sender includes attributes**

   ```python
   # Ensure attributes are set
   logger_provider.add_log_record_processor(processor)
   # Check resource attributes and log attributes
   ```
3. **Check attribute names**
   * Gonzo shows all attributes
   * May just be named differently than expected

### Custom Format Issues

#### Custom Format Not Working

**Symptom**: `--format=my-format` shows error or doesn't parse.

**Diagnosis**:

1. **Verify format file exists**

   ```bash
   ls ~/.config/gonzo/formats/my-format.yaml
   ```
2. **Check YAML syntax**

   ```bash
   cat ~/.config/gonzo/formats/my-format.yaml

   # Validate if you have yamllint
   yamllint ~/.config/gonzo/formats/my-format.yaml
   ```
3. **Test with built-in format first**

   ```bash
   # Verify custom formats work at all
   gonzo --format=loki-stream -f test.json
   ```

**Solutions**:

See Custom Formats Guide for:

* Format file syntax
* Regex patterns
* Field mapping
* Testing formats

#### Regex Not Matching

**Symptom**: Custom format regex doesn't extract fields.

**Solutions**:

1. **Test regex separately**

   ```bash
   # Test your regex pattern
   echo "sample log line" | grep -E "your-regex-pattern"
   ```
2. **Use online regex tester**
   * Test at regex101.com
   * Use example log lines
   * Verify capture groups
3. **Check for special characters**

   ```yaml
   # Escape special characters
   pattern: '\[(\d+)\]'  # Brackets escaped
   ```
4. **Start simple, iterate**

   ```yaml
   # Begin with basic pattern
   pattern: '(\w+)'

   # Then add complexity
   pattern: '(\w+)=(\w+)'

   # Finally, full pattern
   pattern: '(\w+)="([^"]*)"'
   ```

### Encoding Issues

#### Special Characters Garbled

**Symptom**: Non-ASCII characters display incorrectly.

**Solutions**:

1. **Ensure UTF-8 encoding**

   ```bash
   export LANG=en_US.UTF-8
   export LC_ALL=en_US.UTF-8
   ```
2. **Check file encoding**

   ```bash
   file logs.txt
   # Should show: UTF-8 Unicode text

   # Convert if needed
   iconv -f ISO-8859-1 -t UTF-8 logs.txt > logs_utf8.txt
   ```
3. **Terminal font support**
   * Use font with good Unicode support
   * JetBrains Mono, Fira Code, Cascadia Code

#### Binary or Non-Text Data

**Symptom**: Binary data causes display issues.

**Solution**:

```bash
# Filter out binary data
strings logs.bin | gonzo

# Or ensure only text logs are processed
file logs.txt  # Should be "text" not "data"
```

### Performance with Complex Formats

#### Slow Parsing with Complex Regex

**Symptom**: Custom format with complex regex causes slowdowns.

**Solutions**:

1. **Simplify regex patterns**

   ```yaml
   # Instead of: .*?(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+Z).*
   # Use: (\d{4}-\d{2}-\d{2}T[\d:.]+Z)
   ```
2. **Reduce backtracking**
   * Avoid nested quantifiers: `(.*)*`
   * Use possessive quantifiers when possible
   * Anchor patterns: `^` and \`# Log Format Issues

Troubleshooting guide for log parsing and format detection problems in Gonzo.

### Format Detection Issues

#### Logs Not Being Parsed

**Symptom**: Structured logs appear as plain text instead of being parsed.

**Diagnosis**:

Gonzo automatically detects formats per line based on these rules:

* **JSON**: Lines starting with `{`
* **Logfmt**: Lines containing `key=value` patterns
* **Plain text**: Everything else

**Solutions**:

1. **Verify JSON is valid**

   ```bash
   # Test each line individually
   head -1 logs.json | jq .

   # If error, JSON is malformed
   ```
2. **Check line starts with `{`**

   ```bash
   # JSON must start with opening brace
   head logs.json

   # ✅ Good: {"level":"info"...
   # ❌ Bad: 2024-01-15 {"level":"info"...
   ```
3. **Inspect logfmt format**

   ```bash
   # Should have key=value pairs
   head logs.txt

   # ✅ Good: level=info service=api msg="started"
   # ❌ Bad: [INFO] service api started
   ```
4. **Use custom format for non-standard logs**

   ```bash
   gonzo --format=my-custom-format -f logs.txt
   ```

#### Mixed Format Logs

**Symptom**: Some lines parse correctly, others don't.

**Explanation**: Gonzo detects format per line, so mixed formats will have inconsistent parsing.

**Example**:

```
{"level":"info","msg":"API started"}     ← Parsed as JSON
level=info msg="processing request"     ← Parsed as logfmt  
[ERROR] Connection timeout              ← Plain text
```

**Solutions**:

1. **Accept mixed display**
   * This is expected behavior
   * Each format renders appropriately
2. **Pre-filter to single format**

   ```bash
   # Extract only JSON lines
   grep '^{' mixed.log | gonzo

   # Or only logfmt
   grep '=' mixed.log | gonzo
   ```
3. **Convert to uniform format**

   ```bash
   # Convert all to JSON with jq
   cat mixed.log | jq -R -c '. | fromjson? // {"message": .}' | gonzo
   ```

#### Attributes Not Extracted

**Symptom**: Logs parse but attributes panel is empty.

**Causes & Solutions**:

1. **Plain text logs have no structured attributes**
   * Plain text can't be parsed into fields
   * Only JSON and logfmt have attributes
2. **Check JSON structure**

   ```bash
   # Verify JSON has expected fields
   head -1 logs.json | jq .

   # Should show key-value pairs
   ```
3. **Nested JSON**

   ```json
   {
     "log": {
       "level": "info",
       "service": "api"
     }
   }
   ```

   * Gonzo extracts nested attributes
   * May need to check nested paths
4. **Missing common attribute names**
   * Gonzo looks for common fields: `level`, `service`, `host`, etc.
   * Custom fields may not be highlighted

### JSON Issues

#### Malformed JSON

**Symptom**: JSON logs show as plain text or cause errors.

**Common JSON Issues**:

1. **Trailing commas**

   ```json
   {"level":"info","msg":"test",}  ❌ Invalid
   {"level":"info","msg":"test"}   ✅ Valid
   ```
2. **Single quotes instead of double**

   ```json
   {'level':'info'}     ❌ Invalid
   {"level":"info"}     ✅ Valid
   ```
3. **Unescaped quotes in strings**

   ```json
   {"msg":"He said "hi""}           ❌ Invalid
   {"msg":"He said \"hi\""}         ✅ Valid
   {"msg":"He said 'hi'"}           ✅ Valid (single quotes in string)
   ```
4. **Missing quotes on keys**

   ```json
   {level:"info"}       ❌ Invalid
   {"level":"info"}     ✅ Valid
   ```

**Validate & Fix**:

```bash
# Validate JSON
cat logs.json | jq . > /dev/null
# If errors, shows line number

# Pretty-print to find issues
jq . logs.json

# Fix and re-format
jq -c . logs.json > fixed.json
gonzo -f fixed.json
```

#### Multi-line JSON

**Symptom**: JSON objects span multiple lines, not parsed correctly.

**Example**:

```json
{
  "level": "info",
  "message": "test"
}
```

**Solution**:

Gonzo expects one JSON object per line (JSONL/NDJSON format).

```bash
# Compact multi-line JSON to single lines
jq -c . pretty.json > compact.json
gonzo -f compact.json

# Or pipe directly
jq -c . pretty.json | gonzo
```

#### JSON with Metadata Prefix

**Symptom**: Lines have timestamp or metadata before JSON.

**Example**:

```
2024-01-15 10:30:05 {"level":"info","msg":"test"}
```

**Solution**:

Remove prefix before piping to Gonzo:

```bash
# Remove timestamp prefix
sed 's/^[0-9-]* [0-9:]* //' logs.txt | gonzo

# Or use awk
awk '{$1=$2=""; print}' logs.txt | gonzo

# Extract just JSON part
grep -o '{.*}' logs.txt | gonzo
```

#### Escaped JSON in Strings

**Symptom**: JSON contains escaped JSON strings.

**Example**:

```json
{"log":"{\"level\":\"info\",\"msg\":\"test\"}"}
```

**Solution**:

```bash
# Unescape inner JSON
jq -r '.log | fromjson' logs.json | gonzo

# Or handle both levels
jq -c '.log | fromjson? // .' logs.json | gonzo
```

### Logfmt Issues

#### Logfmt Not Detected

**Symptom**: Key=value logs appear as plain text.

**Requirements for logfmt detection**:

* Must have `key=value` patterns
* Multiple pairs per line
* Values can be quoted: `key="value with spaces"`

**Example**:

```
level=info service=api user=123 msg="request completed"  ✅ Detected
INFO service api user 123 request completed              ❌ Not logfmt
```

**Solutions**:

1. **Verify format**

   ```bash
   # Check for key=value pattern
   grep -E '\w+=\w+' logs.txt | head
   ```
2. **Add more key=value pairs**
   * Single pair may not trigger detection
   * Multiple pairs more reliably detected
3. **Use custom format**

   ```bash
   gonzo --format=my-logfmt -f logs.txt
   ```

#### Spaces in Logfmt Values

**Symptom**: Values with spaces not parsed correctly.

**Examples**:

```
msg=hello world         ❌ Breaks: "world" seen as separate key
msg="hello world"       ✅ Correct: quotes preserve spaces
msg=hello\ world        ✅ Correct: escape preserves spaces
```

**Solution**:

Ensure spaces in values are properly quoted or escaped:

```bash
# Fix unquoted spaces (requires log generation fix)
# Or accept partial parsing of problematic lines
```

#### Logfmt with Nested Structures

**Symptom**: Nested objects in logfmt don't parse well.

**Example**:

```
user.id=123 user.name=john
```

**Explanation**: Logfmt is flat by design. Nested structures need JSON.

**Solution**:

1. **Accept flat representation**
   * Gonzo extracts `user.id` and `user.name` as separate attributes
2. **Convert to JSON if needed**

   ```bash
   # If you control log format, use JSON for nested data
   ```

### Plain Text Issues

#### No Structure Extracted from Text Logs

**Symptom**: Plain text logs show no attributes.

**Explanation**: Plain text logs can't be parsed into structured fields automatically.

**Examples**:

```
[2024-01-15 10:30:05] ERROR: Connection failed
INFO - api-service - User login successful
```

**Solutions**:

1. **Accept plain text display**
   * Logs still searchable and analyzable
   * Just no structured attributes
2. **Create custom format parser**

   ```bash
   # Define regex-based parser
   # See Custom Formats Guide
   gonzo --format=my-text-format -f logs.txt
   ```
3. **Convert logs to structured format**
   * Modify application to output JSON/logfmt
   * Use log shipper to add structure (Fluent Bit, Logstash)

#### Severity Not Detected in Text Logs

**Symptom**: Plain text logs don't show color-coded severity.

**Explanation**: Gonzo looks for common severity keywords in text logs:

* ERROR, FATAL, CRITICAL → Red
* WARN, WARNING → Yellow
* INFO → Green
* DEBUG → Blue
* TRACE → White

**Solutions**:

1. **Include severity keywords**

   ```
   [ERROR] Connection failed       ✅ Detected
   Connection failed              ❌ Not detected

   WARN: Low disk space           ✅ Detected  
   Disk space is low              ❌ Not detected
   ```
2. **Use consistent format**
   * Put severity at start of line
   * Use standard keywords (ERROR, WARN, INFO, DEBUG)
3. **Create custom format**
   * Define severity extraction pattern
   * Map custom levels to standard severities

### OTLP Format Issues

#### OTLP Logs Not Appearing

**Symptom**: OTLP receiver running but no logs in Gonzo.

**Diagnosis**:

1. **Verify receiver is enabled**

   ```bash
   # Check Gonzo started with OTLP
   gonzo --otlp-enabled

   # Should show listening on ports 4317 and 4318
   ```
2. **Check sender configuration**

   ```yaml
   # Verify endpoint in sender
   endpoint: localhost:4317      # gRPC
   endpoint: http://localhost:4318/v1/logs  # HTTP
   ```
3. **Test with curl (HTTP)**

   ```bash
   curl -X POST http://localhost:4318/v1/logs \
     -H "Content-Type: application/json" \
     -d '{"resourceLogs":[]}'

   # Should return 200 OK
   ```
4. **Check for port conflicts**

   ```bash
   lsof -i :4317
   lsof -i :4318
   ```

**Solutions**:

See Common Issues - OTLP Receiver for detailed fixes.

#### OTLP Attributes Missing

**Symptom**: OTLP logs appear but without expected attributes.

**Causes**:

1. **Attributes in resource vs log record**
   * Resource attributes: service.name, host, etc.
   * Log record attributes: user\_id, request\_id, etc.
   * Both should be extracted
2. **Verify sender includes attributes**

   ```python
   # Ensure attributes are set
   logger_provider.add_log_record_processor(processor)
   # Check resource attributes and log attributes
   ```
3. **Check attribute names**
   * Gonzo shows all attributes
   * May just be named differently than expected

### Custom Format Issues

#### Custom Format Not Working

**Symptom**: `--format=my-format` shows error or doesn't parse.

**Diagnosis**:

1. **Verify format file exists**

   ```bash
   ls ~/.config/gonzo/formats/my-format.yaml
   ```
2. **Check YAML syntax**

   ```bash
   cat ~/.config/gonzo/formats/my-format.yaml

   # Validate if you have yamllint
   yamllint ~/.config/gonzo/formats/my-format.yaml
   ```
3. **Test with built-in format first**

   ```bash
   # Verify custom formats work at all
   gonzo --format=loki-stream -f test.json
   ```

**Solutions**:

See Custom Formats Guide for:

* Format file syntax
* Regex patterns
* Field mapping
* Testing formats

#### Regex Not Matching

**Symptom**: Custom format regex doesn't extract fields.

**Solutions**:

1. **Test regex separately**

   ```bash
   # Test your regex pattern
   echo "sample log line" | grep -E "your-regex-pattern"
   ```
2. **Use online regex tester**
   * Test at regex101.com
   * Use example log lines
   * Verify capture groups
3. **Check for special characters**

   ```yaml
   # Escape special characters
   pattern: '\[(\d+)\]'  # Brackets escaped
   ```
4. **Start simple, iterate**

   ```yaml
   # Begin with basic pattern
   pattern: '(\w+)'

   # Then add complexity
   pattern: '(\w+)=(\w+)'

   # Finally, full pattern
   pattern: '(\w+)="([^"]*)"'
   ```

### Encoding Issues

#### Special Characters Garbled

**Symptom**: Non-ASCII characters display incorrectly.

**Solutions**:

1. **Ensure UTF-8 encoding**

   ```bash
   export LANG=en_US.UTF-8
   export LC_ALL=en_US.UTF-8
   ```
2. **Check file encoding**

   ```bash
   file logs.txt
   # Should show: UTF-8 Unicode text

   # Convert if needed
   iconv -f ISO-8859-1 -t UTF-8 logs.txt > logs_utf8.txt
   ```
3. **Pre-filter logs**

   ```bash
   # Filter before complex parsing
   grep "pattern" logs.txt | gonzo --format=complex
   ```
4. **Use built-in formats when possible**
   * JSON and logfmt parsing is optimized
   * Custom regex is slower

### Timestamp Issues

#### Timestamps Not Recognized

**Symptom**: Logs appear in wrong order or timestamp not extracted.

**Common timestamp formats Gonzo recognizes**:

```
2024-01-15T10:30:05Z                    # ISO 8601
2024-01-15T10:30:05.123456Z             # ISO 8601 with microseconds
2024-01-15 10:30:05                      # Common format
Jan 15 10:30:05                          # Syslog format
1705315805                               # Unix timestamp
```

**Solutions**:

1. **Use ISO 8601 format (recommended)**

   ```json
   {"timestamp":"2024-01-15T10:30:05Z","msg":"test"}
   ```
2. **Ensure timestamp field name**
   * Common names: `timestamp`, `time`, `@timestamp`, `ts`
   * Gonzo checks these automatically
3. **Custom format for unusual timestamps**
   * Define timestamp extraction in format file
   * Specify timestamp format

#### Timezone Issues

**Symptom**: Timestamps appear in wrong timezone.

**Solutions**:

1. **Use UTC in logs (recommended)**

   ```json
   {"timestamp":"2024-01-15T10:30:05Z"}  # Z indicates UTC
   ```
2. **Include timezone offset**

   ```json
   {"timestamp":"2024-01-15T10:30:05-05:00"}  # EST
   ```
3. **Gonzo displays timestamps as received**
   * No automatic conversion
   * Format logs consistently at source

### Large Log Line Issues

#### Very Long Lines Truncated

**Symptom**: Extremely long log lines appear cut off.

**Solutions**:

1. **Use horizontal scrolling**

   ```
   ← → or h l  # Scroll horizontally
   ```
2. **View in detail modal**

   ```
   Enter  # Opens full log entry
   ```
3. **Split long lines at source**
   * Configure application to use reasonable line length
   * Use structured logging to avoid massive single-line logs

#### Lines Exceed Buffer

**Symptom**: Some log lines cause errors or don't appear.

**Solution**:

Gonzo handles lines up to typical buffer limits. For extremely large lines:

```bash
# Pre-process to truncate lines
cut -c 1-10000 massive.log | gonzo

# Or filter out problematic lines
awk 'length($0) < 10000' massive.log | gonzo
```

### Debugging Format Issues

#### Test Format Detection

```bash
# Test with minimal sample
echo '{"level":"info","msg":"test"}' | gonzo
# Should parse as JSON

echo 'level=info msg=test' | gonzo
# Should parse as logfmt

echo 'INFO test message' | gonzo
# Should show as plain text
```

#### Examine Raw Logs

```bash
# Check first few lines
head -5 logs.txt

# Check for hidden characters
cat -A logs.txt | head

# Validate JSON structure
head -1 logs.json | jq .

# Check line endings
file logs.txt  # Shows CRLF vs LF
```

#### Compare with Known-Good Format

```bash
# Test with working format first
echo '{"level":"info","message":"test"}' > good.json
gonzo -f good.json

# Then compare with problem logs
diff <(head -1 good.json) <(head -1 problem.json)
```

### Common Format Patterns

#### Application Logs

**Go/Logrus**:

```json
{"level":"info","msg":"started","time":"2024-01-15T10:30:05Z"}
```

✅ Parses as JSON automatically

**Python/Logging**:

```
2024-01-15 10:30:05,123 INFO module: message
```

⚠️ Plain text - create custom format for structure

**Node.js/Winston**:

```json
{"level":"info","message":"started","timestamp":"2024-01-15T10:30:05Z"}
```

✅ Parses as JSON automatically

#### System Logs

**Syslog**:

```
Jan 15 10:30:05 hostname service[123]: message
```

⚠️ Plain text - consider custom format

**Systemd Journal**:

```
MESSAGE=Test log
PRIORITY=6
_HOSTNAME=server
```

⚠️ Key=value but special format - needs custom parser

#### Container Logs

**Docker JSON**:

```json
{"log":"application log message\n","stream":"stdout","time":"2024-01-15T10:30:05Z"}
```

✅ Parses as JSON, extracts nested log

**Kubernetes**:

```json
{"level":"info","msg":"test","pod":"app-123"}
```

✅ Parses as JSON with K8s attributes

### Format Best Practices

#### When Choosing Log Format

1. **Prefer structured formats**
   * JSON or logfmt over plain text
   * Easier to parse and analyze
   * Better attribute extraction
2. **Use consistent format**
   * Same format across all services
   * Easier to aggregate and search
3. **Include standard fields**
   * `level` or `severity`: ERROR, WARN, INFO, DEBUG
   * `timestamp`: ISO 8601 format
   * `message` or `msg`: Human-readable message
   * `service` or `service.name`: Service identifier
4. **Example good JSON log**:

   ```json
   {
     "timestamp": "2024-01-15T10:30:05Z",
     "level": "error",
     "service": "api",
     "message": "Database connection failed",
     "error": "connection timeout",
     "host": "prod-server-01"
   }
   ```

#### When You Can't Change Format

1. **Use custom format definition**
   * Create regex-based parser
   * Map fields to standard attributes
2. **Pre-process logs**
   * Use awk/sed to restructure
   * Convert to JSON/logfmt before Gonzo
3. **Use log shipping layer**
   * Fluent Bit, Logstash, Vector
   * Transform logs to standard format

### Getting Help

#### Provide This Info for Format Issues

```bash
# Sample log lines (3-5 lines)
head -5 logs.txt

# File encoding
file logs.txt

# Attempted command
echo "gonzo -f logs.txt [--format=...]"

# Expected vs actual behavior
echo "Expected: Parse as JSON"
echo "Actual: Shows as plain text"

# Gonzo version
gonzo --version
```

#### Resources

* **Common Issues** - General troubleshooting
* **Custom Formats Guide** - Creating format parsers
* [**GitHub Issues**](https://github.com/control-theory/gonzo/issues) - Report format bugs
* [**Examples Directory**](https://github.com/control-theory/gonzo/tree/main/examples) - Sample format files

{% hint style="info" %}
**Testing formats?** Start with small sample files before processing large logs. This makes debugging much faster.
{% endhint %}


# Contributing

Welcome to the Gonzo contributor guide! We're excited that you're interested in contributing to Gonzo. Whether you're fixing a bug, adding a feature, improving documentation, or just asking questions, your contributions are welcome and appreciated.

### Why Contribute?

Contributing to Gonzo offers many benefits:

* **Learn Go and TUI development**: Work with modern Go frameworks like Bubble Tea
* **Improve your skills**: Practice coding, testing, and documentation
* **Make an impact**: Help thousands of developers analyze logs better
* **Join a community**: Connect with other contributors and users
* **Build your portfolio**: Open source contributions look great on resumes
* **Give back**: Support a tool you use and rely on

### Ways to Contribute

You don't need to be a coding expert to contribute! Here are many ways to help:

#### 🐛 Report Bugs

Found a bug? Report it! Include:

* Clear description
* Steps to reproduce
* Expected vs actual behavior
* Your environment details

[Open a bug report →](https://github.com/control-theory/gonzo/issues/new)

#### 💡 Suggest Features

Have an idea for improvement? We'd love to hear it! Describe:

* The problem you're trying to solve
* Your proposed solution
* Why it would be useful
* Any alternatives you've considered

[Suggest a feature →](https://github.com/control-theory/gonzo/issues/new)

#### 📝 Improve Documentation

Documentation is crucial! You can:

* Fix typos or unclear explanations
* Add missing information
* Create tutorials or guides
* Improve examples
* Translate documentation

#### 🎨 Create Skins & Formats

Extend Gonzo's capabilities:

* Design custom color schemes
* Create parsers for new log formats
* Share configurations
* Build integrations

#### 💬 Help Others

Be an active community member:

* Answer questions in GitHub Discussions
* Help troubleshoot issues
* Review pull requests
* Share your use cases

#### 💻 Write Code

Contribute code improvements:

* Fix bugs
* Implement features
* Add tests
* Optimize performance
* Refactor code

### Getting Started

#### First Time Contributors

**Never contributed to open source before? No problem!**

1. **Development Setup** - Set up your development environment
2. **Look for "good first issue" labels** - These are beginner-friendly issues
3. **Ask questions** - Don't hesitate to ask for help
4. **Start small** - Begin with documentation or small fixes
5. **Learn as you go** - Every contributor was a beginner once

#### Experienced Contributors

**Familiar with open source?**

1. **Contribution Guidelines** - Review our process and standards
2. **Architecture Overview** - Understand the codebase
3. **Pick an issue** - Look for issues matching your skills
4. **Discuss first** - For large changes, open an issue to discuss before coding

### Contribution Process

Our contribution workflow:

```
1. Fork & Clone
   ↓
2. Create Branch
   ↓
3. Make Changes
   ↓
4. Write Tests
   ↓
5. Update Docs
   ↓
6. Run Tests & Lint
   ↓
7. Commit & Push
   ↓
8. Create Pull Request
   ↓
9. Code Review
   ↓
10. Merge! 🎉
```

See Contribution Guidelines for detailed steps.

### What We're Looking For

#### High Priority

These contributions are especially valuable:

* 🐛 **Bug fixes**: Stability improvements
* 📚 **Documentation**: Clarity and completeness
* ✅ **Tests**: Increasing code coverage
* 🎨 **Custom formats**: Parsers for popular log formats
* 🔌 **Integrations**: Connecting with other tools

#### Medium Priority

Also valuable contributions:

* ✨ **New features**: After discussion with maintainers
* ⚡ **Performance**: Optimization work
* 🎨 **UI improvements**: Better user experience
* 🌐 **Localization**: Translations

#### Always Welcome

These are always appreciated:

* 📖 **Examples**: Real-world use cases
* 🎨 **Skins**: Custom themes
* 💬 **Discussions**: Ideas and feedback
* 🤝 **Community support**: Helping others

### Project Areas

#### Frontend (TUI)

**What**: Terminal user interface using Bubble Tea

**Skills**: Go, terminal UI design, user experience

**Good for**: Visual thinkers, UI/UX enthusiasts

**Files**: `internal/tui/`

#### Backend (Processing)

**What**: Log parsing, analysis, and pattern detection

**Skills**: Go, algorithms, data structures

**Good for**: Problem solvers, algorithm enthusiasts

**Files**: `internal/analyzer/`, `internal/memory/`

#### Networking (OTLP)

**What**: OpenTelemetry protocol implementation

**Skills**: Go, networking, protocols, gRPC

**Good for**: Systems programmers, protocol enthusiasts

**Files**: `internal/otlplog/`

#### AI Integration

**What**: AI-powered log analysis features

**Skills**: Go, API integration, prompt engineering

**Good for**: AI/ML enthusiasts

**Files**: `internal/ai/`

#### Documentation

**What**: User guides, API docs, examples

**Skills**: Technical writing, clear communication

**Good for**: Writers, educators

**Files**: `docs/`, `README.md`, `*.md` files

#### Testing

**What**: Unit tests, integration tests, benchmarks

**Skills**: Go testing, test design

**Good for**: Quality-focused developers

**Files**: `*_test.go`

### Recognition

We value all contributions! Contributors receive:

* ✨ **Credit** in release notes
* 👥 **Listed** on GitHub contributors page
* 🏆 **Recognition** in the community
* 📣 **Mentions** on social media (with permission)
* 🎖️ **Special badges** for significant contributions

### Code of Conduct

We are committed to providing a welcoming and inclusive environment. All participants must adhere to our Code of Conduct:

* **Be respectful**: Treat everyone with respect and courtesy
* **Be inclusive**: Welcome people of all backgrounds
* **Be collaborative**: Work together constructively
* **Be professional**: Keep discussions on topic

See Community for full Code of Conduct.

### Questions?

Need help or have questions?

* 💬 **GitHub Discussions**: [Start a discussion](https://github.com/control-theory/gonzo/discussions)
* 🐛 **GitHub Issues**: [Open an issue](https://github.com/control-theory/gonzo/issues)
* 📧 **Email**: <hello@controltheory.com>

We're here to help!

### Resources

#### Essential Reading

* **Development Setup** - Get your environment ready
* **Contribution Guidelines** - Detailed process and standards
* **Community** - Connect with other contributors

#### Technical Resources

* **Architecture Overview** - How Gonzo works
* **OTLP Protocol** - OpenTelemetry implementation
* **Extension Points** - Ways to extend Gonzo

#### Helpful Links

* **GitHub Repository**: <https://github.com/control-theory/gonzo>
* **Issue Tracker**: <https://github.com/control-theory/gonzo/issues>
* **Discussions**: <https://github.com/control-theory/gonzo/discussions>
* **Website**: <https://gonzo.controltheory.com>

### Quick Start

Ready to contribute? Follow these steps:

**For code contributions**:

```bash
# 1. Fork the repository on GitHub

# 2. Clone your fork
git clone https://github.com/YOUR-USERNAME/gonzo.git
cd gonzo

# 3. Set up development environment
make deps
make build

# 4. Create a branch
git checkout -b feature/my-feature

# 5. Make changes and test
make dev

# 6. Push and create PR
git push origin feature/my-feature
```

**For documentation contributions**:

* Edit Markdown files directly on GitHub, or
* Follow the same process as code contributions

**For issues and discussions**:

* Just go to GitHub and start engaging!

### Thank You!

Your contributions, no matter how small, make Gonzo better for everyone. Thank you for taking the time to contribute!

We look forward to working with you! 🎉

***

{% hint style="info" %}
**New to open source?** Check out [First Contributions](https://firstcontributions.github.io/) for a gentle introduction to contributing to open source projects.
{% endhint %}

{% hint style="success" %}
**Ready to start?** Head over to Development Setup to get your environment configured, or browse [good first issues](https://github.com/control-theory/gonzo/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) to find your first contribution!
{% endhint %}


# Development Setup

Get your development environment ready to contribute to Gonzo. This guide covers everything from prerequisites to running your first build.

### Prerequisites

#### Required Software

**Go Programming Language**:

* Version: 1.21 or higher
* Download: <https://golang.org/dl/>
* Installation guide: <https://golang.org/doc/install>

```bash
# Verify Go installation
go version
# Should show: go version go1.21.x or higher
```

**Git**:

* Version: 2.0 or higher
* Download: <https://git-scm.com/downloads>

```bash
# Verify Git installation
git --version
```

**Make** (optional but recommended):

* Usually pre-installed on macOS/Linux
* Windows: Install via Chocolatey or use Git Bash

```bash
# Verify Make installation
make --version
```

#### Recommended Tools

**Code Editor**:

* VS Code with Go extension
* GoLand
* Vim/Neovim with vim-go
* Any editor with Go support

**Terminal**:

* Modern terminal with good Unicode support
* Recommendations: iTerm2, Alacritty, Windows Terminal

**Additional Tools**:

```bash
# Code formatting
go install golang.org/x/tools/cmd/goimports@latest

# Linting
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest

# Testing
go install gotest.tools/gotestsum@latest
```

### Getting the Source Code

#### Fork the Repository

1. Go to <https://github.com/control-theory/gonzo>
2. Click "Fork" button (top right)
3. This creates your own copy of the repository

#### Clone Your Fork

```bash
# Clone your fork
git clone https://github.com/YOUR-USERNAME/gonzo.git
cd gonzo

# Add upstream remote
git remote add upstream https://github.com/control-theory/gonzo.git

# Verify remotes
git remote -v
# Should show:
# origin    https://github.com/YOUR-USERNAME/gonzo.git (fetch)
# origin    https://github.com/YOUR-USERNAME/gonzo.git (push)
# upstream  https://github.com/control-theory/gonzo.git (fetch)
# upstream  https://github.com/control-theory/gonzo.git (push)
```

#### Sync with Upstream

Keep your fork up to date:

```bash
# Fetch latest changes from upstream
git fetch upstream

# Switch to main branch
git checkout main

# Merge upstream changes
git merge upstream/main

# Push to your fork
git push origin main
```

### Project Structure

Understanding the codebase:

```
gonzo/
├── cmd/
│   └── gonzo/              # Application entry point
│       ├── main.go         # Main function
│       ├── app.go          # Application setup
│       ├── extractors.go   # Data extraction
│       └── processing.go   # Log processing
│
├── internal/               # Private application code
│   ├── tui/               # Terminal UI (Bubble Tea)
│   │   ├── model.go       # Application model
│   │   ├── update.go      # Update logic
│   │   ├── view.go        # View rendering
│   │   ├── components.go  # UI components
│   │   ├── charts.go      # Chart rendering
│   │   ├── tables.go      # Table components
│   │   ├── modals.go      # Modal dialogs
│   │   ├── navigation.go  # Navigation handling
│   │   ├── formatting.go  # Text formatting
│   │   ├── severity.go    # Severity handling
│   │   ├── styles.go      # UI styles
│   │   └── drain3_manager.go # Drain3 integration
│   │
│   ├── analyzer/          # Log analysis
│   │   ├── otlp.go       # OTLP analysis
│   │   └── text.go       # Text analysis
│   │
│   ├── memory/            # Data storage
│   │   └── frequency.go   # Frequency tracking
│   │
│   ├── otlplog/          # OTLP handling
│   │   ├── converter.go   # Log conversion
│   │   └── detector.go    # Format detection
│   │
│   ├── drain3/           # Log clustering
│   │   └── impl.go       # Drain3 implementation
│   │
│   ├── ai/               # AI integration
│   │   └── openai.go     # OpenAI API
│   │
│   ├── output/           # Output handlers
│   │   └── stdout.go     # Standard output
│   │
│   └── reader/           # Input readers
│       └── stdin.go      # Standard input
│
├── examples/             # Example files
│   ├── config.yml       # Sample config
│   └── formats/         # Custom formats
│
├── docs/                # Documentation
├── Makefile            # Build automation
├── go.mod              # Go module
└── go.sum              # Dependencies
```

### Building Gonzo

#### Quick Build

```bash
# Build using Make (recommended)
make build

# Binary created at: ./bin/gonzo
./bin/gonzo --version
```

#### Manual Build

```bash
# Build without Make
go build -o bin/gonzo ./cmd/gonzo

# Run
./bin/gonzo --version
```

#### Development Build

```bash
# Build with all checks
make dev

# This runs:
# - go fmt (format code)
# - go vet (check for issues)
# - go test (run tests)
# - go build (compile binary)
```

#### Build for All Platforms

```bash
# Cross-compile for multiple platforms
make cross-build

# Creates binaries for:
# - Linux (amd64, arm64)
# - macOS (amd64, arm64)
# - Windows (amd64)
```

### Running Tests

#### Unit Tests

```bash
# Run all tests
make test

# Or with go directly
go test ./...

# Verbose output
go test -v ./...

# Specific package
go test ./internal/analyzer/...
```

#### Race Detection

```bash
# Detect race conditions
make test-race

# Or with go directly
go test -race ./...
```

#### Coverage Report

```bash
# Generate coverage report
go test -coverprofile=coverage.out ./...

# View coverage in browser
go tool cover -html=coverage.out
```

#### Integration Tests

```bash
# Run integration tests
make test-integration

# Or with tags
go test -tags=integration ./...
```

### Running Gonzo in Development

#### Basic Run

```bash
# Build and run
make build
./bin/gonzo -f examples/sample.log

# Or run directly without building
go run ./cmd/gonzo -f examples/sample.log
```

#### With Sample Data

```bash
# Run demo with sample logs
make demo

# This generates sample logs and runs Gonzo
```

#### Testing Features

**Test file input**:

```bash
# Create test log file
cat > test.log << 'EOF'
{"level":"info","msg":"Test 1"}
{"level":"error","msg":"Test 2"}
{"level":"warn","msg":"Test 3"}
EOF

# Run Gonzo
./bin/gonzo -f test.log
```

**Test stdin**:

```bash
# Pipe logs to Gonzo
echo '{"level":"info","msg":"Hello"}' | ./bin/gonzo
```

**Test follow mode**:

```bash
# In terminal 1
./bin/gonzo -f /tmp/live.log --follow

# In terminal 2
while true; do 
  echo "{\"level\":\"info\",\"msg\":\"Log $(date)\"}" >> /tmp/live.log
  sleep 1
done
```

**Test OTLP receiver**:

```bash
# Start with OTLP enabled
./bin/gonzo --otlp-enabled

# In another terminal, send test log
curl -X POST http://localhost:4318/v1/logs \
  -H "Content-Type: application/json" \
  -d '{"resourceLogs":[{"scopeLogs":[{"logRecords":[{"body":{"stringValue":"test"}}]}]}]}'
```

### Development Workflow

#### 1. Create a Feature Branch

```bash
# Sync with upstream first
git fetch upstream
git checkout main
git merge upstream/main

# Create feature branch
git checkout -b feature/my-awesome-feature
```

#### 2. Make Changes

```bash
# Edit files
vim internal/tui/model.go

# Format code
go fmt ./...

# Or use goimports
goimports -w .
```

#### 3. Test Changes

```bash
# Run tests
make test

# Build and test manually
make build
./bin/gonzo -f test.log
```

#### 4. Commit Changes

```bash
# Stage changes
git add .

# Commit with meaningful message
git commit -m "feat: add awesome feature

Detailed description of what this feature does and why.

Closes #123"
```

#### 5. Push to Your Fork

```bash
# Push feature branch to your fork
git push origin feature/my-awesome-feature
```

#### 6. Create Pull Request

1. Go to your fork on GitHub
2. Click "Compare & pull request"
3. Fill out PR template
4. Submit pull request

### Code Style

#### Formatting

```bash
# Format all Go code
go fmt ./...

# Or use goimports (better)
goimports -w .
```

#### Linting

```bash
# Run golangci-lint
golangci-lint run

# Fix auto-fixable issues
golangci-lint run --fix
```

#### Code Conventions

**Naming**:

* Use camelCase for variables and functions
* Use PascalCase for exported names
* Keep names short but descriptive
* Avoid abbreviations unless common

**Comments**:

```go
// Good: Concise description
// ParseLog parses a log line and returns structured data.
func ParseLog(line string) (*Log, error) {
    // Implementation
}

// Bad: Redundant or missing
func ParseLog(line string) (*Log, error) {
    // Implementation
}
```

**Error Handling**:

```go
// Good: Wrap errors with context
if err != nil {
    return fmt.Errorf("failed to parse log: %w", err)
}

// Bad: Lose error context
if err != nil {
    return err
}
```

### Debugging

#### Using Delve

```bash
# Install Delve debugger
go install github.com/go-delve/delve/cmd/dlv@latest

# Debug Gonzo
dlv debug ./cmd/gonzo -- -f test.log

# In Delve:
# (dlv) break main.main
# (dlv) continue
# (dlv) next
# (dlv) print variableName
```

#### Logging Debug Info

```bash
# Run with verbose flag
./bin/gonzo -v -f test.log 2> debug.log

# Check debug output
tail -f debug.log
```

#### VS Code Debug Configuration

Create `.vscode/launch.json`:

```json
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug Gonzo",
      "type": "go",
      "request": "launch",
      "mode": "debug",
      "program": "${workspaceFolder}/cmd/gonzo",
      "args": ["-f", "test.log"],
      "env": {},
      "showLog": true
    },
    {
      "name": "Debug Gonzo with OTLP",
      "type": "go",
      "request": "launch",
      "mode": "debug",
      "program": "${workspaceFolder}/cmd/gonzo",
      "args": ["--otlp-enabled"],
      "env": {},
      "showLog": true
    }
  ]
}
```

### Common Development Tasks

#### Adding a New Feature

1. **Plan the feature**
   * Open an issue to discuss
   * Get feedback from maintainers
   * Design the implementation
2. **Implement the feature**
   * Create feature branch
   * Write code following style guide
   * Add tests for new functionality
   * Update documentation
3. **Test thoroughly**
   * Unit tests
   * Integration tests
   * Manual testing
4. **Submit for review**
   * Create pull request
   * Address review comments
   * Wait for approval

#### Fixing a Bug

1. **Reproduce the bug**
   * Create minimal test case
   * Document steps to reproduce
2. **Write a failing test**
   * Test should fail before fix
   * Test should pass after fix
3. **Fix the bug**
   * Make minimal changes
   * Ensure test passes
4. **Submit fix**
   * Reference issue in commit
   * Include test in PR

#### Updating Dependencies

```bash
# Update all dependencies
go get -u ./...

# Tidy dependencies
go mod tidy

# Verify everything works
make test
```

### Performance Profiling

#### CPU Profiling

```bash
# Build with profiling
go build -o bin/gonzo ./cmd/gonzo

# Run with CPU profiling
./bin/gonzo -f large.log -cpuprofile=cpu.prof

# Analyze profile
go tool pprof cpu.prof
# Commands: top, list, web
```

#### Memory Profiling

```bash
# Run with memory profiling
./bin/gonzo -f large.log -memprofile=mem.prof

# Analyze profile
go tool pprof mem.prof
```

#### Benchmarking

```bash
# Run benchmarks
go test -bench=. ./...

# With memory stats
go test -bench=. -benchmem ./...

# Specific benchmark
go test -bench=BenchmarkParsing ./internal/analyzer/
```

### Troubleshooting Development Issues

#### Build Fails

**Dependency issues**:

```bash
# Clean module cache
go clean -modcache

# Re-download dependencies
go mod download

# Rebuild
make build
```

**Version mismatch**:

```bash
# Check Go version
go version

# Should be 1.21 or higher
# Update if needed
```

#### Tests Fail

**Race conditions**:

```bash
# Run with race detector
go test -race ./...

# Fix any race conditions found
```

**Flaky tests**:

* Run tests multiple times
* Check for timing dependencies
* Use proper synchronization

#### IDE Issues

**VS Code Go extension problems**:

```bash
# Reinstall Go tools
# Command Palette: Go: Install/Update Tools
```

**Gopls issues**:

```bash
# Clean gopls cache
rm -rf ~/Library/Caches/gopls  # macOS
rm -rf ~/.cache/gopls          # Linux
```

### Getting Help

#### Resources

* **GitHub Issues**: Ask questions, report bugs
* **GitHub Discussions**: General discussions
* **Code Review**: Learn from PR feedback
* **Documentation**: Read existing docs thoroughly

#### Communication

* **Be respectful**: Follow Code of Conduct
* **Be patient**: Maintainers are volunteers
* **Be clear**: Provide context and details
* **Be helpful**: Help others when you can

### Next Steps

Now that your development environment is set up:

1. **Read the codebase**: Familiarize yourself with the structure
2. **Pick an issue**: Look for "good first issue" labels
3. **Make a change**: Start with something small
4. **Submit a PR**: Get feedback and iterate

**Related Documentation**:

* Contribution Guidelines - Detailed contribution process
* Community - How to engage with the community
* Architecture Overview - Understanding the codebase

{% hint style="success" %}
**Ready to contribute?** Check out [open issues](https://github.com/control-theory/gonzo/issues) labeled "good first issue" to get started!
{% endhint %}

```bash
```


# Contribution Guidelines

Thank you for considering contributing to Gonzo! It's people like you that make Gonzo such a great tool. This guide covers how to contribute effectively.

### Code of Conduct

This project and everyone participating in it is governed by our Code of Conduct. By participating, you are expected to uphold this code:

* **Be respectful**: Treat everyone with respect and courtesy
* **Be inclusive**: Welcome and support people of all backgrounds
* **Be collaborative**: Work together to improve the project
* **Be professional**: Keep discussions on topic and constructive

### How Can I Contribute?

#### Reporting Bugs

Before creating bug reports, please check [existing issues](https://github.com/control-theory/gonzo/issues) as you might find out that you don't need to create one.

**When creating a bug report, include**:

* **Clear title**: Describe the issue concisely
* **Reproduction steps**: Exact steps to reproduce the problem
* **Expected behavior**: What you expected to happen
* **Actual behavior**: What actually happened
* **Environment details**:
  * Operating System (macOS, Linux, Windows)
  * Go version (`go version`)
  * Gonzo version (`gonzo --version`)
  * Terminal emulator
* **Logs and screenshots**: Include relevant output
* **Sample logs**: Sanitized log files if relevant

**Bug Report Template**:

```markdown
**Describe the bug**
A clear description of what the bug is.

**To Reproduce**
Steps to reproduce the behavior:
1. Run command '...'
2. Press key '...'
3. See error

**Expected behavior**
What you expected to happen.

**Screenshots/Logs**
If applicable, add screenshots or log output.

**Environment:**
- OS: [e.g., macOS 14.0]
- Go Version: [e.g., 1.21.5]
- Gonzo Version: [e.g., v0.1.6]
- Terminal: [e.g., iTerm2]

**Additional context**
Any other context about the problem.
```

#### Suggesting Enhancements

Enhancement suggestions are tracked as [GitHub issues](https://github.com/control-theory/gonzo/issues).

**When creating an enhancement suggestion, include**:

* **Clear title**: Describe the enhancement concisely
* **Detailed description**: Explain what you want to add
* **Use cases**: Why would this be useful?
* **Current behavior**: What happens now?
* **Proposed behavior**: What should happen?
* **Examples**: Show how it would work
* **Alternatives**: Have you considered other solutions?

**Enhancement Template**:

```markdown
**Is your feature request related to a problem?**
A clear description of the problem. Ex. I'm frustrated when [...]

**Describe the solution you'd like**
A clear description of what you want to happen.

**Describe alternatives you've considered**
Other solutions or features you've considered.

**Additional context**
Any other context, mockups, or examples.
```

#### Pull Requests

**Before submitting a pull request**:

1. **Fork the repository**
2. **Create your branch** from `main`

   ```bash
   git checkout -b feature/amazing-feature
   ```
3. **Make your changes**
4. **Add tests** if you've added code
5. **Update documentation** if you've changed APIs
6. **Ensure tests pass**

   ```bash
   make test
   ```
7. **Format and lint your code**

   ```bash
   make fmt
   make vet
   ```
8. **Commit your changes**
9. **Push to your fork**
10. **Open a Pull Request**

**Pull Request Checklist**:

* [ ] Code follows the project's style guide
* [ ] Self-review of code completed
* [ ] Comments added for complex code
* [ ] Documentation updated
* [ ] No new warnings introduced
* [ ] Tests added for new features
* [ ] All tests passing
* [ ] Commits follow commit message guidelines

### Development Guidelines

#### Commit Messages

Follow these guidelines for commit messages:

**Format**:

```
<type>: <subject>

<body>

<footer>
```

**Type**:

* `feat`: New feature
* `fix`: Bug fix
* `docs`: Documentation changes
* `style`: Code style changes (formatting, etc.)
* `refactor`: Code refactoring
* `test`: Adding or updating tests
* `chore`: Maintenance tasks

**Rules**:

* Use present tense ("Add feature" not "Added feature")
* Use imperative mood ("Move cursor to..." not "Moves cursor to...")
* Limit first line to 72 characters or less
* Reference issues and pull requests after first line
* Explain *what* and *why*, not *how*

**Examples**:

```
feat: Add support for custom log formats

Implements user-defined regex patterns for parsing non-standard log
formats. Users can now create YAML files in ~/.config/gonzo/formats/
to define custom parsers.

Closes #123
```

```
fix: Resolve race condition in OTLP receiver

The gRPC handler had a race condition when processing concurrent
requests. Added proper locking around shared state.

Fixes #456
```

```
docs: Update installation instructions

Add instructions for installing via Nix package manager.
```

#### Code Style

**Go Code Conventions**:

* **Follow standard Go style**: Use `gofmt` and `goimports`
* **Meaningful names**: Clear, descriptive variable and function names
* **Small functions**: Keep functions focused and concise
* **Comment exports**: All exported functions, types, and constants
* **Handle errors**: Always handle errors explicitly
* **No naked returns**: Always specify return values

**Example - Good**:

```go
// ParseLogLine extracts structured data from a log line.
// Returns an error if the line cannot be parsed.
func ParseLogLine(line string) (*Log, error) {
    if line == "" {
        return nil, fmt.Errorf("empty log line")
    }
    
    log := &Log{}
    if err := json.Unmarshal([]byte(line), log); err != nil {
        return nil, fmt.Errorf("failed to parse JSON: %w", err)
    }
    
    return log, nil
}
```

**Example - Bad**:

```go
func parse(l string) (*Log, error) {
    // No comments, unclear name, no error wrapping
    log := &Log{}
    json.Unmarshal([]byte(l), log)
    return log, nil
}
```

#### Testing Guidelines

**Write tests for**:

* All new functionality
* Bug fixes (test should fail before fix)
* Edge cases and error conditions
* Public APIs

**Test Structure**:

```go
func TestParseLogLine(t *testing.T) {
    tests := []struct {
        name    string
        input   string
        want    *Log
        wantErr bool
    }{
        {
            name:  "valid JSON log",
            input: `{"level":"info","msg":"test"}`,
            want:  &Log{Level: "info", Message: "test"},
        },
        {
            name:    "invalid JSON",
            input:   `{invalid}`,
            wantErr: true,
        },
        {
            name:    "empty string",
            input:   "",
            wantErr: true,
        },
    }
    
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := ParseLogLine(tt.input)
            if (err != nil) != tt.wantErr {
                t.Errorf("ParseLogLine() error = %v, wantErr %v", err, tt.wantErr)
                return
            }
            if !reflect.DeepEqual(got, tt.want) {
                t.Errorf("ParseLogLine() = %v, want %v", got, tt.want)
            }
        })
    }
}
```

**Test Different Formats**:

* JSON logs
* OTLP format
* Plain text logs
* Logfmt
* Custom formats

#### TUI Guidelines

When working on the terminal UI:

* **Consistent shortcuts**: Don't introduce conflicting key bindings
* **Color usage**: Use colors meaningfully, not decoratively
* **Responsive**: UI should feel snappy
* **Terminal sizes**: Test on different sizes (80x24 minimum)
* **Mouse + keyboard**: Support both input methods
* **Accessibility**: Ensure sufficient color contrast

#### Documentation Guidelines

**Update documentation when you**:

* Add new features
* Change existing behavior
* Add new CLI flags or options
* Modify configuration format

**Documentation to update**:

* `README.md` - Overview, installation, quick start
* `USAGE_GUIDE.md` - Detailed usage instructions
* GitBook docs - Comprehensive documentation
* Code comments - Inline documentation
* Help text - CLI help messages

### Project Structure Reference

Understanding the codebase structure:

```
gonzo/
├── cmd/gonzo/              # Application entry point
│   ├── main.go            # CLI setup and initialization
│   ├── app.go             # Application configuration
│   ├── extractors.go      # Data extraction utilities
│   └── processing.go      # Log processing logic
│
├── internal/              # Private application code
│   ├── tui/              # Terminal UI components (Bubble Tea)
│   │   ├── model.go      # Main Bubble Tea model
│   │   ├── view.go       # Rendering logic
│   │   ├── update.go     # Event handling
│   │   ├── components.go # Reusable UI components
│   │   ├── charts.go     # Chart rendering
│   │   ├── tables.go     # Table components
│   │   ├── modals.go     # Modal dialogs
│   │   ├── navigation.go # Navigation handling
│   │   ├── formatting.go # Text formatting utilities
│   │   ├── severity.go   # Log severity handling
│   │   ├── styles.go     # UI styling definitions
│   │   └── drain3_manager.go # Drain3 integration
│   │
│   ├── analyzer/         # Log analysis engine
│   │   ├── otlp.go      # OTLP log analysis
│   │   └── text.go      # Plain text analysis
│   │
│   ├── memory/           # Frequency tracking
│   │   └── frequency.go  # Frequency counting logic
│   │
│   ├── otlplog/         # OTLP format handling
│   │   ├── converter.go  # OTLP log conversion
│   │   └── detector.go   # OTLP format detection
│   │
│   ├── drain3/          # Drain3 log clustering
│   │   └── impl.go      # Drain3 implementation
│   │
│   ├── ai/              # AI integration
│   │   └── openai.go    # OpenAI API integration
│   │
│   ├── output/          # Output handlers
│   │   └── stdout.go    # Standard output handler
│   │
│   └── reader/          # Input readers
│       └── stdin.go     # Standard input reader
│
├── docs/                # Documentation assets
├── examples/            # Configuration examples
│   └── config.yml      # Example configuration
├── build/              # Build artifacts
├── Makefile            # Build automation
├── go.mod              # Go module definition
└── go.sum              # Go module checksums
```

### Official Color Palette

When creating UI components or skins, use these official colors:

* **Light Blue**: `#0F9EFC`
* **Black**: `#000000`
* **Green**: `#49E209`
* **White**: `#FFFFFF`
* **Dark Blue**: `#081C39`
* **Gray**: `#BCBEC0`

### Development Workflow

#### Before Committing

Run these commands before every commit:

```bash
# Format code
make fmt

# Run linter
make vet

# Run tests
make test

# Build to ensure compilation
make build
```

**Or run all at once**:

```bash
make dev
```

#### Creating a Pull Request

1. **Update your branch** with latest main

   ```bash
   git fetch upstream
   git rebase upstream/main
   ```
2. **Ensure all checks pass**

   ```bash
   make dev
   ```
3. **Push to your fork**

   ```bash
   git push origin feature/my-feature
   ```
4. **Create PR on GitHub**
   * Go to your fork on GitHub
   * Click "Compare & pull request"
   * Fill out the PR template
   * Link related issues
   * Request review from maintainers
5. **Address review feedback**
   * Make requested changes
   * Push updates to same branch
   * Respond to comments
6. **Merge**
   * Maintainer will merge when approved
   * Delete your feature branch after merge

### Release Process

Releases are handled by maintainers:

1. Update version numbers
2. Update `CHANGELOG.md`
3. Create git tag
4. Push tag to trigger release build
5. GitHub Actions creates the release
6. Binaries are automatically built and attached

### Questions?

* **GitHub Issues**: [Open an issue](https://github.com/control-theory/gonzo/issues) with the `question` label
* **GitHub Discussions**: [Start a discussion](https://github.com/control-theory/gonzo/discussions)
* **Email**: Contact maintainers directly

### Thank You!

Thank you for contributing to Gonzo! Every contribution, no matter how small, makes a difference. 🎉

**Related Documentation**:

* Development Setup - Setting up your environment
* Community - Engaging with the community
* Architecture Overview - Understanding the codebase

{% hint style="info" %}
**First time contributor?** Look for issues labeled ["good first issue"](https://github.com/control-theory/gonzo/labels/good%20first%20issue) to get started!
{% endhint %}


# Community

Welcome to the Gonzo community! This page helps you connect with other users, contribute to the project, and get support.

### Getting Involved

#### For Users

**Share Your Experience**:

* ⭐ Star the project on [GitHub](https://github.com/control-theory/gonzo)
* 📝 Write blog posts about using Gonzo
* 🐦 Share tips and tricks on social media
* 💬 Help answer questions in discussions
* 📸 Share screenshots of your setups

**Provide Feedback**:

* 🐛 Report bugs you encounter
* 💡 Suggest new features
* 📊 Share use cases we haven't considered
* 🎨 Propose UI improvements

#### For Developers

**Contribute Code**:

* 🔧 Fix bugs
* ✨ Implement new features
* 🧪 Add tests
* 📚 Improve documentation
* 🎨 Create custom skins
* 📋 Create custom format parsers

**Help Others**:

* 🤝 Review pull requests
* 👥 Mentor new contributors
* 💬 Answer technical questions
* 📖 Improve documentation clarity

### Blog & Content

**ControlTheory Blog**: Regular posts about Gonzo, log analysis, and SRE practices

* [View all blog posts →](https://www.controltheory.com/blog/)
* [Subscribe to newsletter →](https://www.controltheory.com/newsletter)

### Communication Channels

#### GitHub

**Primary Platform**: <https://github.com/control-theory/gonzo>

**Issues**: Report bugs and request features

* Bug reports: Use the bug template
* Feature requests: Use the enhancement template
* Questions: Use the question label
* Good first issues: Look for "good first issue" label

**Discussions**: General conversations

* Q\&A: Ask and answer questions
* Ideas: Brainstorm new features
* Show and tell: Share what you've built
* General: Anything Gonzo-related

**Pull Requests**: Contribute code

* Fork, branch, commit, push
* Follow contribution guidelines
* Wait for review and feedback
* Iterate based on comments

#### ControlTheory Website

**Blog**: <https://www.controltheory.com/blog/>

* Product announcements
* Technical deep dives
* Use case studies
* Best practices

**Documentation**: <https://docs.controltheory.com/gonzo>

* Comprehensive guides
* API documentation
* Examples and tutorials
* Troubleshooting tips

#### Social Media

**Twitter/X**: Follow [@ControlTheoryHQ](https://twitter.com/ControlTheoryHQ)

* Product updates
* Quick tips
* Community highlights

**LinkedIn**: [ControlTheory Company Page](https://www.linkedin.com/company/controltheory)

* Professional updates
* Case studies
* Job postings

### Recognition

#### Contributors

We recognize and celebrate all contributors:

**Hall of Fame**:

* Listed in GitHub contributors
* Mentioned in release notes
* Featured in project README
* Community spotlight posts

**Special Recognition**:

* 🥇 **Top Contributors**: Most impactful contributions
* 🏆 **Bug Hunters**: Found and reported critical bugs
* 📚 **Documentation Heroes**: Significantly improved docs
* 🎨 **Design Contributors**: Created popular skins/themes
* 🔧 **Tool Builders**: Created useful extensions

#### Star History

See our growth: [Star History Chart](https://star-history.com/#control-theory/gonzo\&Date)

Help us reach more users by starring the project!

### Resources

#### Learning Resources

**Getting Started**:

* Quick Start Guide
* Installation
* Basic Usage

**Advanced Topics**:

* AI Integration
* OTLP Protocol
* Custom Formats

**For Contributors**:

* Development Setup
* Contribution Guidelines
* Architecture Overview

#### Example Configurations

**Community Configs**:

* Check `examples/` directory in repository
* Browse community-shared configurations
* Submit your own configs via PR

**Custom Formats**:

* Apache/Nginx parsers
* Application-specific formats
* Cloud service integrations

**Custom Skins**:

* Color scheme variations
* Brand-specific themes
* Accessibility-focused themes

### Community Projects

#### Integrations

**Log Shippers**:

* Fluent Bit configurations
* Logstash pipelines
* Vector configs

**Monitoring Systems**:

* Prometheus integration
* Grafana dashboards
* Alertmanager rules

**CI/CD**:

* GitHub Actions workflows
* GitLab CI pipelines
* Jenkins integrations

#### Tools & Extensions

**Community Tools**:

* Log generators for testing
* Format converters
* Analysis scripts
* Automation tools

**Complementary Projects**:

* Log aggregation tools
* Parsing libraries
* Visualization tools

Submit your projects to be featured here!

### Events & Activities

#### Hackathons

Participate in Gonzo-focused hackathons:

* Build new features
* Create integrations
* Design themes
* Write documentation

**Past Hackathons**:

* Check GitHub discussions for recaps
* See winning projects
* Get inspired for future events

#### Community Calls

**Monthly Community Calls** (when scheduled):

* Product roadmap discussions
* Feature demonstrations
* Q\&A with maintainers
* Community presentations

Watch for announcements in GitHub Discussions.

#### Meetups

**Virtual Meetups**:

* User presentations
* Live demos
* Technical discussions
* Networking

**Local Meetups**:

* Connect with local users
* In-person demos
* Collaborative sessions

Interested in organizing? Reach out to maintainers!

### Support

#### Getting Help

**Documentation First**:

* Check [documentation](https://docs.controltheory.com/gonzo)
* Search [existing issues](https://github.com/control-theory/gonzo/issues)
* Browse [discussions](https://github.com/control-theory/gonzo/discussions)

**Ask the Community**:

* Post in GitHub Discussions (Q\&A)
* Open an issue with "question" label
* Share details about your setup

**Commercial Support**:

* Email: <support@controltheory.com>
* Enterprise support plans available
* Custom feature development

#### Reporting Security Issues

**⚠️ Do not open public issues for security vulnerabilities**

Instead:

* Email: <security@controltheory.com>
* Provide detailed description
* Include steps to reproduce
* Suggest potential fixes if possible

We aim to respond within 48 hours.

### Code of Conduct

#### Our Pledge

We pledge to make participation in our community a harassment-free experience for everyone, regardless of:

* Age, body size, disability
* Ethnicity, gender identity and expression
* Experience level
* Nationality, personal appearance
* Race, religion
* Sexual identity and orientation

#### Our Standards

**Positive Behavior**:

* ✅ Using welcoming and inclusive language
* ✅ Being respectful of differing viewpoints
* ✅ Gracefully accepting constructive criticism
* ✅ Focusing on what is best for the community
* ✅ Showing empathy towards others

**Unacceptable Behavior**:

* ❌ Trolling, insulting, or derogatory comments
* ❌ Personal or political attacks
* ❌ Public or private harassment
* ❌ Publishing others' private information
* ❌ Other conduct inappropriate in professional settings

#### Enforcement

Violations may result in:

* Warning
* Temporary ban
* Permanent ban

Report issues to: <conduct@controltheory.com>

### Roadmap

#### Current Focus

**Short-term** (Next 3 months):

* Performance improvements
* Bug fixes and stability
* Documentation enhancements
* Community feedback implementation

**Medium-term** (3-6 months):

* New AI providers
* Enhanced OTLP features
* Additional integrations
* Plugin system

**Long-term** (6+ months):

* Distributed log analysis
* Advanced visualizations
* Cloud-native deployments
* Enterprise features

See [GitHub Projects](https://github.com/control-theory/gonzo/projects) for detailed roadmap.

#### Influence the Roadmap

**Your input matters**:

* 👍 Upvote issues you care about
* 💬 Comment on proposals
* 📝 Submit feature requests
* 🗳️ Participate in polls

Popular requests get prioritized!

### Credits

#### Built With

Gonzo is built with these amazing open-source projects:

* [**Bubble Tea**](https://github.com/charmbracelet/bubbletea) - TUI framework
* [**Lipgloss**](https://github.com/charmbracelet/lipgloss) - Styling library
* [**Bubbles**](https://github.com/charmbracelet/bubbles) - TUI components
* [**Cobra**](https://github.com/spf13/cobra) - CLI framework
* [**Viper**](https://github.com/spf13/viper) - Configuration
* [**OpenTelemetry**](https://opentelemetry.io/) - Observability standard
* [**drain3**](https://github.com/logpai/Drain3) - Pattern extraction

#### Inspiration

Inspired by:

* [**k9s**](https://k9scli.io/) - Kubernetes TUI
* [**stern**](https://github.com/stern/stern) - Multi-pod log tailing
* [**lnav**](https://lnav.org/) - Log file navigator

#### Team

**Maintainers**:

* Core maintainers listed in [GitHub](https://github.com/control-theory/gonzo)
* ControlTheory team

**Contributors**:

* See [Contributors](https://github.com/control-theory/gonzo/graphs/contributors)
* Everyone who reported bugs
* Everyone who suggested features
* Everyone who improved docs

#### Sponsors

Support Gonzo's development:

* GitHub Sponsors (coming soon)
* Open Collective (coming soon)
* Corporate sponsorship inquiries: <partnerships@controltheory.com>

### Stay Connected

#### Newsletter

Subscribe to our newsletter:

* Product updates
* Tips and tricks
* Community highlights
* Event announcements

Sign up at: <https://www.controltheory.com/newsletter>

#### Blog

Read the latest:

* [**Gonzo Blog**](https://www.controltheory.com/blog/tag/gonzo)
* Technical articles
* Use cases
* Best practices

#### Social Media

Follow us:

* **Twitter/X**: [@ControlTheoryHQ](https://twitter.com/ControlTheoryHQ)
* **LinkedIn**: [ControlTheory](https://www.linkedin.com/company/controltheory)
* **GitHub**: [control-theory](https://github.com/control-theory)

#### Contact

**General Inquiries**: <hello@controltheory.com> **Support**: <support@controltheory.com> **Security**: <security@controltheory.com> **Press**: <press@controltheory.com> **Partnerships**: <partnerships@controltheory.com>

***

### Thank You! 🎉

Thank you for being part of the Gonzo community. Whether you're using it, contributing to it, or just checking it out - we appreciate you!

**Together, we're making log analysis better for everyone.**

{% hint style="success" %}
**Want to get involved?** Start by starring the [GitHub repo](https://github.com/control-theory/gonzo), join the [discussions](https://github.com/control-theory/gonzo/discussions), and say hello!
{% endhint %}


# How to Get Help

Need assistance with Gonzo? Here are the best ways to get support:

#### 💬 Slack Community

Join our Slack workspace to connect with other users and get help:

* [Join Slack](https://join.slack.com/t/ctrltheorycommunity/shared_invite/zt-3dr6rke5w-GlcRaW2bvn4zcSaV8byZgA)

#### GitHub Issues

[Open an issue](https://github.com/control-theory/gonzo/issues/new) for:

* 🐛 Bug reports (include OS, Go version, steps to reproduce)
* 💡 Feature requests
* ❓ General questions

When opening an issue (bug), please try to include:

* Your OS and Go version
* Steps to reproduce
* Expected vs actual behavior
* Log samples (sanitized if needed)

#### Documentation

* [Usage Guide](https://github.com/control-theory/gonzo/blob/main/USAGE_GUIDE.md)
* [Contributing Guide](https://github.com/control-theory/gonzo/blob/main/CONTRIBUTING.md)
* [Changelog](https://github.com/control-theory/gonzo/blob/main/CHANGELOG.md)

#### Contact

For other inquiries: <support@controltheory.com>


# Reference

Welcome to the Gonzo reference documentation! This section provides comprehensive technical reference material for all aspects of Gonzo.

### Overview

The Reference section contains detailed specifications, complete lists, and quick-lookup information. Use this section when you need to:

* **Look up** a specific keyboard shortcut
* **Check** valid configuration options
* **Find** environment variable names
* **Review** version history and changes
* **Verify** exact syntax or values

### Quick Access

#### Need to find something fast?

**Keyboard shortcuts**: Keyboard Shortcuts\
**Configuration options**: Configuration Schema\
**Environment variables**: Environment Variables\
**Version history**: Changelog

### Reference Guides

#### Keyboard Shortcuts

Complete reference of all keyboard shortcuts and mouse interactions.

**What's inside**:

* Global shortcuts (Space, q, r, etc.)
* Panel navigation (Tab, arrow keys)
* Log viewer controls
* AI feature shortcuts
* Search and filter shortcuts
* Vim-style navigation
* Mouse support
* Quick reference card (printable)

**Use when**:

* Learning keyboard shortcuts
* Looking up a specific key
* Wanting to optimize your workflow
* Printing a cheat sheet

**Quick examples**:

```
Space    - Pause/Resume
Enter    - View details
/        - Filter logs
i        - AI analysis
m        - Switch AI model
```

#### Configuration Schema

Complete specification of the configuration file format.

**What's inside**:

* Full YAML schema
* All configuration options
* Valid value types and ranges
* Default values
* Complete examples
* Validation rules
* Best practices

**Use when**:

* Creating a config file
* Validating configuration syntax
* Understanding default values
* Checking valid ranges
* Troubleshooting config issues

**Quick example**:

```yaml
files:
  - "/var/log/app.log"
follow: true
update-interval: 2s
log-buffer: 2000
skin: dracula
```

#### Environment Variables

Complete reference of all environment variables.

**What's inside**:

* Gonzo-specific variables
* AI provider variables
* System variables
* Variable precedence
* Configuration examples
* Docker/Kubernetes usage
* Shell profile setup

**Use when**:

* Setting up environment
* Container deployments
* CI/CD pipelines
* Debugging configuration
* Checking precedence

**Quick examples**:

```bash
GONZO_FILES="/var/log/app.log"
GONZO_FOLLOW="true"
OPENAI_API_KEY="sk-..."
GONZO_AI_MODEL="gpt-4"
```

#### Changelog

Version history and release notes.

**What's inside**:

* All version releases
* New features by version
* Bug fixes
* Breaking changes
* Upgrade notes
* Known issues
* Roadmap

**Use when**:

* Checking what's new
* Planning upgrades
* Understanding changes
* Reviewing history
* Checking compatibility

**Latest version**: 0.1.6 (August 2024)

### How to Use This Section

#### As a Quick Reference

**Keep these open while working**:

* Keyboard Shortcuts - For quick lookups
* Print the quick reference card for your desk

**Bookmark for frequent use**:

* Configuration Schema - When editing config
* Environment Variables - When setting up

#### As Complete Documentation

**Read through for comprehensive understanding**:

* Start with Configuration Schema
* Learn all shortcuts in Keyboard Shortcuts
* Understand precedence in Environment Variables
* Track changes via Changelog

#### As Troubleshooting Aid

**When something's not working**:

1. Check Configuration Schema for valid values
2. Verify environment in Environment Variables
3. Review Changelog for known issues
4. Try shortcuts from Keyboard Shortcuts

### Common Lookup Tasks

#### Find a Keyboard Shortcut

**Question**: "How do I pause the dashboard?"

**Answer**: Check Keyboard Shortcuts → Global Shortcuts

* `Space` - Pause/Resume

#### Validate Config Setting

**Question**: "What values can `update-interval` have?"

**Answer**: Check Configuration Schema → Performance Settings

* Type: `duration`
* Examples: `"500ms"`, `"1s"`, `"2s"`, `"5s"`

#### Find Environment Variable

**Question**: "How do I set the log buffer size via environment?"

**Answer**: Check Environment Variables → Performance Settings

* `GONZO_LOG_BUFFER="2000"`

#### Check Version Changes

**Question**: "What's new in version 0.1.6?"

**Answer**: Check Changelog → \[0.1.6]

* Full screen log viewing (`f` key)
* Extended search character limit
* OTLP message size increase

### Configuration Priority

Understanding how configuration is applied:

**Priority Order** (highest to lowest):

1. **Command line flags** - `gonzo --update-interval=2s`
2. **Environment variables** - `GONZO_UPDATE_INTERVAL="2s"`
3. **Configuration file** - `~/.config/gonzo/config.yml`
4. **Default values** - Built-in defaults

**Example**:

```bash
# config.yml says: update-interval: 10s
export GONZO_UPDATE_INTERVAL="5s"
gonzo --update-interval=1s
# Result: Uses 1s (flag overrides all)
```

Learn more in Configuration Schema and Environment Variables.

### Quick Reference Cards

#### Configuration Quick Card

```yaml
# Essential configuration
files: ["/var/log/app.log"]
follow: true
update-interval: 2s
log-buffer: 2000
memory-size: 15000
skin: dracula
ai-model: "gpt-4"
```

#### Environment Quick Card

```bash
# Essential environment variables
export GONZO_FILES="/var/log/app.log"
export GONZO_FOLLOW="true"
export GONZO_UPDATE_INTERVAL="2s"
export OPENAI_API_KEY="sk-..."
export GONZO_AI_MODEL="gpt-4"
```

#### Keyboard Quick Card

```
ESSENTIAL KEYS
─────────────
Space    Pause/Resume
q        Quit
/        Filter
s        Search
Enter    View details
ESC      Cancel/Close
i        AI analysis
m        Switch model
```

### Version Information

**Current Version**: 0.1.6\
**Release Date**: August 27, 2024\
**Go Version**: 1.21+ required\
**License**: MIT

See Changelog for complete version history.

### Compatibility

#### Platform Support

* **Linux**: All major distributions
* **macOS**: 10.15 and later
* **Windows**: Windows 10+ (WSL recommended)

#### Terminal Compatibility

**Recommended**:

* iTerm2 (macOS)
* Alacritty (Cross-platform)
* Windows Terminal (Windows)
* GNOME Terminal (Linux)
* Kitty (Cross-platform)

**Requirements**:

* Minimum 80x24 size
* 256 color support
* UTF-8 encoding

#### Go Version

**Required**: Go 1.21 or higher (for building from source)

**Check version**:

```bash
go version
```

### Related Documentation

#### Configuration Guides

* **Configuration File Guide** - Detailed config guide
* **CLI Reference** - Command line options
* **Advanced Configuration** - Advanced topics

#### User Guides

* **Quick Start** - Get started quickly
* **Basic Usage** - Learn the basics
* **Navigation & Controls** - Master the interface

#### Technical Docs

* **Architecture Overview** - How Gonzo works
* **OTLP Protocol** - Protocol details
* **Extension Points** - Extending Gonzo

### Printable Resources

#### Cheat Sheets

Create your own cheat sheets from these pages:

**Keyboard Shortcuts**:

* Print the quick reference card
* Keep near your workstation

**Configuration Template**:

* Copy the complete example
* Customize for your needs

**Environment Setup**:

* Use shell profile templates
* Add to your `.bashrc` or `.zshrc`

### Contributing to Reference Docs

Found an error or missing information?

**How to help**:

* [Open an issue](https://github.com/control-theory/gonzo/issues) to report problems
* [Submit a PR](https://github.com/control-theory/gonzo/pulls) to fix errors
* Suggest improvements via [Discussions](https://github.com/control-theory/gonzo/discussions)

See Contributing Guidelines for details.

### Keeping Up to Date

#### Stay Current

**Watch for updates**:

* Star the [GitHub repository](https://github.com/control-theory/gonzo)
* Watch for release notifications
* Check Changelog regularly
* Follow [@ControlTheoryHQ](https://twitter.com/ControlTheoryHQ)

**Update Gonzo**:

```bash
# Via go install
go install github.com/control-theory/gonzo/cmd/gonzo@latest

# Via Homebrew
brew upgrade gonzo

# Check version
gonzo --version
```

### Support

#### Need Help?

**For reference questions**:

* Search this Reference section
* Check related documentation
* Look in Troubleshooting

**For other help**:

* [GitHub Discussions](https://github.com/control-theory/gonzo/discussions) - Q\&A
* [GitHub Issues](https://github.com/control-theory/gonzo/issues) - Bug reports
* Email: <support@controltheory.com>

### Feedback

#### Improve These Docs

Help make reference docs better:

**What works well**:

* Clear examples
* Complete coverage
* Easy navigation
* Quick lookups

**We're working on**:

* Searchability
* More examples
* Better organization
* Interactive demos

**Your feedback matters**: [Share suggestions →](https://github.com/control-theory/gonzo/discussions)

***

### Navigate Reference Docs

Choose what you need:

**⌨️ Keyboard Shortcuts** - All shortcuts and mouse actions

**⚙️ Configuration Schema** - Complete config file reference

**🌍 Environment Variables** - All environment variables

**📋 Changelog** - Version history and release notes

{% hint style="info" %}
**Pro Tip**: Bookmark the pages you reference most often. The Keyboard Shortcuts and Environment Variables pages are frequently accessed.
{% endhint %}


# Keyboard Shortcuts

Complete reference of all keyboard shortcuts available in Gonzo. Master these to become a power user!

### Global Shortcuts

These shortcuts work from anywhere in the interface:

| Key             | Action                    | Description                                    |
| --------------- | ------------------------- | ---------------------------------------------- |
| `Space`         | Pause/Unpause             | Freeze dashboard updates (logs still buffer)   |
| `r`             | Reset                     | Clear all data and reset dashboard             |
| `q` or `Ctrl+C` | Quit                      | Exit Gonzo                                     |
| `?` or `h`      | Help                      | Show help screen with shortcuts                |
| `/`             | Filter                    | Enter filter mode (supports regex)             |
| `s`             | Search                    | Search and highlight text in logs              |
| `ESC`           | Cancel/Clear              | Clear filters, close modals, or cancel actions |
| `u`             | Cycle Interval (Forward)  | Increase update interval (1s→2s→5s→10s)        |
| `U`             | Cycle Interval (Backward) | Decrease update interval                       |

### Navigation Shortcuts

#### Panel Navigation

| Key         | Action         | Description                                |
| ----------- | -------------- | ------------------------------------------ |
| `Tab`       | Next Panel     | Move to next panel (clockwise)             |
| `Shift+Tab` | Previous Panel | Move to previous panel (counter-clockwise) |
| Mouse Click | Focus Panel    | Click any panel to switch focus            |

**Panel Order**: Log Viewer → Word Frequency → Attributes → Counts → (repeat)

#### Within Panels

| Key         | Action         | Description                                |
| ----------- | -------------- | ------------------------------------------ |
| `↑` or `k`  | Move Up        | Move selection up one entry                |
| `↓` or `j`  | Move Down      | Move selection down one entry              |
| `←` or `h`  | Scroll Left    | Horizontal scroll left                     |
| `→` or `l`  | Scroll Right   | Horizontal scroll right                    |
| `PgUp`      | Page Up        | Move up one page (\~10 entries)            |
| `PgDn`      | Page Down      | Move down one page (\~10 entries)          |
| `Home`      | Jump to Top    | Jump to first entry (pauses auto-scroll)   |
| `End`       | Jump to Bottom | Jump to latest entry (resumes auto-scroll) |
| Mouse Wheel | Scroll         | Scroll through content                     |

### Log Viewer Shortcuts

Specific to the Log Viewer panel (top-left):

| Key     | Action         | Description                        |
| ------- | -------------- | ---------------------------------- |
| `Enter` | View Details   | Open detailed view of selected log |
| `c`     | Toggle Columns | Show/hide Host and Service columns |
| `f`     | Full Screen    | Toggle full screen log viewing     |

#### Auto-Scroll Behavior

* **Scrolling up** or pressing `Home` → Pauses auto-scroll
* **Pressing `End`** → Resumes auto-scroll to latest logs
* **Status indicator**: Shows `FOLLOWING` when auto-scrolling

### Detail View Shortcuts

When viewing a log entry's details (after pressing `Enter`):

| Key             | Action       | Description                          |
| --------------- | ------------ | ------------------------------------ |
| `↑` / `↓`       | Scroll       | Scroll through log details           |
| `PgUp` / `PgDn` | Page Scroll  | Scroll by page                       |
| `i`             | AI Analysis  | Instant AI analysis of this log      |
| `c`             | AI Chat      | Start AI chat conversation about log |
| `Tab`           | Switch Pane  | Switch between details and chat pane |
| `m`             | Switch Model | Open model selection modal           |
| `ESC`           | Close        | Return to main dashboard             |

### AI Features Shortcuts

Available when AI is configured:

| Key | Action           | Description                                      |
| --- | ---------------- | ------------------------------------------------ |
| `i` | Instant Analysis | Get AI insights on selected log (in detail view) |
| `c` | Chat Mode        | Start conversational analysis (in detail view)   |
| `m` | Model Selection  | Choose different AI model                        |

#### In Model Selection Modal

| Key             | Action      | Description                        |
| --------------- | ----------- | ---------------------------------- |
| `↑` / `↓`       | Navigate    | Move through model list            |
| `PgUp` / `PgDn` | Page Scroll | Scroll by page                     |
| Mouse Wheel     | Scroll      | Scroll through models              |
| `Enter`         | Select      | Choose highlighted model           |
| `ESC`           | Cancel      | Close modal without changing model |

### Counts Modal Shortcuts

When viewing the detailed Counts analysis (press `Enter` on Counts panel):

| Key             | Action      | Description              |
| --------------- | ----------- | ------------------------ |
| `↑` / `↓`       | Scroll      | Scroll through analysis  |
| `PgUp` / `PgDn` | Page Scroll | Scroll by page           |
| Mouse Wheel     | Scroll      | Scroll content           |
| `ESC`           | Close       | Return to main dashboard |

**Modal Contents**:

* Time-series heatmap (60-minute window)
* Top 3 patterns per severity level
* Top 3 services per severity level

### Search and Filter Shortcuts

#### Filter Mode

Press `/` to enter filter mode:

| Key       | Action | Description                           |
| --------- | ------ | ------------------------------------- |
| Type text | Filter | Enter filter pattern (supports regex) |
| `Enter`   | Apply  | Apply filter                          |
| `ESC`     | Cancel | Cancel without applying               |

**Filter Examples**:

* `error` - Show logs containing "error"
* `error\|warn` - Show errors OR warnings (regex)
* `payment.*failed` - Regex pattern matching

#### Search Mode

Press `s` to enter search mode:

| Key       | Action | Description               |
| --------- | ------ | ------------------------- |
| Type text | Search | Enter search term         |
| `Enter`   | Apply  | Highlight matches         |
| `ESC`     | Clear  | Clear search highlighting |

### View Options

| Key | Action         | Description                                 |
| --- | -------------- | ------------------------------------------- |
| `c` | Toggle Columns | Show/hide Host/Service columns (Log Viewer) |
| `f` | Full Screen    | Toggle full screen view (Log Viewer)        |

### Mouse Support

Gonzo supports mouse interactions:

#### Click Actions

| Mouse Action     | Result                |
| ---------------- | --------------------- |
| Click panel      | Switch focus to panel |
| Click log entry  | Select entry          |
| Double-click log | Open detail view      |
| Click button     | Activate button       |

#### Scroll Actions

| Mouse Action | Result                            |
| ------------ | --------------------------------- |
| Wheel up     | Scroll up                         |
| Wheel down   | Scroll down                       |
| Shift+Wheel  | Horizontal scroll (if applicable) |

### Quick Reference Card

Print this reference for quick access:

```
═══════════════════════════════════════════════════════════
                    GONZO KEYBOARD SHORTCUTS
═══════════════════════════════════════════════════════════

GLOBAL CONTROLS                 NAVIGATION
───────────────                 ──────────
Space    Pause/Resume           Tab           Next panel
r        Reset data             Shift+Tab     Previous panel
q        Quit                   ↑↓ or kj      Move up/down
?        Help                   ←→ or hl      Scroll left/right
/        Filter                 Home          Jump to top
s        Search                 End           Jump to bottom
ESC      Cancel/Clear           PgUp/PgDn     Page scroll

LOG VIEWER                      AI FEATURES
──────────                      ───────────
Enter    View details           i        Instant analysis
c        Toggle columns         c        Chat mode
f        Full screen            m        Switch model

VIEW OPTIONS                    DETAIL VIEW
────────────                    ───────────
u/U      Cycle interval         ↑↓       Scroll
                               ESC      Close
                               Tab      Switch pane
                               i        AI analysis
                               c        AI chat

═══════════════════════════════════════════════════════════
```

### Vim-Style Navigation

Gonzo supports Vim-style keybindings for navigation:

| Vim Key | Standard Key | Action |
| ------- | ------------ | ------ |
| `h`     | `←`          | Left   |
| `j`     | `↓`          | Down   |
| `k`     | `↑`          | Up     |
| `l`     | `→`          | Right  |

**Why Vim keys?**

* Faster navigation (no need to move to arrow keys)
* Familiar to Vim/Vi users
* More ergonomic hand position

### Customizing Shortcuts

Currently, keyboard shortcuts are not customizable. This is a planned feature for future releases.

**Workaround**: Use terminal key remapping if needed.

### Keyboard Layout Considerations

#### QWERTY

All shortcuts are optimized for QWERTY keyboard layout.

#### Other Layouts

If you use Dvorak, Colemak, or other layouts:

* Physical key positions may differ
* Consider using arrow keys instead of `hjkl`
* Terminal remapping may help

#### International Keyboards

* Shortcuts use ASCII characters
* Should work on most international keyboards
* Some special keys may vary by layout

### Accessibility

#### For Users with Limited Mobility

* **Full mouse support**: All actions available via mouse
* **Large click targets**: Panels are easy to target
* **No rapid key sequences**: All shortcuts are single key or simple combo

#### For Screen Reader Users

Gonzo is a visual terminal UI and may have limited screen reader support. We're working on improvements:

* Alternative text modes
* Better semantic structure
* Keyboard-only navigation

### Common Workflows

#### Efficient Log Review

```
1. Start Gonzo
2. Space (pause)
3. ↑↓ or kj (navigate)
4. Enter (view details)
5. ESC (close)
6. Space (resume)
```

#### Quick Filtering

```
1. / (filter mode)
2. Type: error
3. Enter (apply)
4. Review filtered logs
5. ESC (clear filter)
```

#### AI Analysis

```
1. Navigate to log
2. Enter (open details)
3. i (instant analysis)
4. Read AI response
5. c (start chat if needed)
6. ESC (close)
```

#### Deep Pattern Investigation

```
1. Navigate to Counts panel (Tab)
2. Enter (open modal)
3. Review heatmap and patterns
4. ↑↓ (scroll through analysis)
5. ESC (close modal)
```

### Tips & Tricks

#### Speed Tips

* **Use Vim keys**: `hjkl` is faster than arrow keys
* **Tab navigation**: Quickly jump between panels
* **Space for investigation**: Pause to review, resume when done
* **Home/End**: Quick jumps to top/bottom

#### Workflow Tips

* **Filter before detail**: Use `/` to narrow down before diving in
* **Pause for AI**: Pause dashboard before AI analysis for stability
* **Reset regularly**: Press `r` to clear old data and start fresh
* **Use search**: `s` to highlight without filtering

#### Power User Tricks

* **Combine filters**: Use regex in `/` for complex patterns
* **Quick model switch**: `m` to try different AI models
* **Full screen logs**: `f` for better readability
* **Column toggle**: `c` to see more or less info

### Troubleshooting

#### Shortcuts Not Working

**Key not responding**:

* Ensure panel has focus (click or Tab to it)
* Check if modal is open (ESC to close)
* Verify keyboard layout is correct

**Mouse not working**:

* Check terminal supports mouse (most modern ones do)
* Try keyboard navigation instead
* Update terminal if issues persist

#### Conflicts with Terminal

Some terminals intercept keys:

* `Ctrl+C` - May be caught by terminal (use `q` instead)
* `Ctrl+Z` - Typically suspends process
* Function keys - May not work in all terminals

**Solution**: Use alternative keys or configure terminal.

### Platform-Specific Notes

#### macOS

* `Cmd` key not used (terminal limitation)
* All standard shortcuts work
* Mouse support excellent in iTerm2, Terminal.app

#### Linux

* All shortcuts work as documented
* Mouse support varies by terminal
* Works great in GNOME Terminal, Alacritty, Kitty

#### Windows

* All shortcuts work in Windows Terminal
* Some older terminals have limited mouse support
* Git Bash supports all features

### Related Documentation

* **Navigation & Controls** - Detailed navigation guide
* **Interface Overview** - Understanding the UI
* **AI Integration** - Using AI features

{% hint style="success" %}
**Pro Tip**: Print out the Quick Reference Card and keep it nearby while learning Gonzo. You'll memorize the shortcuts quickly!
{% endhint %}

{% hint style="info" %}
**Missing a shortcut?** Suggest new shortcuts by [opening an issue](https://github.com/control-theory/gonzo/issues) on GitHub!
{% endhint %}


# Configuration Schema

Complete reference for Gonzo's configuration file format. This guide documents all available configuration options and their valid values.

### Configuration File Location

**Default location**: `~/.config/gonzo/config.yml`

**Custom location**: Specify with `--config` flag

```bash
gonzo --config /path/to/config.yml
```

### File Format

Gonzo uses YAML format for configuration files.

**Basic structure**:

```yaml
# Input configuration
files: []
follow: false

# Performance settings
update-interval: 1s
log-buffer: 1000
memory-size: 10000

# Display settings
skin: default

# AI configuration
ai-model: ""

# OTLP receiver
otlp:
  enabled: false
  grpc-port: 4317
  http-port: 4318
```

### Complete Schema

#### Input Configuration

**`files`**

**Type**: `array of strings`\
**Default**: `[]` (empty, uses stdin)\
**Description**: List of log files or glob patterns to read

```yaml
files:
  - "/var/log/app.log"
  - "/var/log/error.log"
  - "/var/log/*.log"
```

**Notes**:

* Supports glob patterns
* Can specify multiple files
* Paths can be relative or absolute
* Empty array uses stdin

**`follow`**

**Type**: `boolean`\
**Default**: `false`\
**Description**: Follow log files in real-time (like `tail -f`)

```yaml
follow: true
```

**Notes**:

* Only applies to file input
* When `true`, watches files for new content
* Useful for monitoring live logs

#### Performance Settings

**`update-interval`**

**Type**: `duration`\
**Default**: `"1s"`\
**Valid values**: Any Go duration string\
**Description**: How often the dashboard updates

```yaml
update-interval: 2s
```

**Examples**:

* `"500ms"` - Half second
* `"1s"` - One second (default)
* `"2s"` - Two seconds
* `"5s"` - Five seconds
* `"10s"` - Ten seconds

**Notes**:

* Lower values = more responsive but higher CPU
* Higher values = lower CPU but less responsive
* Can be changed at runtime with `u`/`U` keys

**`log-buffer`**

**Type**: `integer`\
**Default**: `1000`\
**Valid range**: `1` to `100000`\
**Description**: Maximum number of log entries to keep in memory

```yaml
log-buffer: 2000
```

**Notes**:

* Circular buffer (old logs evicted when full)
* Higher values use more memory
* Lower values may lose old logs faster
* Consider log volume when setting

**`memory-size`**

**Type**: `integer`\
**Default**: `10000`\
**Valid range**: `100` to `1000000`\
**Description**: Maximum number of words to track for frequency analysis

```yaml
memory-size: 15000
```

**Notes**:

* Affects Word Frequency panel
* Higher values track more unique words
* Lower values use less memory
* LRU eviction when limit reached

#### Display Settings

**`skin`**

**Type**: `string`\
**Default**: `"default"`\
**Valid values**: Any installed skin name\
**Description**: Color scheme/theme to use

```yaml
skin: dracula
```

**Built-in skins**:

**Dark themes**:

* `default` - Gonzo default dark
* `controltheory-dark` - ControlTheory branded
* `dracula` - Dracula theme
* `gruvbox` - Gruvbox dark
* `monokai` - Monokai
* `nord` - Nord theme
* `solarized-dark` - Solarized dark

**Light themes**:

* `controltheory-light` - ControlTheory branded
* `github-light` - GitHub light
* `solarized-light` - Solarized light
* `vs-code-light` - VS Code light
* `spring` - Spring theme

**Notes**:

* Custom skins go in `~/.config/gonzo/skins/`
* Can be changed via command line: `--skin=NAME`

#### AI Configuration

**`ai-model`**

**Type**: `string`\
**Default**: `""` (auto-select best available)\
**Description**: AI model to use for log analysis

```yaml
ai-model: "gpt-4"
```

**Common values**:

* `""` - Auto-select (recommended)
* `"gpt-4"` - OpenAI GPT-4
* `"gpt-3.5-turbo"` - OpenAI GPT-3.5
* `"llama3"` - Ollama Llama 3
* `"mistral"` - Ollama Mistral
* Model names from your AI provider

**Notes**:

* Requires `OPENAI_API_KEY` environment variable
* Can be overridden with `--ai-model` flag
* Can be changed at runtime with `m` key

#### OTLP Receiver Configuration

**`otlp.enabled`**

**Type**: `boolean`\
**Default**: `false`\
**Description**: Enable OTLP log receiver

```yaml
otlp:
  enabled: true
```

**Notes**:

* Starts gRPC and HTTP servers
* Required for receiving OTLP logs
* Can be enabled via `--otlp-enabled` flag

**`otlp.grpc-port`**

**Type**: `integer`\
**Default**: `4317`\
**Valid range**: `1024` to `65535`\
**Description**: Port for OTLP gRPC receiver

```yaml
otlp:
  enabled: true
  grpc-port: 5317
```

**Notes**:

* Standard OTLP port is 4317
* Change if port conflict exists
* Requires `otlp.enabled: true`

**`otlp.http-port`**

**Type**: `integer`\
**Default**: `4318`\
**Valid range**: `1024` to `65535`\
**Description**: Port for OTLP HTTP receiver

```yaml
otlp:
  enabled: true
  http-port: 5318
```

**Notes**:

* Standard OTLP HTTP port is 4318
* Change if port conflict exists
* Requires `otlp.enabled: true`

#### Advanced Configuration

**`test-mode`**

**Type**: `boolean`\
**Default**: `false`\
**Description**: Run without TTY for testing

```yaml
test-mode: true
```

**Notes**:

* For automated testing only
* Disables TUI
* Not for normal use

**`formats-dir`**

**Type**: `string`\
**Default**: `"~/.config/gonzo/formats"`\
**Description**: Directory containing custom format definitions

```yaml
formats-dir: "/custom/path/to/formats"
```

**Notes**:

* Override default formats directory
* Must contain `.yaml` format files
* Path can use `~` for home directory

### Complete Example

```yaml
# ~/.config/gonzo/config.yml
# Complete Gonzo configuration example

# ===== Input Configuration =====
# Files to read (supports glob patterns)
files:
  - "/var/log/app.log"
  - "/var/log/error.log"
  - "/var/log/nginx/*.log"

# Follow files in real-time (like tail -f)
follow: true

# ===== Performance Settings =====
# Dashboard update frequency
# Options: 500ms, 1s, 2s, 5s, 10s
update-interval: 2s

# Maximum log entries to keep in buffer
# Higher = more history, more memory
log-buffer: 2000

# Maximum unique words to track
# Higher = more words tracked, more memory
memory-size: 15000

# ===== Display Settings =====
# Color scheme (built-in or custom)
# Options: default, dracula, nord, monokai, etc.
skin: dracula

# ===== AI Configuration =====
# AI model for log analysis
# Empty string = auto-select best available
# Examples: "gpt-4", "gpt-3.5-turbo", "llama3"
ai-model: "gpt-4"

# ===== OTLP Receiver =====
# OpenTelemetry Protocol log receiver
otlp:
  # Enable OTLP receiver
  enabled: true
  
  # gRPC port (standard: 4317)
  grpc-port: 4317
  
  # HTTP port (standard: 4318)
  http-port: 4318

# ===== Advanced Settings =====
# Custom formats directory
# formats-dir: "~/.config/gonzo/formats"

# Test mode (for automated testing)
# test-mode: false
```

### Validation

#### Schema Validation

Gonzo validates configuration on startup:

**Valid config**: Gonzo starts normally\
**Invalid config**: Error message explains issue

**Common validation errors**:

* Invalid YAML syntax
* Unknown configuration keys
* Invalid value types
* Out-of-range values

#### Testing Configuration

Test your configuration:

```bash
# Try loading config
gonzo --config config.yml --help

# If no errors, config is valid
```

### Environment Variable Overrides

Environment variables override config file:

| Config Key        | Environment Variable    |
| ----------------- | ----------------------- |
| `files`           | `GONZO_FILES`           |
| `follow`          | `GONZO_FOLLOW`          |
| `update-interval` | `GONZO_UPDATE_INTERVAL` |
| `log-buffer`      | `GONZO_LOG_BUFFER`      |
| `memory-size`     | `GONZO_MEMORY_SIZE`     |
| `ai-model`        | `GONZO_AI_MODEL`        |
| `otlp.enabled`    | `GONZO_OTLP_ENABLED`    |
| `otlp.grpc-port`  | `GONZO_OTLP_GRPC_PORT`  |
| `otlp.http-port`  | `GONZO_OTLP_HTTP_PORT`  |

See Environment Variables for details.

### Command Line Flag Overrides

Command line flags override both config file and environment variables:

```bash
# Config file says follow: false
# This overrides it:
gonzo --config config.yml --follow

# Config file says update-interval: 2s
# This overrides it:
gonzo --config config.yml --update-interval=5s
```

**Priority** (highest to lowest):

1. Command line flags
2. Environment variables
3. Configuration file
4. Default values

### Configuration Best Practices

#### Production Use

```yaml
# Optimized for production monitoring
files:
  - "/var/log/production/*.log"
follow: true
update-interval: 2s  # Balance responsiveness and CPU
log-buffer: 5000     # Keep more history
memory-size: 20000   # Track more words
skin: default        # Consistent appearance
```

#### Development Use

```yaml
# Optimized for local development
files:
  - "/var/log/app.log"
  - "/tmp/debug.log"
follow: true
update-interval: 1s  # Fast updates
log-buffer: 1000     # Less history needed
memory-size: 10000   # Standard tracking
skin: dracula        # Personal preference
```

#### Resource-Constrained

```yaml
# Optimized for low-resource systems
files:
  - "/var/log/app.log"
follow: true
update-interval: 5s  # Reduce CPU
log-buffer: 500      # Minimal memory
memory-size: 5000    # Minimal tracking
skin: default
```

#### OTLP Receiver

```yaml
# Optimized for OTLP log ingestion
# No files needed - receives via network
otlp:
  enabled: true
  grpc-port: 4317
  http-port: 4318
update-interval: 1s  # Responsive for live logs
log-buffer: 2000     # Buffer network logs
memory-size: 15000
```

### Troubleshooting

#### Config Not Loading

**Symptom**: Settings ignored

**Checks**:

```bash
# Verify file exists
ls -la ~/.config/gonzo/config.yml

# Check YAML syntax
cat ~/.config/gonzo/config.yml

# Specify explicitly
gonzo --config ~/.config/gonzo/config.yml
```

#### Invalid YAML

**Symptom**: Parse error on startup

**Solution**:

* Check indentation (use spaces, not tabs)
* Verify colons have spaces after them
* Ensure strings with special chars are quoted
* Use YAML validator online

#### Values Not Applied

**Check priority**:

1. Is there a command line flag overriding?
2. Is there an environment variable set?
3. Is the config file being loaded?

```bash
# Check environment
env | grep GONZO

# Clear environment if needed
unset GONZO_UPDATE_INTERVAL
```

### Related Documentation

* **Environment Variables** - Environment variable reference
* **CLI Reference** - Command line options
* **Configuration File Guide** - Detailed configuration guide

{% hint style="info" %}
**Tip**: Start with the example configuration and modify only what you need. This ensures valid syntax and reasonable defaults.
{% endhint %}

{% hint style="warning" %}
**Note**: Changes to the config file require restarting Gonzo. Runtime changes can be made with keyboard shortcuts or flags.
{% endhint %}


# Environment Variables

Complete reference for environment variables that configure Gonzo's behavior. Environment variables provide a convenient way to configure Gonzo without command-line flags or config files.

### Overview

Environment variables are useful for:

* **Container deployments**: Configure via Docker/Kubernetes env vars
* **CI/CD pipelines**: Set configuration in pipeline env
* **Quick testing**: Temporary configuration without files
* **System-wide defaults**: Set in shell profile

**Priority Order** (highest to lowest):

1. Command line flags
2. **Environment variables**
3. Configuration file
4. Default values

### Gonzo-Specific Variables

#### Input Configuration

**`GONZO_FILES`**

**Type**: String (comma-separated paths)\
**Default**: `""` (uses stdin)\
**Description**: Log files to read

```bash
# Single file
export GONZO_FILES="/var/log/app.log"

# Multiple files
export GONZO_FILES="/var/log/app.log,/var/log/error.log"

# Glob pattern (quote to prevent shell expansion)
export GONZO_FILES="/var/log/*.log"
```

**Example**:

```bash
export GONZO_SKIN="dracula"
```

**Built-in skins**:

* Dark: `default`, `controltheory-dark`, `dracula`, `gruvbox`, `monokai`, `nord`, `solarized-dark`
* Light: `controltheory-light`, `github-light`, `solarized-light`, `vs-code-light`, `spring`

#### Advanced Settings

**`GONZO_TEST_MODE`**

**Type**: Boolean (`true` or `false`)\
**Default**: `false`\
**Description**: Run without TTY (for testing)

```bash
export GONZO_TEST_MODE="true"
```

**Note**: For automated testing only, not for normal use.

### AI Provider Variables

These configure AI provider connections:

#### OpenAI API

**`OPENAI_API_KEY`**

**Type**: String (API key)\
**Required for**: OpenAI API access\
**Description**: Your OpenAI API key

```bash
export OPENAI_API_KEY="sk-your-actual-api-key-here"
```

**Get your key**: <https://platform.openai.com/api-keys>

**`OPENAI_API_BASE`**

**Type**: String (URL)\
**Default**: `https://api.openai.com/v1`\
**Description**: API endpoint (for custom providers)

```bash
# For OpenAI (default, can omit)
export OPENAI_API_BASE="https://api.openai.com/v1"

# For LM Studio (MUST include /v1)
export OPENAI_API_BASE="http://localhost:1234/v1"

# For Ollama (NO /v1 suffix)
export OPENAI_API_BASE="http://localhost:11434"

# For custom OpenAI-compatible API
export OPENAI_API_BASE="https://your-api.com/v1"
```

**Important Notes**:

* LM Studio: **MUST** include `/v1` suffix
* Ollama: **MUST NOT** include `/v1` suffix
* Most others: Include `/v1` suffix

#### OpenAI Configuration

**`OPENAI_ORGANIZATION`**

**Type**: String (organization ID)\
**Optional**: For multi-org accounts\
**Description**: OpenAI organization ID

```bash
export OPENAI_ORGANIZATION="org-your-org-id"
```

### System Variables

These system-wide variables affect Gonzo:

#### Terminal Configuration

**`TERM`**

**Type**: String\
**Default**: Set by terminal\
**Description**: Terminal type

```bash
export TERM="xterm-256color"
```

**Recommended values**:

* `xterm-256color` - 256 color support
* `screen-256color` - For tmux/screen
* `alacritty` - For Alacritty terminal

**`LANG` / `LC_ALL`**

**Type**: String (locale)\
**Default**: System locale\
**Description**: Character encoding

```bash
export LANG="en_US.UTF-8"
export LC_ALL="en_US.UTF-8"
```

**Note**: UTF-8 recommended for proper display.

#### Display Control

**`NO_COLOR`**

**Type**: Boolean (any value)\
**Default**: Not set\
**Description**: Disable color output

```bash
# Disable colors
export NO_COLOR=1

# Re-enable colors
unset NO_COLOR
```

**Note**: Setting to any value disables colors.

### Complete Configuration Examples

#### Basic Development Setup

```bash
# ~/.bashrc or ~/.zshrc
export GONZO_FILES="/var/log/app.log"
export GONZO_FOLLOW="true"
export GONZO_SKIN="dracula"
export OPENAI_API_KEY="sk-your-key-here"
```

#### Production Monitoring

```bash
# Production server configuration
export GONZO_FILES="/var/log/production/*.log"
export GONZO_FOLLOW="true"
export GONZO_UPDATE_INTERVAL="2s"
export GONZO_LOG_BUFFER="5000"
export GONZO_MEMORY_SIZE="20000"
export GONZO_SKIN="default"
export OPENAI_API_KEY="sk-prod-key"
```

#### OTLP Receiver

```bash
# OTLP log receiver setup
export GONZO_OTLP_ENABLED="true"
export GONZO_OTLP_GRPC_PORT="4317"
export GONZO_OTLP_HTTP_PORT="4318"
export GONZO_UPDATE_INTERVAL="1s"
export GONZO_LOG_BUFFER="2000"
```

#### Local AI with Ollama

```bash
# Using Ollama for AI features
export OPENAI_API_KEY="ollama"
export OPENAI_API_BASE="http://localhost:11434"
export GONZO_AI_MODEL="llama3"
export GONZO_FILES="/var/log/app.log"
export GONZO_FOLLOW="true"
```

#### Local AI with LM Studio

```bash
# Using LM Studio for AI features
export OPENAI_API_KEY="local-key"
export OPENAI_API_BASE="http://localhost:1234/v1"  # Note: /v1 required
export GONZO_AI_MODEL=""  # Auto-select
export GONZO_FILES="/var/log/app.log"
```

### Docker/Container Usage

#### Docker Compose

```yaml
# docker-compose.yml
services:
  gonzo:
    image: gonzo:latest
    environment:
      - GONZO_OTLP_ENABLED=true
      - GONZO_OTLP_GRPC_PORT=4317
      - GONZO_OTLP_HTTP_PORT=4318
      - GONZO_LOG_BUFFER=2000
      - GONZO_UPDATE_INTERVAL=2s
      - OPENAI_API_KEY=${OPENAI_API_KEY}
    ports:
      - "4317:4317"
      - "4318:4318"
```

#### Docker Run

```bash
docker run -e GONZO_OTLP_ENABLED=true \
           -e GONZO_OTLP_GRPC_PORT=4317 \
           -e GONZO_OTLP_HTTP_PORT=4318 \
           -e OPENAI_API_KEY="${OPENAI_API_KEY}" \
           -p 4317:4317 \
           -p 4318:4318 \
           gonzo:latest
```

#### Kubernetes

```yaml
# kubernetes-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: gonzo
spec:
  template:
    spec:
      containers:
      - name: gonzo
        image: gonzo:latest
        env:
        - name: GONZO_OTLP_ENABLED
          value: "true"
        - name: GONZO_OTLP_GRPC_PORT
          value: "4317"
        - name: GONZO_OTLP_HTTP_PORT
          value: "4318"
        - name: GONZO_LOG_BUFFER
          value: "2000"
        - name: OPENAI_API_KEY
          valueFrom:
            secretKeyRef:
              name: gonzo-secrets
              key: openai-api-key
        ports:
        - containerPort: 4317
        - containerPort: 4318
```

### Shell Profile Setup

#### Bash (\~/.bashrc)

```bash
# Gonzo Configuration
export GONZO_FILES="/var/log/app.log"
export GONZO_FOLLOW="true"
export GONZO_SKIN="dracula"
export GONZO_UPDATE_INTERVAL="2s"

# OpenAI Configuration
export OPENAI_API_KEY="sk-your-key-here"

# Optional: Add completion
if [ -f ~/.gonzo-completion.bash ]; then
  source ~/.gonzo-completion.bash
fi
```

#### Zsh (\~/.zshrc)

```zsh
# Gonzo Configuration
export GONZO_FILES="/var/log/app.log"
export GONZO_FOLLOW="true"
export GONZO_SKIN="nord"
export GONZO_UPDATE_INTERVAL="2s"

# OpenAI Configuration
export OPENAI_API_KEY="sk-your-key-here"

# Optional: Add completion
if [ -f ~/.gonzo-completion.zsh ]; then
  source ~/.gonzo-completion.zsh
fi
```

#### Fish (\~/.config/fish/config.fish)

```fish
# Gonzo Configuration
set -x GONZO_FILES "/var/log/app.log"
set -x GONZO_FOLLOW "true"
set -x GONZO_SKIN "monokai"
set -x GONZO_UPDATE_INTERVAL "2s"

# OpenAI Configuration
set -x OPENAI_API_KEY "sk-your-key-here"
```

### Debugging Environment Variables

#### View All Gonzo Variables

```bash
# Show all GONZO_* variables
env | grep GONZO

# Show all OpenAI variables
env | grep OPENAI

# Show all relevant variables
env | grep -E '(GONZO|OPENAI|TERM|LANG)'
```

#### Test Configuration

```bash
# Print configuration without starting Gonzo
gonzo --help

# Or check specific values
echo "Files: $GONZO_FILES"
echo "Follow: $GONZO_FOLLOW"
echo "Interval: $GONZO_UPDATE_INTERVAL"
echo "API Key: ${OPENAI_API_KEY:0:10}..."  # Show only first 10 chars
```

#### Clear All Settings

```bash
# Unset all Gonzo variables
unset GONZO_FILES
unset GONZO_FOLLOW
unset GONZO_UPDATE_INTERVAL
unset GONZO_LOG_BUFFER
unset GONZO_MEMORY_SIZE
unset GONZO_AI_MODEL
unset GONZO_OTLP_ENABLED
unset GONZO_OTLP_GRPC_PORT
unset GONZO_OTLP_HTTP_PORT
unset GONZO_SKIN

# Unset OpenAI variables
unset OPENAI_API_KEY
unset OPENAI_API_BASE
```

### Precedence Examples

Understanding how different configuration methods interact:

#### Example 1: Command Line Overrides Env Var

```bash
export GONZO_UPDATE_INTERVAL="5s"
gonzo --update-interval=1s  # Uses 1s, not 5s
```

#### Example 2: Env Var Overrides Config File

```yaml
# config.yml has: update-interval: 10s
```

```bash
export GONZO_UPDATE_INTERVAL="2s"
gonzo --config=config.yml  # Uses 2s, not 10s
```

#### Example 3: Full Precedence Chain

```yaml
# config.yml
update-interval: 10s
```

```bash
export GONZO_UPDATE_INTERVAL="5s"
gonzo --config=config.yml --update-interval=1s
# Result: Uses 1s (flag > env > config)
```

### Security Considerations

#### API Keys

**Never commit API keys**:

```bash
# ❌ BAD - Don't commit to version control
export OPENAI_API_KEY="sk-actual-key"

# ✅ GOOD - Use secrets management
export OPENAI_API_KEY="${OPENAI_KEY_FROM_VAULT}"

# ✅ GOOD - Read from secure file
export OPENAI_API_KEY=$(cat ~/.secrets/openai_key)
```

**Use environment-specific keys**:

```bash
# Development
export OPENAI_API_KEY="sk-dev-key"

# Production
export OPENAI_API_KEY="sk-prod-key"
```

#### File Permissions

Protect your shell profile:

```bash
chmod 600 ~/.bashrc
chmod 600 ~/.zshrc
```

#### Kubernetes Secrets

Store sensitive values in secrets:

```yaml
apiVersion: v1
kind: Secret
metadata:
  name: gonzo-secrets
type: Opaque
stringData:
  openai-api-key: "sk-your-key-here"
```

### Troubleshooting

#### Variable Not Applied

**Check if set**:

```bash
echo $GONZO_FILES
# If empty, not set
```

**Check for typos**:

```bash
# Wrong
export GONZO_FILE="/var/log/app.log"  # Missing 'S'

# Correct
export GONZO_FILES="/var/log/app.log"
```

**Check for overrides**:

```bash
# Command line flag overrides env var
gonzo -f other.log  # Ignores GONZO_FILES
```

#### AI Not Working

**Check API key**:

```bash
echo $OPENAI_API_KEY
# Should show your key (sk-...)
```

**Check API base**:

```bash
echo $OPENAI_API_BASE
# Should be correct for your provider
```

**Test connectivity**:

```bash
# For OpenAI
curl https://api.openai.com/v1/models \
  -H "Authorization: Bearer $OPENAI_API_KEY"

# For LM Studio
curl http://localhost:1234/v1/models

# For Ollama
curl http://localhost:11434/api/tags
```

#### OTLP Receiver Not Starting

**Check if enabled**:

```bash
echo $GONZO_OTLP_ENABLED
# Should be "true"
```

**Check port conflicts**:

```bash
# Check if ports are free
lsof -i :4317
lsof -i :4318
```

### Best Practices

1. **Use shell profiles**: Set persistent defaults in `~/.bashrc` or `~/.zshrc`
2. **Separate environments**: Use different values for dev/prod
3. **Secure API keys**: Never commit keys to version control
4. **Document setup**: Comment your environment configuration
5. **Test changes**: Verify variables are applied correctly
6. **Use defaults**: Only override what you need to change

### Related Documentation

* **Configuration Schema** - Configuration file reference
* **CLI Reference** - Command line options
* **AI Integration** - AI provider setup

{% hint style="info" %}
**Tip**: Use `env | grep GONZO` to quickly see all your current Gonzo environment settings.
{% endhint %}

{% hint style="warning" %}
**Security**: Never expose API keys in logs, screenshots, or public repositories. Use environment variables or secrets management.
{% endhint %}

\_FILES="/var/log/nginx/access.log,/var/log/nginx/error.log" gonzo \`\`\`

**`GONZO_FOLLOW`**

**Type**: Boolean (`true` or `false`)\
**Default**: `false`\
**Description**: Follow log files in real-time

```bash
export GONZO_FOLLOW="true"
```

**Example**:

```bash
export GONZO_FOLLOW="true"
export GONZO_FILES="/var/log/app.log"
gonzo
```

#### Performance Settings

**`GONZO_UPDATE_INTERVAL`**

**Type**: Duration string\
**Default**: `"1s"`\
**Valid values**: Go duration format (e.g., `500ms`, `2s`, `5s`)\
**Description**: Dashboard update frequency

```bash
export GONZO_UPDATE_INTERVAL="2s"
```

**Common values**:

* `"500ms"` - Very responsive
* `"1s"` - Default, good balance
* `"2s"` - Reduced CPU usage
* `"5s"` - Low resource usage

**`GONZO_LOG_BUFFER`**

**Type**: Integer\
**Default**: `1000`\
**Valid range**: `1` to `100000`\
**Description**: Maximum log entries in buffer

```bash
export GONZO_LOG_BUFFER="2000"
```

**Guidelines**:

* **Low volume** (`<100 logs/sec`): 500-1000
* **Medium volume** (`100-1000 logs/sec`): 1000-5000
* **High volume** (`>1000 logs/sec`): 5000-10000

**`GONZO_MEMORY_SIZE`**

**Type**: Integer\
**Default**: `10000`\
**Valid range**: `100` to `1000000`\
**Description**: Maximum words tracked for frequency analysis

```bash
export GONZO_MEMORY_SIZE="15000"
```

**Guidelines**:

* **Minimal**: 5000
* **Standard**: 10000 (default)
* **Extended**: 15000-20000
* **Maximum**: 50000+

#### AI Configuration

**`GONZO_AI_MODEL`**

**Type**: String\
**Default**: `""` (auto-select)\
**Description**: AI model for log analysis

```bash
# Auto-select best available (recommended)
export GONZO_AI_MODEL=""

# OpenAI models
export GONZO_AI_MODEL="gpt-4"
export GONZO_AI_MODEL="gpt-3.5-turbo"

# Ollama models
export GONZO_AI_MODEL="llama3"
export GONZO_AI_MODEL="mistral"

# LM Studio models
export GONZO_AI_MODEL="openai/gpt-oss-120b"
```

#### OTLP Receiver

**`GONZO_OTLP_ENABLED`**

**Type**: Boolean (`true` or `false`)\
**Default**: `false`\
**Description**: Enable OTLP log receiver

```bash
export GONZO_OTLP_ENABLED="true"
```

**`GONZO_OTLP_GRPC_PORT`**

**Type**: Integer\
**Default**: `4317`\
**Valid range**: `1024` to `65535`\
**Description**: gRPC receiver port

```bash
export GONZO_OTLP_GRPC_PORT="4317"
```

**`GONZO_OTLP_HTTP_PORT`**

**Type**: Integer\
**Default**: `4318`\
**Valid range**: `1024` to `65535`\
**Description**: HTTP receiver port

```bash
export GONZO_OTLP_HTTP_PORT="4318"
```

#### Display Settings

**`GONZO_SKIN`**

**Type**: String\
**Default**: `"default"`\
**Valid values**: Any installed skin name\
**Description**: Color scheme/theme

```bash
export GONZO
```


# Dstl8 Docs

Distill your logs into insights!

Learn more about [Dstl8 ](https://www.controltheory.com/product/dstl8/)on the ControlTheory website.

<table data-view="cards"><thead><tr><th></th><th data-hidden data-card-cover data-type="image">Cover image</th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td>Quickstart</td><td><a href="https://images.unsplash.com/photo-1635144432103-47f3a18bae38?crop=entropy&#x26;cs=srgb&#x26;fm=jpg&#x26;ixid=M3wxOTcwMjR8MHwxfHNlYXJjaHwxfHxxdWlja3N0YXJ0fGVufDB8fHx8MTc3Njc5MjEzMXww&#x26;ixlib=rb-4.1.0&#x26;q=85">https://images.unsplash.com/photo-1635144432103-47f3a18bae38?crop=entropy&#x26;cs=srgb&#x26;fm=jpg&#x26;ixid=M3wxOTcwMjR8MHwxfHNlYXJjaHwxfHxxdWlja3N0YXJ0fGVufDB8fHx8MTc3Njc5MjEzMXww&#x26;ixlib=rb-4.1.0&#x26;q=85</a></td><td><a href="/pages/wUGkQTqtWUE95gK6NX4V">/pages/wUGkQTqtWUE95gK6NX4V</a></td></tr><tr><td>Sources</td><td><a href="https://images.unsplash.com/photo-1556010334-298f19160723?crop=entropy&#x26;cs=srgb&#x26;fm=jpg&#x26;ixid=M3wxOTcwMjR8MHwxfHNlYXJjaHw4fHxmYXVjZXR8ZW58MHx8fHwxNzc2NzkyMTg0fDA&#x26;ixlib=rb-4.1.0&#x26;q=85">https://images.unsplash.com/photo-1556010334-298f19160723?crop=entropy&#x26;cs=srgb&#x26;fm=jpg&#x26;ixid=M3wxOTcwMjR8MHwxfHNlYXJjaHw4fHxmYXVjZXR8ZW58MHx8fHwxNzc2NzkyMTg0fDA&#x26;ixlib=rb-4.1.0&#x26;q=85</a></td><td><a href="/pages/vlhX10qVqR77WJpGSbcP">/pages/vlhX10qVqR77WJpGSbcP</a></td></tr><tr><td>MCP</td><td><a href="https://images.unsplash.com/photo-1626285094816-39f688104ce0?crop=entropy&#x26;cs=srgb&#x26;fm=jpg&#x26;ixid=M3wxOTcwMjR8MHwxfHNlYXJjaHwxMHx8QVBJfGVufDB8fHx8MTc3Njc5MjIyMXww&#x26;ixlib=rb-4.1.0&#x26;q=85">https://images.unsplash.com/photo-1626285094816-39f688104ce0?crop=entropy&#x26;cs=srgb&#x26;fm=jpg&#x26;ixid=M3wxOTcwMjR8MHwxfHNlYXJjaHwxMHx8QVBJfGVufDB8fHx8MTc3Njc5MjIyMXww&#x26;ixlib=rb-4.1.0&#x26;q=85</a></td><td><a href="/pages/5ulQFp7a1FCavifah8Zp">/pages/5ulQFp7a1FCavifah8Zp</a></td></tr></tbody></table>


# Quickstart

Fastpath >>>>>

{% hint style="info" %}
**Just want to look around first?** Choose **Explore Sample Data** on first launch to see a preloaded demo workspace with live anomalies and a sample incident. No setup required. When you're ready for real value, follow the steps below to integrate your own project.
{% endhint %}

The shortest path to querying your logs with an AI assistant: create a source, assign its streams to a workspace, and connect your assistant via MCP. Use the [Dstl8 CLI](/controltheory-documentation/dstl8-docs/dstl8-cli) to on-board at warp speed — `dstl8 setup` runs the whole flow below as one guided command.

### Terminology

* **Source** — A connection to a platform you want to pull logs from (e.g. an AWS account's CloudWatch, a Kubernetes cluster). You can add multiple sources of the same type with different credentials.
* **Stream Type** — A kind of log stream produced by a source, e.g. a CloudWatch Lambda log group, or a Kubernetes Deployment or DaemonSet.
* **Stream** — A specific instance of a stream type, e.g. one Lambda function or one pod.
* **Workspace** — A boundary that controls user and data access. Streams are assigned to workspaces to make them queryable. Every organization starts with a **Default** workspace.

#### Explore with sample data

If you picked **Explore Sample Data** on first launch, you'll notice Dstl8 creates a second workspace tagged **Sample** alongside your **Default** workspace. It comes preloaded so you can see the product working before connecting anything:

* An OTLP source named **Sample Data** feeding a set of live streams.
* Anomalies and at least one active incident generated from the sample traffic.
* A completed **Möbius Analysis** summarizing the incident, plus the **Sentiment Heatmap** and **Möbius Chat**.

Sample incidents behave like real ones, which means the org admin receives email notifications for them. This is expected. It also previews how alerting works once you connect a real source.

Use the sample workspace to get familiar with the dashboard, incidents, and Möbius. You can delete it anytime from the workspace settings (gear icon) once you have real data flowing.

### 1. Create a source and validate streams

Pick a platform and add it as a source:

* [**AWS CloudWatch**](/controltheory-documentation/dstl8-docs/sources/aws-cloudwatch) — if your logs live in CloudWatch Log Groups.
* [**Kubernetes**](/controltheory-documentation/dstl8-docs/sources/kubernetes) — install the in-cluster agent to collect container logs and cluster events.
* Other sources (Vercel, Supabase, OTLP, GitHub) — see [Sources](/controltheory-documentation/dstl8-docs/sources).

New sources start as **Pending**. Within a couple of minutes the source should transition to **Healthy** and streams will appear with their inferred stream types.

**Validate:** expand the source card on the **Sources** page — you should see streams listed under **STREAMS**. If nothing appears after a few minutes, re-run **Test Connection** from the source's actions menu (gear icon).

### 2. Assign streams to a workspace

Streams must be assigned to a workspace before they're queryable. Every organization starts with a **Default** workspace — the fastest path is to assign everything to it.

1. On the source card, open the actions menu (gear icon) and select **Assign Streams**.
2. Check the **Default** workspace to assign all streams from this source, or drill in to select specific **Stream Types** or individual streams.
3. Click **Save**.

The source card now shows `1 workspace` receiving streams.

For splitting streams across multiple workspaces (e.g. prod vs staging), see [Assigning streams to workspaces](/controltheory-documentation/dstl8-docs/sources#assigning-streams-to-workspaces).

### 3. Connect your AI assistant via MCP

Dstl8 exposes an MCP endpoint per organization that lets Claude (or any MCP-compatible assistant) query your logs, incidents, and anomaly tools directly.

1. In **Org Settings → Organizational Info**, copy your MCP endpoint — it looks like `https://<org_id>.app.dstl8.ai/mcp`.
2. In **Org Settings → API Tokens**, create an API token and copy it (it's only shown once).
3. Configure your client. Per-client setup guides:
   * [Claude Code](https://docs.controltheory.com/controltheory-documentation/dstl8-docs/mcp-integration/claude-code)
   * [Claude Desktop](https://docs.controltheory.com/controltheory-documentation/dstl8-docs/mcp-integration/claude-desktop)
   * [Cursor](https://docs.controltheory.com/controltheory-documentation/dstl8-docs/mcp-integration/cursor)
   * [Codex](https://docs.controltheory.com/controltheory-documentation/dstl8-docs/mcp-integration/codex)
   * [ChatGPT](https://docs.controltheory.com/controltheory-documentation/dstl8-docs/mcp-integration/chatgpt)

Full reference: [MCP Integration](https://docs.controltheory.com/controltheory-documentation/dstl8-docs/mcp-integration).

### 4. Ask a question

From your configured assistant, try:

* *"What's going on in production?"*
* *"Any anomalies in the last hour?"*
* *"Summarize recent errors across my streams."*

If you get a grounded answer referencing your actual services and log patterns, you're set.


# Dstl8 CLI

Your fast on-ramp and TUI

The `dstl8` CLI is the on-ramp to Dstl8. The flow is: **authenticate → add sources → install MCP**. After that, your AI agent can investigate incidents, query logs, and analyze patterns through Dstl8's MCP tools.

The CLI also ships an interactive TUI for browsing workspaces, sources, incidents, heatmaps, and logs from a terminal.

#### Setup

**Install the CLI**

Pick the option that matches your environment. Each installs the same `dstl8` binary.

| Method                   | Command                                                                           |
| ------------------------ | --------------------------------------------------------------------------------- |
| Homebrew (macOS / Linux) | `brew install control-theory/dstl8/dstl8`                                         |
| Shell installer          | `curl -fsSL https://install.dstl8.ai/script/dstl8-cli \| sh`                      |
| npm                      | `npm install -g dstl8` (or `npx dstl8`)                                           |
| Nix                      | `nix profile install github:control-theory/dstl8`                                 |
| Manual                   | Download from [GitHub Releases](https://github.com/control-theory/dstl8/releases) |

Verify with `dstl8 version`.

**Fast track: `dstl8 setup`**

One command to get fully onboarded:

```bash
dstl8 setup
```

This walks through four steps — each optional, skip any with `:skip` and re-run `dstl8 setup` anytime to finish later:

1. **Account** — Creates your account via GitHub or browser signup (skipped if you're already logged in)
2. **AI agent integration** — Installs the Dstl8 MCP server into detected AI coding agents (Claude Code, Codex, Cursor, and others)
3. **Data sources** — Auto-detects sources on your machine (Kubernetes contexts, AWS credentials, Vercel/Supabase/GitHub configs) and sets them up
4. **Explore** — Opens the interactive dashboard or web dashboard

That's the entire authenticate → add sources → install MCP flow in one guided pass. Prefer to run each piece yourself, or need to script it? The three steps below are the same flow, done manually.

**1. Authenticate**

Pick the option that matches your situation — you only need one.

**If you don't have a Dstl8 account yet:**

```bash
dstl8 signup
```

Opens your browser to create a Dstl8 account and organization. Once you're done, the CLI saves a long-lived API token locally, and a `Default` workspace is created for you to start with.

**If you already have an account** — for example, you were invited to an existing org, or you're setting up a new device:

```bash
dstl8 login
```

Opens your browser to authenticate. If you were invited to an org, accept the invite in the browser first, then run `dstl8 login` to attach the CLI.

Either way, confirm with `dstl8 profiles` — the active profile is marked `►`.

**2. Add sources**

Adding a source is what gets logs flowing into Dstl8. `dstl8 sources add` is an interactive wizard for every source type. It auto-detects local config (`~/.aws/credentials`, `~/.kube/config`, `vercel.json`, `supabase/config.toml`, `.git/config`) and pre-fills sensible defaults.

```bash
dstl8 sources add kubernetes
dstl8 sources add cloudwatch
dstl8 sources add vercel
dstl8 sources add supabase
dstl8 sources add otlp
dstl8 sources add cloudflare
```

For pull-based sources (`kubernetes`, `cloudwatch`), the CLI verifies the connection before exiting. For webhook-based sources (`vercel`, `supabase`, `otlp`, `github`), the wizard prints a webhook URL and any auto-generated tokens — paste those into the upstream provider to complete the setup.

For scripted setups, pass `--yes` with the relevant flags to skip prompts:

```bash
dstl8 sources add cloudwatch --yes \
  --name prod-cw \
  --aws-region us-east-1
```

**Confirm logs are flowing.** Pull-based sources should ingest immediately. Webhook sources only start flowing after you paste the webhook URL into the upstream provider, so do that first.

```bash
dstl8 sources                      # source listed and ingesting
dstl8 logs fetch -n 5              # recent logs
```

**3. Install MCP**

This is the step that connects Dstl8 to your AI agent. `dstl8 install` auto-detects MCP-compatible clients on your machine and configures them:

```bash
dstl8 install                      # interactive picker
dstl8 install --all                # install to every detected client
dstl8 install claude-code          # install to a specific client
dstl8 install status               # see what's installed where
```

Supported clients:

| Client         | Install command                                                                                                                                              |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Claude Code    | `dstl8 install claude-code`                                                                                                                                  |
| Claude Desktop | `dstl8 install claude-desktop`, or download `dstl8.mcpb` from the [latest release](https://github.com/control-theory/dstl8/releases/latest) and double-click |
| Codex          | `dstl8 install codex`                                                                                                                                        |
| LM Studio      | `dstl8 install lm-studio`                                                                                                                                    |
| Cursor         | `dstl8 install --include-experimental cursor`                                                                                                                |
| Windsurf       | `dstl8 install --include-experimental windsurf`                                                                                                              |

Restart your AI client after installing so it picks up the new MCP server. Your AI agent can now query Dstl8.

#### The TUI

`dstl8 tui` opens an interactive terminal UI for browsing your data without leaving the shell. Most investigation work runs through your AI client once MCP is set up, but the TUI is useful for quick visual checks and one-off navigation.

The TUI splits into org-level views (Overview, Workspaces, Incidents, Events, Sources) and workspace views (Dashboard, Incidents, Heatmap, Log Viewer, Events, and — for workspaces with a Kubernetes source — Topology). Use `←` `→` to switch tabs, `↑` `↓` or `j` `k` to navigate, `Enter` to drill in, and `Esc` to go back. `Ctrl+C` quits.

**Sources**

The org-level Sources tab lists every source connected to your organization. Press `Enter` to drill into streams, then `Enter` again on a stream to see its logs. Press `a` on any source or stream to assign it to a workspace.

<figure><img src="/files/SfJNKI0Es7toYm7XNzVO" alt=""><figcaption></figcaption></figure>

**Workspace dashboard**

Each workspace has a Dashboard with a Möbius AI summary at the top, a list of active incidents, and the sources feeding the workspace. Press `Enter` on the Möbius summary for a full analysis.

<figure><img src="/files/qLZRp5ewBBdXVwbhEcWC" alt=""><figcaption></figcaption></figure>

**Incidents**

The Incidents tab gives you a sortable, filterable table — Open, Resolved, Closed, or All. Press `s` to change the sort, `f` to cycle filters, and `Enter` on a row to open the incident detail view.

<figure><img src="/files/kz8yXoDSOhwNbh3AqBok" alt=""><figcaption></figcaption></figure>

The detail view renders Möbius's full analysis: summary, description, evidence, recommended actions, alongside the impacted resources and event timeline.

<figure><img src="/files/TeSGb2mmzEKINm66rshd" alt=""><figcaption></figcaption></figure>

**Heatmap**

The Heatmap plots sentiment over time by stream, namespace, or service. Anomalies surface as red dots on the affected row. Press `w` to change the time window, `g` to change the grouping, and `Enter` on a row to view the filtered logs for that group.

<figure><img src="/files/9TP8m34POHjfE8XJg70K" alt=""><figcaption></figcaption></figure>

**Log Viewer**

The Log Viewer combines a stacked severity bar chart (1-minute buckets) with a scrollable log table. Press `Enter` on a log line to open a detail modal with full metadata. `c` copies the body to your clipboard.

<figure><img src="/files/YMd5OHVn3g2ret919LyL" alt=""><figcaption></figcaption></figure>

For the complete list of keybindings across every view, see the [README](https://github.com/control-theory/dstl8-cli#navigation).

#### Other CLI commands

A handful of commands are useful outside the TUI, especially in scripts and CI.

**Piping logs in with tap**

`dstl8 tap` pipes *any* logs into Dstl8 without setting up a dedicated source — it auto-detects the format, converts to OTLP, and streams to your org:

```bash
kubectl logs -f deploy/api | dstl8 tap
heroku logs --tail         | dstl8 tap
cat app.log                | dstl8 tap
dstl8 tap --listen                       # local OTLP endpoint for SDKs/collectors
```

See the full [Tap guide](/controltheory-documentation/dstl8-docs/dstl8-cli/tap) for supported formats, the `--listen` OTLP server mode, and per-vendor examples.

**Sending and querying events**

`dstl8 events` sends and queries platform events — deploy markers, config changes, CI results, and notes on the timeline:

```bash
dstl8 events send --type deploy --title "Deployed checkout v1.42" --env prod
dstl8 events list --start -7d --type deploy,ci
dstl8 events search "rollback"
```

See the [Events guide](/controltheory-documentation/dstl8-docs/events) for the full flag reference and CI/CD integration.

**Exploring cluster topology**

`dstl8 topology` (alias: `topo`) explores the Kubernetes topology captured by cluster agents — the resource tree and blast-radius impact for any component:

```bash
dstl8 topology clusters                                 # clusters with topology data
dstl8 topology view --kinds deployment,service          # the cluster resource tree
dstl8 topology impact deployment/checkout/payment-api   # what depends on it, what it depends on
```

See the [Topology guide](/controltheory-documentation/dstl8-docs/topology) for the web UI and TUI views and the full flag reference.

**Tailing and fetching logs**

`dstl8 logs tail` streams logs to stdout in real time:

```bash
dstl8 logs tail                                    # all logs
dstl8 logs tail --source Prod -s error             # one source, errors only
dstl8 logs tail --stream-name api --search "timeout"
```

`dstl8 logs fetch` pulls a time range and exits — useful for scripts and verifying ingestion:

```bash
dstl8 logs fetch --start 24h -n 500 --json
dstl8 logs fetch --start 7d --end 24h --source Prod -s error
```

Time arguments accept relative (`30m`, `1h`, `24h`, `7d`) or absolute (`2024-01-15`, `2024-01-15T09:30:00`) values. `--json` produces NDJSON for piping.

**Profiles and workspaces**

```bash
dstl8 profiles                     # list configured profiles
dstl8 switch <profile>             # change the active profile
dstl8 workspaces                   # list workspaces
dstl8 workspaces create <name> --description "Production monitoring"
dstl8 sources assign <source> <workspace>
```

Configuration lives in `~/.config/dstl8/`. Use `--profile <name>` on any command to run it against a specific profile without switching.

#### More

The full command reference, every flag, and release notes live in the [dstl8-cli README](https://github.com/control-theory/dstl8-cli) and on the [releases page](https://github.com/control-theory/dstl8/releases).


# Tap: Pipe In Any Logs

Pipe logs from anywhere into Dstl8 — format auto-detected, sent as OTLP

`dstl8 tap` pipes *any* logs into Dstl8 without setting up a dedicated source. It reads log lines from stdin (or runs a local OTLP endpoint with `--listen`), auto-detects the format and vendor, converts each record to OTLP with proper resource attributes, and streams it to your organization's OTLP source — so it renders and groups in the platform exactly like Kubernetes, Docker, and other native sources.

```bash
kubectl logs -f deploy/api | dstl8 tap          # tail a deployment straight into Dstl8
flyctl logs -j             | dstl8 tap          # fly.io JSON logs
heroku logs --tail         | dstl8 tap          # heroku logplex
docker compose logs -f     | dstl8 tap          # per-service compose logs
cat app.log                | dstl8 tap          # a plain log file
dstl8 tap --listen                              # receive OTLP locally (SDKs/collectors)
```

{% hint style="info" %}
**No OTLP source in your org yet?** Tap auto-creates one named `tap` on first use (the token is generated server-side), waits for it to come online, then starts streaming. Nothing to configure.
{% endhint %}

A running tap looks like this:

```
Tapping logs → otlp source "tap" (https://acme.dstl8.ai/src-a1b2c3)
  Detected format: vercel (100)   service.name=my-app   service.instance.id=my-app.vercel.app
  tap: 1204 read · 1204 sent · 0 failed · 0 dropped · 512.0 KiB
```

Diagnostics (the banner, detection line, and periodic stats) print to **stderr**; **stdout** is reserved for `--dry-run` OTLP JSON and `--echo` records, so both pipe cleanly into other tools.

### How detection works

Tap samples the first several lines of the stream, locks onto the best-matching format, and — for transport wrappers like `kubectl`, `docker`, and `heroku` — strips the wrapper prefix and re-detects the inner payload. A per-line fallback handles mixed streams (for example, a JSON stream with an occasional plain-text panic). Multi-line stack traces (Java, Python tracebacks, Go panics) are joined into a single record, and vendor double-encoding (Vercel's `[fn] {json}`, Fly's inner JSON) is unwrapped automatically.

Force a format with `--format <name>` to skip detection entirely.

**Supported formats:**

| Category | Formats                                                                                                                                                                                                                                                             |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Vendors  | `vercel`, `supabase`, `cloudflare` (Logpush), `wrangler` (Workers), `flyio`, `victorialogs`, `heroku`, `docker`, `kubectl`, `cloudwatch` (`aws logs tail`), `gcp` (Cloud Logging)                                                                                   |
| Generic  | `otlp` (OTLP-JSON passthrough), `json` (zap/logrus/pino/bunyan dialects), `logfmt`, `syslog` (RFC 5424 + 3164), `journald`, `klog`/`glog`, `java` (log4j/logback), `python`, `rails`, `access` (nginx/Apache combined), `nginx-error`, `text` (plain-text fallback) |

### Streams and resource attributes

Every record's `service.name` becomes the platform **stream type** and `service.instance.id` becomes the **stream name**. Tap fills these from per-vendor extraction (the Vercel project, Kubernetes pod/container, Fly app, and so on), falling back to the format name and hostname.

* Override them with `--service` (stream type) and `--instance` (stream name).
* Add arbitrary resource attributes with `--attr key=value` (repeatable).

### Flags

| Flag                     | Description                                                                                  |
| ------------------------ | -------------------------------------------------------------------------------------------- |
| `--source <name-or-id>`  | OTLP source to send to (default: the org's only `otlp` source; auto-created if none)         |
| `--format <name>`        | Force an input format, skipping auto-detection                                               |
| `--service <name>`       | Override `service.name` (the platform stream type)                                           |
| `--instance <name>`      | Override `service.instance.id` (the platform stream name)                                    |
| `--attr key=value`       | Add an extra resource attribute (repeatable)                                                 |
| `--listen`               | Receive OTLP on local ports instead of reading stdin                                         |
| `--listen-port <n>`      | Local OTLP HTTP port for `--listen` (default 4318)                                           |
| `--listen-grpc-port <n>` | Local OTLP gRPC port for `--listen` (default 4317)                                           |
| `--dry-run`              | Print the OTLP JSON to stdout instead of sending (works offline — no source or login needed) |
| `--echo`                 | Print each parsed record as it's sent                                                        |
| `--quiet`                | Suppress the banner and periodic stats                                                       |

## Examples

### Kubernetes (kubectl)

```bash
kubectl logs -f deploy/api | dstl8 tap
kubectl logs -f deploy/api --timestamps --prefix | dstl8 tap    # keep pod/container identity
kubectl logs -f -l app=checkout --prefix | dstl8 tap            # by label selector
stern <selector> | dstl8 tap --format stern                     # multi-pod tailing with stern
```

* `--prefix` adds `[pod/<name>/<container>]` to each line so tap can set `k8s.*` attributes and derive the service name from the container.
* `stern`'s plain output is too ambiguous to auto-detect — pass `--format stern` (strip color with `stern --color never` if needed).

{% hint style="info" %}
Tapping `kubectl` is great for ad-hoc debugging. For continuous, cluster-wide collection, install the [Kubernetes source](/controltheory-documentation/dstl8-docs/sources/kubernetes) instead.
{% endhint %}

### Docker

```bash
docker compose logs -f | dstl8 tap
docker logs -f -t <container> | dstl8 tap
```

Compose's `service-1 |` prefix sets the service and container name automatically. `-t` adds timestamps.

### AWS CloudWatch

```bash
aws logs tail <log-group> --follow | dstl8 tap --service eks-prod
aws logs tail <log-group> --follow --since 1h | dstl8 tap
```

* Keep the default `detailed` output format (it includes the stream name) — don't use `--format short`.
* Works across Lambda (`.../[$LATEST]...`), ECS, and EKS control-plane stream shapes; the inner payload (JSON, klog, logfmt) is re-detected automatically.
* The log group name isn't part of the output, so the stream type defaults to `cloudwatch` — pass `--service <name>` to label it.

### Vercel

```bash
vercel logs <deployment-url> -j -f | dstl8 tap
vercel logs <deployment-url> -j -f --scope <team> | dstl8 tap   # project owned by a team
vercel logs <deployment-url> -j -n 100 | dstl8 tap              # recent history instead of follow
```

* `-j` (JSON Lines) is **required** — the default human-readable output isn't structured enough to detect and map.
* `-f` streams only *new* logs; use `-n <count>` to pull history.
* Add `--scope <team>` if the project belongs to a team (otherwise you'll see "No projects found"), or run `vercel link` once in the project directory and drop `--scope`.

### Fly.io

```bash
flyctl logs -j | dstl8 tap
```

`-j` for JSON output. The envelope `level` is always `info`; tap unwraps the inner JSON to recover the real severity.

### Heroku

```bash
heroku logs --tail | dstl8 tap
```

The Heroku CLI has no JSON mode; tap parses the logplex text and re-detects the inner payload (router lines are logfmt, app lines vary).

### GCP Cloud Logging

```bash
gcloud logging tail 'resource.type=cloud_run_revision' --format=json | jq -c '.[]' | dstl8 tap
```

`gcloud` pretty-prints a JSON *array*, so pipe through `jq -c '.[]'` to get one object per line.

### systemd / journald

```bash
journalctl -f -o json | dstl8 tap
```

`-o json` is required for structured fields (`MESSAGE`, `PRIORITY`, `_SYSTEMD_UNIT`, …).

### Any app or file

```bash
./my-server 2>&1         | dstl8 tap    # a running process (merge stderr with 2>&1)
tail -f /var/log/app.log | dstl8 tap    # a growing file
cat app.log              | dstl8 tap    # a static file
```

### Labeling and previewing

```bash
# Force a format and label the stream:
flyctl logs -j | dstl8 tap --format fly --service my-app

# Preview detection and the OTLP mapping without sending anything:
cat app.log | dstl8 tap --dry-run --echo

# Add extra resource attributes:
kubectl logs -f deploy/api | dstl8 tap --attr env=prod --attr team=payments

# Send to a specific source:
cat app.log | dstl8 tap --source prod-otlp
```

## Local OTLP listener (`--listen`)

Instead of reading stdin, tap can run a local OTLP endpoint and forward everything it receives to Dstl8. Point any OpenTelemetry SDK, agent, or collector at it — no per-app credentials or endpoint configuration on the Dstl8 side.

```bash
dstl8 tap --listen
```

This listens on both standard OTLP ports: **gRPC on 4317** and **HTTP on 4318** (change them with `--listen-grpc-port` / `--listen-port`). Incoming resource attributes are preserved; `service.name` and `service.instance.id` are filled with fallbacks only when absent.

### Point an OTel SDK at it

```bash
# gRPC (default port 4317):
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317

# or HTTP (default port 4318):
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
```

Then run your instrumented app as usual — its logs flow through tap into Dstl8.

### Point an OTel Collector at it

Add an OTLP exporter to your collector pipeline:

```yaml
exporters:
  otlp:
    endpoint: localhost:4317
    tls:
      insecure: true

service:
  pipelines:
    logs:
      receivers: [otlp]
      exporters: [otlp]
```

### Generate test logs with telemetrygen

[`telemetrygen`](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/cmd/telemetrygen) is the OpenTelemetry Collector's load-generation tool — handy for trying tap end-to-end without any real infrastructure.

```bash
go install github.com/open-telemetry/opentelemetry-collector-contrib/cmd/telemetrygen@latest
```

In one terminal, start the listener:

```bash
dstl8 tap --listen
```

In another, generate logs:

```bash
# 5 logs/second for 30 seconds over gRPC (port 4317):
telemetrygen logs --otlp-insecure --otlp-endpoint localhost:4317 --duration 30s --rate 5

# Same over HTTP (port 4318):
telemetrygen logs --otlp-http --otlp-insecure --otlp-endpoint localhost:4318 --duration 30s --rate 5

# A fixed batch of 100 logs with a custom service name, body, and severity:
telemetrygen logs --otlp-insecure --otlp-endpoint localhost:4317 --logs 100 \
  --service checkout --body "payment authorized" --severity-text Warn --severity-number 13

# Extra resource attributes (values must be quoted):
telemetrygen logs --otlp-insecure --otlp-endpoint localhost:4317 --duration 30s --rate 5 \
  --service checkout --otlp-attributes 'env="staging"'
```

Then confirm arrival:

```bash
dstl8 logs tail --source tap
```

## Requirements and nuances

* **Input must be piped.** Running `dstl8 tap` in a bare terminal errors out — pipe logs in, or use `--listen` for the OTLP server mode.
* **Prefer a tool's JSON/structured mode** when it has one (`-j`, `--format json`, `-o json`) — you get richer fields and more reliable detection than human-formatted output.
* **Follow flags stream only new lines.** `-f` / `--follow` / `--tail` won't replay history; use the tool's count/since flags (`-n`, `--since`) for backlog.
* **Detection samples the first several lines.** A very short burst may show `Detected format: mixed` — pass `--format <name>` to force it. Real streams lock on their own.
* **Everything lands in one OTLP source** (auto-created as `tap` if you have none). Use `--service` (stream type) and `--instance` (stream name) to separate and label streams in the dashboard.
* **With more than one OTLP source**, tap won't guess — pass `--source <name-or-id>`.
* **Merge stderr** with `2>&1` when tapping an app that logs to stderr.
* **A freshly created source takes a few seconds to provision.** Tap waits for it to come online before sending (you'll see "Waiting for the source endpoint to come online…"); no logs are lost.
* **Verify arrival** with `dstl8 logs tail --source tap` (or your `--source`).

Tap batches records and retries transient failures with backoff. On `Ctrl+C` (or stdin EOF) it flushes any buffered records and prints a summary.


# Sources

Get logs flowing!

A **Source** is a connection to an external platform that brings logs and data into your workspace.

### Terminology

* **Workspace** — A boundary that controls user and data access. Every organization starts with a **Default**workspace.
* **Source** — An instance of a source type (e.g. CloudWatch). You can add multiple sources of the same type with different credentials (e.g. one per AWS account or region).
* **Stream Type** — The kind of log stream produced by a source, e.g. a CloudWatch Lambda log group, or a Kubernetes DaemonSet or Deployment.
* **Stream** — A specific instance of a stream type, e.g. a particular container, pod, or Lambda function.

### Workspaces

A workspace is a boundary that controls who and what can access a given set of data. Common patterns:

* An **environment** — e.g. `staging`, `production`.
* An **application or service** — scoped to the team or developer(s) that own it.
* Any other grouping that fits your organization.

Each workspace has:

* **Its own users** — control exactly who can access its data.
* **Its own streams** — assigned from one or more sources (see Assigning streams to workspaces below).
* **Its own Möbius scope** — the Möbius AI agent operates only against the data in the workspace it's invoked from.

Every organization starts with a **Default** workspace.

### Supported sources

* **AWS CloudWatch** — Pull logs from CloudWatch Log Groups
* **Cloudflare** — Receive Cloudflare Logpush jobs over HTTP
* **GitHub** — Receive webhook events from GitHub
* **Google Cloud** — Pull logs from Google Cloud Logging
* **Kubernetes** — Pull pod logs and events from Kubernetes clusters
* **OTLP** — Receive logs from any OpenTelemetry exporter
* **Railway** — Pull logs from the environments of a Railway project
* **Supabase** — Receive logs from Supabase via OTLP log drain
* **Vercel** — Receive webhook events from Vercel

### Adding a source

1. Go to **Sources** in the sidebar and click **Add Source**.
2. Select a source type.
3. Configure the source (name and any source-specific settings).
4. Provide credentials if required, then click **Test Connection** to verify.
5. Click **Create**.

New sources start as **Pending**. It can take a couple of minutes for logs to begin flowing. Once streams are detected, the source transitions to **Healthy** and streams are listed with their inferred stream types.

### Assigning streams to workspaces

Creating a source ingests its data, but streams must be **assigned to a workspace** before they're accessible there. Each workspace can receive a different subset — for example, production streams to one workspace and staging to another.

1. In the **Sources** list, open the actions menu on a source (gear icon) and select **Assign Streams**.
2. For each workspace, check the streams you want it to receive. Selections are hierarchical — checking a **Stream Type** includes all of its streams, and checking a **Workspace** includes everything from that source.
3. Click **Save**.

The number of workspaces currently receiving streams from a source is shown on the source card.

### Source actions

From the actions menu (gear icon) on a source:

* **Edit** — update name and configuration.
* **Assign Streams** — manage which workspaces receive which streams (above).
* **Test Connection** — re-verify credentials.
* **Disable** — pause ingestion without deleting the source.
* **Delete** — remove the source permanently.


# AWS CloudWatch

Pull logs from AWS CloudWatch Log Groups into Dstl8.

### Add a CloudWatch source

#### 1. Open the Add Source dialog

From **Sources**, click **Add Source** and select **AWS CloudWatch**.

#### 2. Configure the source

Give the source a unique name.

By default, CloudWatch log groups are **auto-discovered** from the account. To customize, expand **Advanced config**:

* **Auto Discover** *(default)* — log groups are found automatically.
* **Log Groups** — manually specify log groups, one per line (e.g. `/aws/lambda/my-function`). Use this when you want to limit ingestion to a known set.

#### **3. Enter credentials**

| Field                              | Notes                                                 |
| ---------------------------------- | ----------------------------------------------------- |
| **AWS Access Key ID**              | From an IAM user or role with CloudWatch read access. |
| **AWS Secret Access Key**          | Paired with the access key ID.                        |
| **AWS Region**                     | Region where your log groups live, e.g. `us-east-1`.  |
| **AWS Session Token** *(optional)* | Required only when using temporary STS credentials.   |

Need credentials? Create a dedicated IAM user with read-only Logs access and mint an access key. Attach the AWS-managed [`CloudWatchLogsReadOnlyAccess`](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/CloudWatchLogsReadOnlyAccess.html) policy (ARN `arn:aws:iam::aws:policy/CloudWatchLogsReadOnlyAccess`), which grants the `logs:Describe*`, `logs:Get*`, `logs:List*`, and `logs:FilterLogEvents` read actions with no write access.

```bash
# 1) create the user
aws iam create-user --user-name cloudwatch-ro-logs

# 2) attach AWS-managed CloudWatchLogsReadOnlyAccess
aws iam attach-user-policy \
  --user-name cloudwatch-ro-logs \
  --policy-arn arn:aws:iam::aws:policy/CloudWatchLogsReadOnlyAccess

# 3) mint an access key (only shown once -- capture immediately)
aws iam create-access-key --user-name cloudwatch-ro-logs
```

The `create-access-key` output returns the `AccessKeyId` and `SecretAccessKey` for the two fields above. The secret is shown only once, so capture it immediately. For temporary credentials, attach the same policy to a role, assume it with `aws sts assume-role`, and use the returned token in **AWS Session Token**.

Click **Test Connection**. You should see **Connection successful**.

#### 4. Create

Click **Create** to add the source.

### After creating

The source appears in the list as **Pending** with 0 streams. Within a couple of minutes, CloudWatch events begin arriving, streams are detected, and the source transitions to **Healthy**. Each stream is listed with its inferred **Stream Type** (e.g. `ec2/stage/clickhouse`, `eks`, `unknown`).

### Assign streams to workspaces

Streams need to be assigned to a workspace to be accessible. Open the source's actions menu (gear icon) and select **Assign Streams**, then check the streams you want the **Default** workspace (or any other workspace) to receive and **Save**.

See Assigning streams to workspaces for details.

### Tips

* Add a separate CloudWatch source per AWS account or region rather than sharing credentials across environments.
* Start with **Auto Discover** for the simplest setup; move to manual **Log Groups** when you need tighter control over what's ingested.

<br>


# Cloudflare

Receive logs from Cloudflare via an HTTP Logpush job.

Cloudflare Logpush batches log events to an HTTP endpoint. Dstl8 receives them as one HTTP source and figures out streams from what comes in. This page covers Workers Trace Events — logs and exceptions from your Workers.

### Prerequisites

* The `dstl8` CLI, installed and logged in. See [Dstl8 CLI](/controltheory-documentation/dstl8-docs/dstl8-cli) — check with `dstl8 profiles`, the active one is marked `►`.
* A Cloudflare account with Logpush. Workers Trace Events needs the **Workers Paid** plan.
* Account-level access — this dataset is account-scoped only, not per zone.

### Add a Cloudflare source

Create the source from the CLI or the web app — either way you end up with the same destination URL for the Cloudflare-side Logpush job.

#### From the CLI

**1. Run the wizard**

```bash
dstl8 sources add cloudflare
```

One prompt — the source name (default `cloudflare`). The secret's generated for you, so there's nothing to grab from Cloudflare first. `:skip` cancels.

<figure><img src="/files/sHEMXBLZXv14GgTpTsY6" alt=""><figcaption><p>dstl8 sources add cloudflare</p></figcaption></figure>

Prefer scripting it?

```bash
dstl8 sources add cloudflare --yes --name cloudflare-prod
```

Still prints the destination URL below, so it's fine for CI.

**2. Copy the destination URL**

The wizard ends with one URL — your webhook URL plus the Logpush secret as a query param:

`https://<org_id>.app.dstl8.ai/src-<id>?header_X-CF-Secret=<secret>`

That's the only thing the Cloudflare side needs. (Cloudflare turns `header_*` query params into real request headers — that's how the secret gets there without a separate field.)

> Sensitive. Don't commit it or paste it into shared docs.

> Grab it now — there's no command to print it again. If you lose it, the web app still has it.

**3. Assign the source to a workspace**

* **One workspace** (the common case): streams get assigned automatically.
* **A few workspaces**: pick from a checkbox list — `1-N:toggle a:all n:none enter:assign N q:skip`.
* **Skipped it, or used `--yes`?** Do it later:

```bash
dstl8 sources assign cloudflare-prod Default
```

<figure><img src="/files/UPh36Ls6onjyh5A5Rjn7" alt=""><figcaption><p>dstl8 sources assign cloudflare-prod Default</p></figcaption></figure>

#### From the web app

**1. Open the Add Source dialog**

From **Sources**, click **Add Source** and select **Cloudflare**.

<figure><img src="/files/cmPAXOtAS1LUHmfDWACl" alt=""><figcaption><p>Add Source → Cloudflare</p></figcaption></figure>

**2. Configure the source**

Give the source a unique name (e.g. `cloudflare-prod`) and click **Create**.

<figure><img src="/files/M2MfVj1VQOyNKFWEuu3k" alt=""><figcaption><p>Name the source</p></figcaption></figure>

**3. Copy the connection details**

Dstl8 displays the values you'll paste into Cloudflare's Logpush job:

| Field                   | Notes                                                                                   |
| ----------------------- | --------------------------------------------------------------------------------------- |
| Webhook URL             | `https://<org_id>.app.dstl8.ai/src-<id>`                                                |
| LogPush Secret          | Sent by Cloudflare in the `X-CF-Secret` header to authenticate incoming events.         |
| LogPush Destination URL | Webhook URL + `?header_X-CF-Secret=<secret>` — the one value the Cloudflare side needs. |

<figure><img src="/files/TXONcSFyvFNLhs74EIFz" alt=""><figcaption><p>Cloudflare Source Created</p></figcaption></figure>

> Sensitive. Don't commit it or paste it into shared docs.

**4. Assign the source to a workspace**

Pick the workspace that should receive this source's streams and click **Assign** (or **Skip** to assign later from the source's actions menu).

<figure><img src="/files/ndk20E9lqo8928GAnkyE" alt=""><figcaption><p>Assign the source to a workspace</p></figcaption></figure>

### Create the Logpush job in Cloudflare

With that destination URL copied:

#### 1. Open Logpush

In the left menu, go to **Observe → Investigate → Logpush**.

<figure><img src="/files/r4Jkvi6czn693oPH3eFv" alt=""><figcaption><p>Navigate to Logpush</p></figcaption></figure>

#### 2. Create a job

Click **Create a Logpush job**.

<figure><img src="/files/NfXpSy9quwPSnteRbvk6" alt=""><figcaption><p>Create a Logpush job</p></figcaption></figure>

#### 3. Pick HTTP

Select **HTTP** as the destination. Cloudflare will POST batches of log events to that endpoint on an interval instead of streaming them one by one.

<figure><img src="/files/5lke8gPipptwEe6lf7NO" alt=""><figcaption><p>Choose HTTP destination</p></figcaption></figure>

#### 4. Paste the URL

In **HTTP endpoint**, paste the destination URL you copied earlier. Don't strip the `header_X-CF-Secret` param or add others.

<figure><img src="/files/QC3ahBnZmCFBx2juxCU6" alt=""><figcaption><p>Paste the destination URL</p></figcaption></figure>

#### 5. Pick the dataset and submit

Select **Workers Trace Events**. Leave the rest at their defaults, then **Submit**.

<figure><img src="/files/89OKOyqtMNuLheW4rNPB" alt=""><figcaption><p>Select Workers Trace Events</p></figcaption></figure>

<figure><img src="/files/VL23eplxjn3mVpVvnGFj" alt=""><figcaption><p>Submit the Logpush job</p></figcaption></figure>


# GitHub Actions

Capture your GitHub action events

GitHub Actions emits events for CI/CD activity in your repositories. Dstl8 receives `workflow_run` and `workflow_job` events as a single webhook source and infers a stream per repository, per event type.

#### Add a GitHub source

The webhook secret is generated by Dstl8 during source creation, so you'll create the source first and then paste the values into GitHub. Open GitHub and Dstl8 in separate tabs.

**1. Open the Add Source dialog**

In Dstl8, from **Sources**, click **Add Source** and select **GitHub**.

**2. Configure the source**

In the **Configure GitHub Source** dialog:

* **Name**: a unique name to identify this source (e.g. the repository or org name).

Click **Create**.

**3. Copy the webhook values**

Dstl8 displays the values you'll paste into GitHub:

| Field       | Notes                                                                           |
| ----------- | ------------------------------------------------------------------------------- |
| Payload URL | URL for the webhook, e.g. `https://<org_id>.app.dstl8.ai/src-<id>`.             |
| Secret      | Auto-generated. GitHub uses this to sign payloads, and Dstl8 uses it to verify. |

Keep this dialog open while you set up the webhook on the GitHub side.

**4. Add the webhook in GitHub**

In your GitHub repository:

1. Go to **Settings → Webhooks → Add webhook**.
2. Paste the **Payload URL** from Dstl8.
3. Set **Content type** to `application/json`.
4. Paste the **Secret** from Dstl8.
5. Under **Which events would you like to trigger this webhook?**, select **Let me select individual events** and check **Workflow runs** and **Workflow jobs**. Deselect any other events, including **Pushes** (which is selected by default).
6. Leave **Active** checked and click **Add webhook**.

GitHub sends a ping payload to test the endpoint. You should see a green check next to the new webhook with *Last delivery was successful*.

> Only `workflow_run` and `workflow_job` events are supported. Other event types (push, pull request, etc.) are rejected by the receiver. Make sure no other events are selected in the webhook settings.

**5. Trigger a workflow**

If your repository doesn't already have a workflow, add one to generate events. For example, `.github/workflows/ci.yml`:

```yaml
name: CI

on:
  push:

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Echo
        run: echo "Build triggered by ${{ github.event_name }} on ${{ github.ref }}"
```

Create a branch, edit a file, and push. The workflow runs and GitHub sends `workflow_run` and `workflow_job` events to Dstl8.

#### After creating

The source appears in the Sources list as Pending with 0 streams. Once GitHub starts forwarding events, Dstl8 detects two streams per repository:

* `workflow_run` keyed by repository name, e.g. `combat-tracker`
* `workflow_job` keyed by repository name, e.g. `combat-tracker`

The source transitions to Healthy once events are flowing. If you point the webhook at multiple repositories (via an org-level webhook), each repository contributes its own pair of streams.

#### Assign streams to workspaces

Streams need to be assigned to a workspace to be accessible. Open the source's actions menu (gear icon) and select **Assign Streams**, then check the streams you want the Default workspace (or any other workspace) to receive and Save.

See Assigning streams to workspaces for details.

#### Tips

* Use a separate GitHub source per repository (or per org) rather than pointing multiple repositories at the same endpoint with collisions in mind. Streams are keyed by repository name, so pointing two unrelated repos at the same source still works, but the streams sit side by side in the same source.
* For org-wide coverage, configure the webhook at the organization level (**Org Settings → Webhooks**) instead of per repository. The same Payload URL and Secret apply.
* If the ping delivery fails, check the secret in the Dstl8 source matches what you pasted into GitHub. Mismatches show up as 401 responses in GitHub's **Recent Deliveries** tab on the webhook.
* If events stop arriving, GitHub's **Recent Deliveries** tab shows the full request and response for each attempt and supports redelivery, which is the fastest way to debug.


# Google Cloud

Pull logs from Google Cloud Logging into Dstl8.

Google Cloud Logging collects the logs of every service in a GCP project: GKE containers, Cloud Run revisions, Cloud Functions, Compute Engine instances, Cloud SQL, App Engine, load balancers, and audit logs. Dstl8 polls the Cloud Logging API as a single source, covering one project, and infers a stream from the GCP resource that produced each log.

### Add a Google Cloud source

The Project ID and the service account key both come from Google Cloud, so collect them before you open Dstl8.

#### 1. Create a service account and key

In the Google Cloud console, with the project you want to collect from selected:

1. Go to **IAM & Admin → Service Accounts** and click **Create service account**. Give it a name you'll recognize, such as `dstl8-log-reader`.
2. Grant it the **Logs Viewer** role (`roles/logging.viewer`) on the project, then finish creating the account.
3. Open the service account, go to the **Keys** tab, and click **Add key → Create new key → JSON**. The key file downloads once, and its contents are what you paste into Dstl8.

The same thing from the command line:

```bash
# 1) create the service account
gcloud iam service-accounts create dstl8-log-reader \
  --display-name="Dstl8 log reader"

# 2) grant read-only access to the project's logs
gcloud projects add-iam-policy-binding PROJECT_ID \
  --member="serviceAccount:dstl8-log-reader@PROJECT_ID.iam.gserviceaccount.com" \
  --role="roles/logging.viewer"

# 3) create the JSON key; paste this file's contents into Dstl8
gcloud iam service-accounts keys create dstl8-key.json \
  --iam-account="dstl8-log-reader@PROJECT_ID.iam.gserviceaccount.com"
```

Your **Project ID** is the string in the console's project picker, e.g. `my-gcp-project`, not the display name and not the numeric project number. `gcloud config get-value project` prints it.

> **Logs Viewer** covers everything except Data Access audit logs, which Cloud Logging treats as private. Grant **Private Logs Viewer** (`roles/logging.privateLogViewer`) instead if you need those.

#### 2. Open the Add Source dialog

In Dstl8, from **Sources**, click **Add Source** and select **Google Cloud**.

#### 3. Configure the source

In the **Configure Google Cloud Source** dialog:

| Field                          | Notes                                                                      |
| ------------------------------ | -------------------------------------------------------------------------- |
| **Name**                       | A unique name to identify this source.                                     |
| **Service Account Key (JSON)** | The full contents of the JSON key file you downloaded.                     |
| **Project ID**                 | The GCP project whose logs you want to collect.                            |
| **What to collect**            | `All logs` *(default)*, `Categories`, or `Custom filter (LQL)`. See below. |
| **Poll interval**              | How often Dstl8 polls Cloud Logging: `1m` *(default)* or `5m`.             |

**What to collect** decides how much of the project Dstl8 ingests:

* **All logs**: everything the service account is allowed to read.
* **Categories**: check any of GKE (Kubernetes), Cloud Run, Cloud Functions, Compute Engine, Cloud SQL, App Engine, Load Balancing, and Audit Logs. Dstl8 turns the selection into a Cloud Logging filter for you.
* **Custom filter (LQL)**: write the filter yourself in Cloud Logging query language, e.g. `resource.type="gce_instance" AND severity>=WARNING`. See [Google's query language reference](https://cloud.google.com/logging/docs/view/logging-query-language) for the full syntax.

Whichever you pick, Cloud Logging applies the filter server-side, so anything it excludes is never sent to Dstl8.

#### 4. Create

Click **Create** to add the source.

### After creating

The source appears in the Sources list as **Waiting for logs**. Streams usually appear within a couple of minutes, and the source transitions to **Healthy**. Logs trail real time by about two minutes, the lag Cloud Logging needs before entries are settled enough to read reliably.

Each stream's **Stream Type** comes from the GCP resource that produced the log:

| GCP resource    | Stream Type       | Stream name                     |
| --------------- | ----------------- | ------------------------------- |
| GKE (`k8s_*`)   | `gke`             | Kubernetes namespace            |
| Cloud Run       | `cloud-run`       | Service or job name             |
| Cloud Functions | `cloud-functions` | Function name                   |
| Compute Engine  | `gce`             | Log ID, e.g. `syslog`           |
| Cloud SQL       | `cloud-sql`       | Database ID                     |
| App Engine      | `app-engine`      | Module ID                       |
| Load Balancing  | `load-balancer`   | Log ID, e.g. `requests`         |
| Audit logs      | `audit`           | Audit log type, e.g. `activity` |

Anything else keeps its raw GCP resource type as the Stream Type, e.g. `pubsub_topic`, falling back to `unknown` when GCP reports no resource type. Each log keeps its GCP resource labels, severity, trace IDs, and HTTP request details as attributes you can filter on in Dstl8.

### Assign streams to workspaces

Streams need to be assigned to a workspace to be accessible. Open the source's actions menu (gear icon) and select **Assign Streams**, then check the streams you want the **Default** workspace (or any other workspace) to receive and click **Save Assignments**.

See [Assigning streams to workspaces](/controltheory-documentation/dstl8-docs/sources#assigning-streams-to-workspaces) for details.

### Tips

* One source covers one project. To collect from several projects, add a source per project, each with a service account key from that project.
* Cloud Logging's read quota is per project (60 requests/minute), and Dstl8 stays well under it. Sources pointed at the same project share that budget, so raise **Poll interval** to `5m` if you're running more than one.
* Cloud Logging matches log IDs exactly rather than by prefix, so to collect audit logs specifically, name them in full in a custom filter: `log_id("cloudaudit.googleapis.com/activity")`, and likewise `data_access`, `system_event`, or `policy`.
* If no logs arrive, check the service account against the **Project ID** you entered. The two are set independently, so a valid key for a project the service account can't read fails only once Dstl8 polls. Confirm the **Logs Viewer** role is granted on that project and that the Cloud Logging API is enabled for it.


# Kubernetes

Kube ahoy!

Collect container logs and cluster events from Kubernetes clusters via an in-cluster agent.

### How it works

The **ControlTheory agent** runs inside your cluster and forwards data to Dstl8. It has two components:

* **DaemonSet** — runs on every node to collect pod and container logs. Optionally exposes OTLP ports (`1757`, `1758`) on each node so applications co-located with the agent can push their own telemetry to it.
* **Cluster component** — runs once per cluster to collect cluster-wide events, metadata, and [topology snapshots](/controltheory-documentation/dstl8-docs/topology) (how your workloads, pods, services, and nodes connect).

You can install both (recommended, default), or either one independently.

### Add a Kubernetes source

#### 1. Create the source in Dstl8

From **Sources**, click **Add Source** and select **Kubernetes**. Configure the source and complete setup — Dstl8 will provide:

* Organization ID
* DaemonSet and cluster admission tokens
* Config and data endpoints
* A ready-to-run install command

#### 2. Install the agent

With `kubectl` configured against the target cluster, run the install script (the UI provides this command with your values prefilled):

```bash
./install.sh \
  -i <org-id> \
  --ds-token <ds-token> \
  --cluster-token <cluster-token> \
  --config-endpoint <config-url> \
  --data-endpoint <host:port> \
  --cluster-name <name> \
  -e <env>
```

The agent installs via Helm into the `controltheory` namespace by default.

#### 3. Verify

Check the rollout:

```bash
./install.sh -o status
```

In the Dstl8 UI, the source transitions from **Pending** to **Healthy** as the agent connects and begins forwarding. Streams appear as pods emit logs — typical stream types include Deployments, DaemonSets, StatefulSets, and Jobs.

### Install options

| Flag                | Description                                                |
| ------------------- | ---------------------------------------------------------- |
| `-i, --org-id`      | Organization identifier (required)                         |
| `--config-endpoint` | Config endpoint URL (required)                             |
| `--data-endpoint`   | Data endpoint `host:port` (required)                       |
| `--cluster-name`    | Name to identify this cluster (required)                   |
| `-e, --env`         | Deployment environment, e.g. `prod`, `staging` (required)  |
| `--ds-token`        | DaemonSet admission token (required for `ds` / `both`)     |
| `--cluster-token`   | Cluster admission token (required for `cluster` / `both`)  |
| `-t, --type`        | Install `ds`, `cluster`, or `both` (default: `both`)       |
| `-n, --namespace`   | Kubernetes namespace (default: `controltheory`)            |
| `--no-host-port`    | Don't expose OTLP ports (`1757` / `1758`) on nodes         |
| `--kubeconfig`      | Path to kubeconfig (default: `~/.kube/config`)             |
| `--helm-version`    | Pin a specific Helm chart version (default: latest stable) |

### Other operations

```bash
./install.sh -o preflight     # check node capacity, taints, and schedulability before install
./install.sh -o status        # report on current agent state
./install.sh -o uninstall     # remove the agent
```

Run **preflight** on large or constrained clusters to surface scheduling issues — node capacity, taints, and overprovisioned pods — before committing to install.

### Updating the agent

The agent ships as two Helm charts — `aigent-ds` (DaemonSet) and `aigent-cluster` (cluster component) — published to the ControlTheory chart repository at `https://control-theory.github.io/helm-charts`. The two charts are versioned in lockstep; always upgrade both together.

Check what you're running and what's available:

```bash
helm list -n controltheory            # installed releases and chart versions
helm repo update ct-helm
helm search repo ct-helm              # latest published versions
```

(`./install.sh -o status` also reports the installed release versions.)

#### Option 1: Re-run the install script (recommended)

`install.sh` uses `helm upgrade --install` and refreshes the chart repository on every run, so re-running your original install command upgrades the agent in place — same flags, same tokens, latest chart:

```bash
./install.sh \
  -i <org-id> \
  --ds-token <ds-token> \
  --cluster-token <cluster-token> \
  --config-endpoint <config-url> \
  --data-endpoint <host:port> \
  --cluster-name <name> \
  -e <env>
```

Don't have the command handy? Open **Sources** in the Dstl8 UI, open the Kubernetes source's actions menu, and select **Install Script** — it returns the same command with your values prefilled. To upgrade to a specific chart version instead of the latest, add `--helm-version <version>`.

#### Option 2: Upgrade with Helm directly

If you manage the releases with Helm yourself (or in CI), upgrade both charts in the install namespace:

```bash
helm repo add ct-helm https://control-theory.github.io/helm-charts
helm repo update ct-helm

helm upgrade aigent-ds ct-helm/aigent-ds -n controltheory --reuse-values
helm upgrade aigent-cluster ct-helm/aigent-cluster -n controltheory --reuse-values
```

`--reuse-values` carries forward the values the install script originally set (admission tokens, endpoints, cluster name), so you don't need to re-supply them. Pin a version with `--version <version>` on each command. If you installed into a different namespace, adjust `-n` accordingly.

{% hint style="warning" %}
`--reuse-values` keeps your previous values but does **not** pick up new chart defaults introduced by a release. If release notes mention new configuration options, prefer re-running the install script (Option 1), which re-applies every value explicitly on top of fresh chart defaults.
{% endhint %}

#### Verify and roll back

After upgrading, confirm the pods are healthy and the source stays **Healthy** in the Dstl8 UI:

```bash
kubectl get pods -n controltheory
./install.sh -o status
```

If something goes wrong, Helm keeps the previous release revision — roll back either chart:

```bash
helm rollback aigent-ds -n controltheory
helm rollback aigent-cluster -n controltheory
```

### Tips

* Install a separate Kubernetes source per cluster rather than sharing tokens across clusters.
* If OTLP ports `1757` / `1758` conflict with existing workloads on your nodes, pass `--no-host-port`.
* Assign the resulting streams to workspaces as described in Sources → Assigning streams to workspaces.


# OpenTelemetry (OTel)

Get your OTLP Flowing

Receive logs from any OpenTelemetry exporter.

### Add an OTLP source

#### 1. Open the Add Source dialog

From Sources, click Add Source and select OTLP.

#### 2. Configure the source

Give the source a unique name. By default, incoming telemetry is mapped to streams using two OTel resource attributes:

| Field                 | Notes                                                                                  |
| --------------------- | -------------------------------------------------------------------------------------- |
| Stream Type Attribute | OTel resource attribute mapped to `ct.stream.type`. Defaults to `service.name`.        |
| Stream Name Attribute | OTel resource attribute mapped to `ct.stream.name`. Defaults to `service.instance.id`. |

For most setups the defaults work as long as your exporter sets `service.name` and `service.instance.id` on the resource. The `ct.source.type` and `ct.source.id` fields are always set automatically.

For advanced mappings (e.g. computing stream type/name from different attributes), expand **Custom log statements** to provide [OTTL](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/pkg/ottl/README.md) transforms that run in the `resource` context and replace the simple mappings above. This is rarely needed.

#### 3. Create

Click Create. Dstl8 generates an OTLP/HTTP endpoint and a bearer token.

#### 4. Configure your exporter

| Field              | Notes                                                                                                                           |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------- |
| OTLP/HTTP Endpoint | Base URL for your exporter, e.g. `https://<org_id>.app.dstl8.ai/src-<id>`. The exporter POSTs to `/v1/logs`under this base URL. |
| Bearer Token       | Include in the `Authorization` header of every request.                                                                         |

Example OTel collector config:

```yaml
exporters:
  otlphttp:
    endpoint: https://<org_id>.app.dstl8.ai/src-<id>
    headers:
      Authorization: "Bearer <your-token>"
```

### After creating

The source appears in the list as Pending with 0 streams. Once your exporter starts sending telemetry, streams are detected from the configured attributes and the source transitions to Healthy. Each stream is listed with its inferred Stream Type (e.g. `checkout-service`, `payment-api`, etc..).

### Assign streams to workspaces

Streams need to be assigned to a workspace to be accessible. Open the source's actions menu (gear icon) and select Assign Streams, then check the streams you want the Default workspace (or any other workspace) to receive and Save.

See Assigning streams to workspaces for details.

### Tips

* Use `service.name` to group related instances under one Stream Type, and `service.instance.id` (pod name, hostname, container ID) to give each a unique Stream Name.
* Add a separate OTLP source per environment rather than sharing one endpoint across staging and production, so streams don't collide.


# Railway

Pull logs from Railway projects into Dstl8.

Railway emits deployment logs, the stdout and stderr of every service in a project. Dstl8 polls Railway's API as a single source, covering every persistent environment in the project, and infers a stream per service.

### Add a Railway source

The Project ID and the API token both come from Railway, so collect them before you open Dstl8.

#### 1. Get your Project ID and API token

In Railway, open the project, click **Settings** at the top right of the project view, and go to the **General** tab. Copy the **Project ID**. It's also the UUID in the project URL, `railway.com/project/<project-id>`.

Then create an API token:

1. Go to [Railway → Account → Tokens](https://railway.com/account/tokens).
2. Give the token a name. If the project belongs to a team workspace, select that workspace.
3. Create the token and copy it. Railway shows the value only once.

> Use an **Account** or **Workspace** token. A project token won't work, because it's scoped to a single environment while a Dstl8 source polls every persistent environment in the project.

#### 2. Open the Add Source dialog

In Dstl8, from **Sources**, click **Add Source** and select **Railway**.

#### 3. Configure the source

In the **Configure Railway Source** dialog:

| Field                               | Notes                                                                                                                                    |
| ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| **Name**                            | A unique name to identify this source.                                                                                                   |
| **Project ID**                      | The Project ID you copied from Railway.                                                                                                  |
| **API Token**                       | The Account or Workspace token you created.                                                                                              |
| **Filter** *(optional)*             | Railway log query syntax, applied server-side. Leave empty to collect every log.                                                         |
| **Poll interval**                   | How often Dstl8 polls Railway: `1m` *(default)*, `5m`, or `15m`.                                                                         |
| **Include PR preview environments** | Off by default. Turn it on to collect from PR preview environments too. Each one Dstl8 polls counts against your Railway API rate limit. |

Filters use Railway's query syntax: `@level:error` matches an attribute, `-@level:debug` negates one, and `AND` / `OR` join terms. See [Railway's logs documentation](https://docs.railway.com/observability/logs) for the full reference.

Click **Test Connection**. You should see **Connection successful**.

#### 4. Create

Click **Create** to add the source.

### After creating

The source appears in the Sources list as **Waiting for logs**, with no streams listed yet. Railway history isn't backfilled, so the first streams appear a few minutes after your services next emit logs, and the source transitions to **Healthy**.

Every Railway stream has the **Stream Type** `railway`, and each stream is named after the Railway service that produced it. Logs that Railway can't attribute to a service, such as plugin logs, land in a stream named `unknown`. A service deployed to several environments is still one stream. Each log keeps its Railway environment as an attribute you can filter on in Dstl8.

### Assign streams to workspaces

Streams need to be assigned to a workspace to be accessible. Open the source's actions menu (gear icon) and select **Assign Streams**, then check the streams you want the **Default** workspace (or any other workspace) to receive and click **Save Assignments**.

See [Assigning streams to workspaces](/controltheory-documentation/dstl8-docs/sources#assigning-streams-to-workspaces) for details.

### Tips

* One source covers one Railway project. Railway's rate limit is hourly and per token (100 requests/hour on Free, 1,000 on Hobby, 10,000 on Pro), so sources sharing a token share one budget. On the lower plans, raise **Poll interval** to `5m` or `15m`.
* Use a **Filter** when you want only part of the logs. Railway applies it before sending, so it trims what Dstl8 ingests, though not API usage, which depends on how many environments you poll and how often.
* If **Test Connection** fails, re-check both **Project ID** and **API Token**. Railway returns the same `Project not found` response for an invalid token and for an unknown project, so the error can't tell you which of the two is wrong.


# Supabase

Receive logs from Supabase via an OTLP log drain.

Supabase emits logs from your Postgres database, PostgREST, Auth, Storage, Realtime, and Edge Functions. Dstl8 receives them as a single OTLP source and infers a stream per log type.

### Add a Supabase source

#### 1. Open the Add Source dialog

From Sources, click Add Source and select Supabase.

#### 2. Configure the source

Give the source a unique name. There's no other configuration on this step — Dstl8 generates an OTLP endpoint and auth token for your Supabase log drain to send data to.

#### 3. Create

Click Create. Dstl8 displays the values you'll need to paste into Supabase:

| Field         | Notes                                                                |
| ------------- | -------------------------------------------------------------------- |
| OTLP Endpoint | URL for the log drain, e.g. `https://<org_id>.app.dstl8.ai/src-<id>` |
| Auth Token    | Bearer token for the `Authorization` header.                         |

Keep this dialog open while you set up the destination on the Supabase side.

#### 4. Configure your Supabase log drain

In your Supabase dashboard:

1. Go to **Project Settings → Log Drains**.
2. Click **Add destination** and select **OpenTelemetry Protocol (OTLP)** as the type.
3. Give the destination a name (e.g. "Dstl8").
4. Paste the **OTLP Endpoint** from Dstl8 into the OTLP Endpoint field. The full value should look like `https://<org_id>.app.dstl8.ai/src-<id>`
5. Leave **Protocol** as `HTTP/Protobuf` and keep **Gzip Compression** enabled.
6. Under **Custom Headers**, keep the default `Content-Type: application/x-protobuf` and add a new header with name `Authorization` and value `Bearer <auth-token>` (using the Auth Token from Dstl8).
7. Save.

> Supabase OTLP log drains are a paid add-on. Check Supabase's pricing page for the current cost.

### After creating

The source appears in the list as Pending with 0 streams. Once the Supabase log drain starts forwarding events, streams are detected per log type and the source transitions to Healthy.

### Assign streams to workspaces

Streams need to be assigned to a workspace to be accessible. Open the source's actions menu (gear icon) and select Assign Streams, then check the streams you want the Default workspace (or any other workspace) to receive and Save.

See Assigning streams to workspaces for details.

### Tips

* Use a separate Supabase source per Supabase project rather than pointing multiple projects at the same endpoint, so streams don't collide.
* If logs aren't arriving, check the log drain status in Supabase's Project Settings → Log Drains for delivery errors.


# Vercel

Receive logs from Vercel via a webhook log drain.

Vercel emits logs from your project's Functions, Edge Functions, Static Files, Rewrites, Builds, Firewall, and Redirects. Dstl8 receives them as a single webhook source and infers a stream per source type.

### Add a Vercel source

The webhook secret is generated by Vercel during drain creation, so you'll move between the two consoles. Open Vercel and Dstl8 in separate tabs.

#### 1. Start a drain in Vercel

In your Vercel dashboard:

1. Go to **Project Settings → Drains**.
2. Click **Add Drain**.
3. On **Choose data to drain**, select **Logs** and click **Next**.
4. On **Configure the drain**, set:
   * **Drain Name**: any name you'll recognize (e.g. `dstl8`).
   * **Projects**: choose **Specific Projects** and pick the Vercel project to drain.
   * **Sources**: leave all sources checked unless you have a reason to exclude one.
   * **Environment**: check **Production** (and **Preview** if you want preview deploys too).
5. Click **Next** to reach **Configure the destination**.

Leave this Vercel dialog open. You'll need the **Signature Verification Secret** value shown on this step in the next step.

#### 2. Open the Vercel source dialog in Dstl8

In Dstl8, from **Sources**, click **Add Source** and select **Vercel**.

#### 3. Configure the source

In the **Configure Vercel Source** dialog:

* **Name**: a unique name to identify this source (e.g. `vercel-prod` or the project name).
* **Signature Verification Secret**: copy the secret from Vercel's destination step and paste it here. Vercel uses this secret to sign webhook payloads, and Dstl8 uses it to verify them.

Click **Create**.

#### 4. Copy the webhook URL

Dstl8 displays the **Webhook URL** for your new source, e.g. `https://<org_id>.app.dstl8.ai/src-<id>`. Copy it. Keep this dialog open in case you need to reopen it.

#### 5. Finish the Vercel drain

Back in Vercel's **Configure the destination** step:

| Field                         | Value                                     |
| ----------------------------- | ----------------------------------------- |
| URL                           | The Webhook URL from Dstl8.               |
| Encoding                      | **JSON** or **NDJSON**. Either works.     |
| Signature Verification Secret | Already filled in by Vercel. Leave as is. |

Click **Test**. You should see *Success: Your endpoint sent a 2xx status*.

Click **Create Drain**.

### After creating

The source appears in Dstl8's Sources list as Pending with 0 streams. Once Vercel starts forwarding events, Dstl8 detects streams grouped by Vercel source type:

* `edge` — Edge Function invocations
* `lambda` — Function (serverless) invocations
* `static` — Static file requests
* `redirect` — Redirect responses

Other types (`rewrite`, `build`, `firewall`) appear as matching traffic arrives.

Within each type, streams are keyed by Vercel deployment ID, e.g. `dpl_AKjTAYM1iU1xpvvfTkxVCv3pJL3G`. A new deployment creates a new set of streams. The source transitions to Healthy once events are flowing.

### Assign streams to workspaces

Streams need to be assigned to a workspace to be accessible. Open the source's actions menu (gear icon) and select **Assign Streams**, then check the streams you want the Default workspace (or any other workspace) to receive and Save.

See [Assigning streams to workspaces](https://claude.ai/chat/f8733ef0-6c6d-491e-b91d-89419b661610) for details.

### Tips

* Use a separate Vercel source per Vercel project rather than pointing multiple projects at the same endpoint, so streams don't collide.
* Each Vercel deployment creates a new set of streams (one per type, keyed by `dpl_...`). After a deploy, re-run **Assign Streams** to pick up the new ones in your workspace.
* If the **Test** in Vercel fails with a signature error, the secret in the Dstl8 dialog doesn't match the one Vercel generated. Reopen the Dstl8 source and update it, or regenerate the secret in Vercel and paste the new value into Dstl8.
* If logs aren't arriving after creation, check the drain status in Vercel's **Project Settings → Drains** for delivery errors.


# Topology

See how your Kubernetes workloads connect — and what's in the blast radius when one breaks

Dstl8 captures the resource topology of your connected Kubernetes clusters — workloads, pods, services, ingresses, nodes, and the relationships between them. You can explore it visually in the web UI, browse it in the terminal, and query blast radius from the CLI. Möbius uses the same graph to reason about impact across the cluster during investigations.

### How it works

The cluster component of the [ControlTheory Kubernetes agent](/controltheory-documentation/dstl8-docs/sources/kubernetes) collects a topology snapshot roughly every **30 minutes** and sends it to Dstl8. That means:

* Topology requires a **Kubernetes source** with the cluster agent installed and running.
* A freshly installed agent can take up to half an hour to produce its first snapshot.
* Every topology view shows a freshness badge — **"Last scanned 12m ago"** — which turns to **"Stale — agent may be down"** if snapshots stop arriving.

## In the web UI

Open a workspace and click **Topology** in the sidebar. The link appears once the workspace has a Kubernetes source assigned and at least one cluster is reporting topology data. If the workspace spans multiple clusters, use the cluster selector in the header to switch between them; the header also shows totals (nodes · namespaces · workloads · pods).

Each Kubernetes source's detail page also has its own **Topology** tab with the same views, scoped to just that source's clusters.

There are two views, switched with the **Explorer** / **Graph** tabs.

### Explorer

A hierarchical tree of the cluster with a detail pane beside it:

* **Cluster** → **Nodes** (with pod counts per node) and a **Namespaces** section
* Each namespace groups its resources: Deployments, StatefulSets, DaemonSets, CronJobs, Jobs, Services, Ingresses, and Standalone Pods
* Pods are listed under their owning workload (ReplicaSets are collapsed away), with restart counts; Deployments and StatefulSets show `ready/desired` badges (e.g. `3/5`)

Type in the **Filter by name…** box to find a resource — the tree narrows to matches and their ancestors auto-expand. Click any item to see its details on the right: current status, metadata (labels, annotations, readiness, restarts), its **Relationships** — each one a clickable link that jumps to the related entity — and the entity's recent logs and log patterns from the last hour.

### Graph

An interactive network diagram of the same data:

* **Namespaces start collapsed** as summary boxes ("12 pods · 4 deploy · 1 sts · 2 svc") — click one to expand it in place, or use **Expand all** / **Collapse all**.
* **Filter by kind** with the toggle badges above the graph (Deployment, StatefulSet, DaemonSet, ReplicaSet, Job, CronJob, Pod, Service, Ingress). ReplicaSets and Jobs are hidden by default to reduce clutter.
* **Search** with the *Find workload, pod, service…* box.
* Scroll to zoom, drag the background to pan, drag nodes to rearrange. Click a node to open its detail panel; click the background to close it.

Nodes are color-coded by kind and carry a status dot (green healthy, amber pending/degraded, red failed, gray unknown). Edges are color-coded by relationship:

| Relationship | Meaning                                           |
| ------------ | ------------------------------------------------- |
| `owns`       | Ownership chain (Deployment → ReplicaSet → Pod)   |
| `targets`    | A Service targeting the pods it load-balances     |
| `routes_to`  | An Ingress routing traffic to a Service           |
| `runs_on`    | A Pod scheduled on a Node                         |
| `uses`       | A Pod referencing a ConfigMap or Secret           |
| `contains`   | Cluster containment (cluster → nodes, namespaces) |

### Reading blast radius

Select any entity and its detail panel lists both directions: outgoing relationships (what it owns, targets, or uses) and incoming ones (what runs on it, targets it, or depends on it). Selecting a Node, for example, immediately shows every pod scheduled on it; selecting a Service shows the ingresses routing to it and the pods behind it. That's the "what breaks if this goes away" question, answered before you drain the node.

{% hint style="info" %}
**Nothing showing?** The empty state means the workspace has no Kubernetes source yet, or the cluster agent hasn't produced a snapshot. Add a [Kubernetes source](/controltheory-documentation/dstl8-docs/sources/kubernetes), and give a fresh agent up to 30 minutes.
{% endhint %}

## In the TUI

`dstl8 tui` adds a **Topology** tab to any workspace that has a Kubernetes source. It renders the same resource tree as the web Explorer, navigable from the keyboard:

| Key     | Action                                      |
| ------- | ------------------------------------------- |
| `↑` `↓` | Move through the resource tree              |
| `Enter` | Expand / collapse the selected entity       |
| `→`     | Expand                                      |
| `←`     | Collapse / jump to parent                   |
| `c`     | Switch cluster (when several have topology) |

## From the CLI

`dstl8 topology` (alias: `topo`) exposes the graph for scripts, quick checks, and AI agents. All subcommands accept `--json` for raw output.

```bash
dstl8 topology clusters                          # list clusters that have topology data
dstl8 topology view                              # show the cluster resource tree
dstl8 topology view my-cluster -n payments       # one cluster, one namespace
dstl8 topology view --kinds deployment,service   # filter by kind
dstl8 topology impact deployment/checkout/payment-api   # blast radius for a workload
dstl8 topology impact node/worker-2 --direction dependents
```

### `dstl8 topology view`

Prints the resource tree (alias: `tree`). With one cluster reporting, the cluster argument is optional.

| Flag              | Description                                                 |
| ----------------- | ----------------------------------------------------------- |
| `--kinds`         | Comma-separated kind filter (e.g. `deployment,pod,service`) |
| `-n, --namespace` | Restrict to one namespace                                   |
| `--json`          | Raw JSON output                                             |

### `dstl8 topology impact`

Shows what depends on a component and what it depends on. The argument is `kind/namespace/name` — omit the namespace for cluster-scoped kinds:

```bash
dstl8 topology impact deployment/checkout/payment-api
dstl8 topology impact node/worker-2
```

| Flag            | Description                                              |
| --------------- | -------------------------------------------------------- |
| `-c, --cluster` | Cluster key (from `dstl8 topology clusters`)             |
| `--depth`       | Traversal depth, 1–5 (default 3)                         |
| `--direction`   | `dependents`, `dependencies`, or `both` (default `both`) |
| `--json`        | Raw JSON output                                          |

Typical uses: check what's riding on a node before draining it, list everything downstream of a service before a risky deploy, or let an MCP-connected agent pull `--json` impact data while investigating an incident.


# Events

Deploys, config changes, CI runs, and notes as first-class timeline markers

Platform events are first-class markers on the Dstl8 timeline — deploys, configuration changes, CI results, scaling actions, maintenance windows, and free-form notes. Send them from scripts, deploy pipelines, and CI, then correlate them with logs and incidents to answer the eternal question: *what changed right before things broke?*

Events come from several places:

* **Automatic** — Kubernetes events flow in through a connected [Kubernetes source](/controltheory-documentation/dstl8-docs/sources/kubernetes), and GitHub Actions `workflow_run` results are promoted automatically when a [GitHub source](/controltheory-documentation/dstl8-docs/sources/github-actions) is connected.
* **Manual** — send events from the CLI (`dstl8 events send`), the API, or the web UI (the **+ Create Event** button on a workspace's Events page).

### Where events show up

* **Web UI** — the **Events** page shows events across the whole organization; each workspace also has its own Events page. Events are rendered as color-coded markers on log timeline charts (blue for deploys, green for CI, purple for config changes, and so on), so a deploy line lands right on top of the error spike it caused.
* **Incidents** — related events appear alongside an incident so Möbius and humans can correlate cause and effect.
* **TUI** — `dstl8 tui` has an Events tab at both the org and workspace level. Press `Enter` on a row for a scrollable detail modal with the message, attributes, and annotations.
* **CLI** — `dstl8 events list`, `get`, and `search`, documented below.

### Event types and severities

| Type          | Typical use                                                   |
| ------------- | ------------------------------------------------------------- |
| `deploy`      | A deployment started or finished                              |
| `ci`          | A CI pipeline or workflow result                              |
| `config`      | A configuration change (feature flag, env var, infra setting) |
| `scaling`     | A scaling action (HPA change, replica count, instance resize) |
| `maintenance` | A maintenance window                                          |
| `note`        | A free-form human note ("started load test")                  |
| `custom`      | Anything else                                                 |

Severity is `info` (default), `warning`, or `error`.

## Viewing events from the CLI

```bash
dstl8 events list                                # last 24h, newest first
dstl8 events list --start -7d --type deploy,ci   # last 7 days, only deploys and CI
dstl8 events list -w myworkspace -s error        # workspace-scoped, error severity
dstl8 events list --source k8s,github            # only k8s- and github-sourced events
dstl8 events list --object service:checkout      # events for one object
dstl8 events list --search "rollback" --json     # keyword filter, NDJSON output
dstl8 events get <event-id>                      # full detail for one event
dstl8 events search "cache warmer failing"       # semantic search (keyword fallback)
```

`event` is an alias for `events`, and `--json` produces one JSON object per line for piping into `jq` or scripts.

**`list` flags:**

| Flag              | Description                                                   |
| ----------------- | ------------------------------------------------------------- |
| `--start`         | Start time (default `-24h`)                                   |
| `--end`           | End time (default now)                                        |
| `--type`          | Event type filter (comma-separated or repeatable)             |
| `-s, --severity`  | Severity filter (`info`, `warning`, `error`; comma-separated) |
| `--source`        | Source type filter (`cli`, `k8s`, `api`, `ui`, `github`, …)   |
| `--object`        | Object filter as `type:name` (e.g. `service:checkout`)        |
| `--search`        | Keyword search over title/message/reason/object               |
| `-w, --workspace` | Workspace name or ID                                          |
| `-n, --limit`     | Max number of events (default 100)                            |
| `--json`          | NDJSON output                                                 |

Time formats for `--start`/`--end`: relative (`-30m`, `-1h`, `-24h`, `-7d`, `now`) or absolute (`2026-07-08`, `2026-07-08T09:30:00`).

`dstl8 events search` uses semantic search when embeddings are available, falling back to keyword search otherwise (the mode used is printed to stderr).

## Sending events

```bash
dstl8 events send --type deploy --title "Deployed checkout v1.42" \
    --reason deploy.finished --object service:checkout --env prod \
    --attr image=checkout:v1.42 --attr sha=abc123

dstl8 events send --type note --title "Started load test" --occurred-at -5m

dstl8 events send --type config --title "Raised HPA max to 20" --severity warning
```

`send` prints the created event ID on success (or the full event with `--json`) so scripts can capture it. Events sent from the CLI are recorded with `source_type=cli`.

**`send` flags:**

| Flag               | Description                                                                                        |
| ------------------ | -------------------------------------------------------------------------------------------------- |
| `--type`           | **Required.** Event type (`deploy`, `ci`, `config`, `scaling`, `maintenance`, `note`, `custom`, …) |
| `--title`          | **Required.** Short one-line title                                                                 |
| `--reason`         | Machine-readable subtype (e.g. `deploy.finished`)                                                  |
| `--message`        | Longer message body                                                                                |
| `--severity`       | `info` (default), `warning`, or `error`                                                            |
| `--object`         | Object association as `type:name` (e.g. `service:checkout`)                                        |
| `--env`            | Environment (e.g. `prod`)                                                                          |
| `--cluster`        | Cluster name                                                                                       |
| `--namespace`      | Namespace                                                                                          |
| `-w, --workspace`  | Workspace name or ID (omit for an org-wide event)                                                  |
| `--attr key=value` | Attribute (repeatable)                                                                             |
| `--occurred-at`    | When it happened (`now`, `-5m`, or `2026-07-08T12:00:00Z`; default now)                            |
| `--ended-at`       | End time for span-like events (maintenance windows, load tests)                                    |
| `--dedup-key`      | Coalesce repeated events into one counted row                                                      |
| `--json`           | Print the full created event as JSON                                                               |

{% hint style="info" %}
Use `--dedup-key` for anything that might fire repeatedly (a retrying deploy hook, a flapping config sync). Events with the same dedup key coalesce into a single row with a count instead of flooding the timeline.
{% endhint %}

## CI/CD integration

Call `dstl8 events send` from a deploy script, GitHub Actions step, or Terraform hook to drop a marker on the timeline the moment a change ships:

```bash
# At the end of a deploy script:
dstl8 events send --type deploy \
  --title "Deployed $SERVICE $VERSION" \
  --reason deploy.finished \
  --object "service:$SERVICE" --env prod \
  --attr "sha=$GIT_SHA" --attr "version=$VERSION"
```

The CLI authenticates from its local config (`~/.config/dstl8/`), so the machine running the script needs to have been logged in once with `dstl8 login`. For headless runners, restore a pre-authenticated `~/.config/dstl8/` directory (its `profiles.toml` and `auth.json`) from your secrets store before calling the CLI.

{% hint style="success" %}
**Using GitHub Actions?** You may not need the CLI at all — when a [GitHub source](/controltheory-documentation/dstl8-docs/sources/github-actions) is connected, `workflow_run` results are promoted to platform events automatically.
{% endhint %}

## Deleting events

Deletion is intentionally restricted: only human- or tooling-authored events (`cli`, `api`, `ui`) can be removed, via the web UI. Machine-generated events (`k8s`, `github`) are an immutable timeline.


# Möbius Chat Slash Commands

Quick actions in Möbius Chat — type / to see them

Möbius Chat — the AI assistant built into the Dstl8 web UI — supports slash commands for common actions like saving facts to memory or resetting the conversation. They work anywhere the chat input appears: the chat sidebar (toggle it from the header), incident pages, and the explore heatmap.

### Using slash commands

Type `/` as the first character in the chat input and a command menu pops up above it. Keep typing to filter the list.

| Key     | Action                             |
| ------- | ---------------------------------- |
| `↑` `↓` | Move through the matching commands |
| `Tab`   | Autocomplete the selected command  |
| `Enter` | Run the selected command           |
| `Esc`   | Close the menu                     |

You can also click a command in the menu to run it. Commands that take an argument (`/remember`, `/forget`) wait for you to type the text and press `Enter`; the others run immediately.

### Available commands

#### `/remember <fact>`

Saves something to Möbius's persistent memory. Möbius stores the fact in its knowledge graph — attaching it to a related entity if one exists, or creating a new one — and confirms what it saved. Memory persists across conversations, so Möbius can use it in future investigations.

```
/remember the checkout service is owned by the payments team
/remember we deploy to prod every Tuesday afternoon
/remember error spikes in api-gateway around 2am are the nightly batch job — expected
```

#### `/forget <fact>`

The inverse of `/remember` — removes something from Möbius's persistent memory. Möbius finds the matching entry, deletes the specific fact (or the whole entity if nothing else is attached to it), and confirms what it removed.

```
/forget the checkout service is owned by the payments team
```

#### `/summarize`

Asks Möbius to summarize the conversation so far, highlighting the key points and any decisions made. Useful at the end of a long investigation before you close the tab — pair it with `/remember` to keep the conclusions.

#### `/clear`

Starts a new conversation immediately, clearing all messages in the current chat. Möbius's persistent memory is **not** affected — only the conversation history.

#### `/help`

Lists all available slash commands with their descriptions, right in the chat.

{% hint style="info" %}
**Memory is shared with your AI agents.** Facts saved with `/remember` live in the same knowledge graph your MCP-connected agents (Claude Code, Cursor, and others) can read and write — so context you teach Möbius in the browser is available to your coding agent in the terminal, and vice versa. See [MCP Integration](/controltheory-documentation/dstl8-docs/mcp-integration).
{% endhint %}


# MCP Integration

Get runtime context where you work

Dstl8 exposes an MCP (Model Context Protocol) server for each organization, giving AI assistants direct access to your logs, incidents, and observability tools.

### Get your MCP credentials

#### 1. Find your MCP endpoint

Each organization has a unique MCP endpoint:

```
https://<org_id>.app.dstl8.ai/mcp
```

Find your full URL in **Org** **Settings → Organizational Info.** The `org_id` is also surfaced in the product sign-in URL for the Dstl8 UI.

#### 2. Generate an API token

1. Go to **Org Settings → API Tokens**
2. Click on **Create API Token**
3. Give it a descriptive name (e.g. "Claude Code - Jon")
4. Copy the token — it won't be shown again

Your token will look like `dstl8_xxxxxxxx_xxxxxxxxxxxxxxxxxxxxxxxx`.

### Available tools

Once connected, your AI assistant has access to:

* **Log querying** — search, filter, and analyze log samples and patterns
* **Incident management** — create, update, and list incidents
* **Anomaly detection** — surface anomalies across your services
* **Sentiment and severity analysis** — understand log health at a glance
* **Knowledge graph** — explore entities and relationships across your system

### Client setup guides

Choose your AI assistant:

* [Claude Code](/controltheory-documentation/dstl8-docs/mcp-integration/claude-code)
* [Claude Desktop](/controltheory-documentation/dstl8-docs/mcp-integration/claude-desktop)
* [Codex](/controltheory-documentation/dstl8-docs/mcp-integration/codex)
* [ChatGPT](/controltheory-documentation/dstl8-docs/mcp-integration/chatgpt)
* [Cursor](/controltheory-documentation/dstl8-docs/mcp-integration/cursor)

### Example prompts

Once connected, try asking:

**Situational awareness**

* "What are my active incidents?"
* "What's going on in production?"
* "Give me a health pulse across all services"
* "Any active incidents in staging?"

**Targeted investigation**

* "Why is the auth service throwing 500s?"
* "Is this error happening in staging too, or just prod?"
* "Show me recurring patterns in the payments service"

**Deploy verification**

* "Did my last deploy fix the connection timeout issue?"
* "Compare error rates before and after the 2pm deploy"
* "Is staging converging with production after the hotfix?"

**Pre-coding context**

* "What should I know about the billing service before I make changes?"
* "Any known incidents or patterns related to the webhook handler?"
* "Show me recent anomalies in the service I'm about to refactor"

**Cross-environment correlation**

* "Is the error I'm seeing locally also showing up in prod?"
* "Compare my local logs against staging for the same service"
* "Is this safe to promote to production?"


# Claude Code

Brewing....

Connect Dstl8 to Claude Code for terminal-based observability access.

### Prerequisites

* Node.js 18+
* Claude Code installed
* Your [MCP endpoint and API token](/controltheory-documentation/dstl8-docs/mcp-integration)

### Setup

Run the following in your terminal (not inside Claude Code):

```bash
claude mcp add-json Dstl8 '{
  "command": "npx",
  "args": [
    "-y",
    "mcp-remote",
    "https://<org_id>.app.dstl8.ai/mcp",
    "--header",
    "Authorization: Bearer <your-token>"
  ]
}'
```

Replace `<org-id>` and `<your-token>` with your credentials from **Settings → Integrations → MCP**.

### Scoping

The command above saves to your local project config (`.mcp.json`). To make Dstl8 available across all your projects:

```bash
claude mcp add-json Dstl8 --scope user '{
  "command": "npx",
  "args": [
    "-y",
    "mcp-remote",
    "https://<org_id>.app.dstl8.ai/mcp",
    "--header",
    "Authorization: Bearer <your-token>"
  ]
}'
```

### Verify

Inside Claude Code, run:

```
/mcp
```

You should see `Dstl8` with status **connected**.

### Updating

To update your endpoint or token, re-run the setup command with `--overwrite`:

```bash
claude mcp add-json Dstl8 '{
  ...
}' --overwrite
```

### Troubleshooting

**Server shows "failed"** — Run `mcp-remote` directly to see the underlying error:

```bash
npx -y mcp-remote https://<org_id>.app.dstl8.ai/mcp \
  --header "Authorization: Bearer <your-token>"
```

**Connection timeout** — Increase the MCP startup timeout:

```bash
MCP_TIMEOUT=30000 claude
```


# Claude Desktop

Distilling...

Connect Dstl8 to Claude Desktop for observability access in chat.

### Prerequisites

* Node.js 18+
* Claude Desktop installed
* Your [MCP endpoint and API token](/controltheory-documentation/dstl8-docs/mcp-integration)

### Setup

Open your Claude Desktop config file:

| Platform | Path                                                              |
| -------- | ----------------------------------------------------------------- |
| macOS    | `~/Library/Application Support/Claude/claude_desktop_config.json` |
| Windows  | `%APPDATA%\Claude\claude_desktop_config.json`                     |
| Linux    | `~/.config/Claude/claude_desktop_config.json`                     |

Add the following inside the `mcpServers` object:

```json
{
  "mcpServers": {
    "Dstl8": {
      "command": "npx",
      "args": [
        "-y",
        "mcp-remote",
        "https://<org_id>.app.dstl8.ai/mcp",
        "--header",
        "Authorization: Bearer <your-token>"
      ]
    }
  }
}
```

Replace `<org-id>` and `<your-token>` with your credentials.

If you already have other MCP servers configured, add the `"Dstl8": { ... }` block alongside them inside the existing `mcpServers` object.

### Verify

1. Fully quit Claude Desktop (not just close the window)
2. Relaunch Claude Desktop
3. Look for the tools icon (hammer) in the input area
4. Click it to confirm Dstl8 tools are listed

### Troubleshooting

**Tools icon not appearing** — Make sure you fully quit and relaunched (not just closed the window). On macOS, use Cmd+Q.

**Server shows disconnected** — Check that `npx` is accessible from your system PATH. Open a terminal and run `npx --version` to confirm.

**Windows: "Connection closed" errors** — Use the `cmd /c` wrapper:

```json
{
  "mcpServers": {
    "Dstl8": {
      "command": "cmd",
      "args": [
        "/c",
        "npx",
        "-y",
        "mcp-remote",
        "https://<org_id>.app.dstl8.ai/mcp",
        "--header",
        "Authorization: Bearer <your-token>"
      ]
    }
  }
}
```


# Codex

Bubbling...

Connect Dstl8 to OpenAI Codex (CLI, VS Code extension, or Desktop app) for observability access while coding.

### Prerequisites

* Codex CLI, VS Code extension, or Desktop app installed
* Node.js 18+
* Your [MCP endpoint and API token](/controltheory-documentation/dstl8-docs/mcp-integration)

### Setup (CLI)

The quickest way is via the CLI:

```bash
codex mcp add Dstl8 --env DSTL8_TOKEN=<your-token> -- npx -y mcp-remote https://<org_id>.app.dstl8.ai/mcp --header "Authorization: Bearer <your-token>"
```

Replace `<org-id>` and `<your-token>` with your credentials from **Settings → Integrations → MCP**.

### Setup (config file)

Codex stores MCP config in `~/.codex/config.toml`. For project-scoped config, use `.codex/config.toml` in your project root.

#### Option A: Remote HTTP (recommended)

If your Dstl8 MCP endpoint supports direct HTTP connections:

```toml
[mcp_servers.Dstl8]
url = "https://<org_id>.app.dstl8.ai/mcp"
bearer_token_env_var = "DSTL8_TOKEN"
```

Then set the environment variable in your shell profile (`.bashrc`, `.zshrc`, etc.):

```bash
export DSTL8_TOKEN="dstl8_xxxxxxxx_xxxxxxxxxxxxxxxxxxxxxxxx"
```

#### Option B: Via mcp-remote

If direct HTTP doesn't connect (e.g. due to transport compatibility), use `mcp-remote` as a stdio bridge:

```toml
[mcp_servers.Dstl8]
command = "npx"
args = ["-y", "mcp-remote", "https://<org_id>.app.dstl8.ai/mcp", "--header", "Authorization: Bearer <your-token>"]
```

Replace `<org-id>` and `<your-token>` with your credentials.

### Verify

In the Codex CLI, run:

```
/mcp
```

You should see `Dstl8` listed as connected.

In the VS Code extension, go to the gear icon → **MCP settings** to check server status.

### Troubleshooting

**Server fails to connect** — Test `mcp-remote` directly:

```bash
npx -y mcp-remote https://<org_id>.app.dstl8.ai/mcp \
  --header "Authorization: Bearer <your-token>"
```

**Timeout on startup** — Increase the startup timeout in your config:

```toml
[mcp_servers.Dstl8]
startup_timeout_sec = 30.0
```


# ChatGPT

Sampling.....

Connect Dstl8 to ChatGPT via MCP for observability access in chat.

### Prerequisites

* ChatGPT Plus, Team, or Enterprise plan
* Your [MCP endpoint and API token](/controltheory-documentation/dstl8-docs/mcp-integration)

### Setup

1. Open ChatGPT and go to **Settings → Connectors → Add custom connector**
2. Enter the following:
   * **Name:** Dstl8
   * **URL:** `https://<org_id>.app.dstl8.ai/mcp`
   * **Authentication:** Bearer token
   * **Token:** your Dstl8 API token
3. Click **Save**

Replace `<org-id>` and token with your credentials.

### Verify

Start a new conversation and ask ChatGPT to list your available tools. You should see the Dstl8 observability tools listed.

### Troubleshooting

**Connector not connecting** — Verify your endpoint is reachable by running in a terminal:

```bash
curl -I -H "Authorization: Bearer <your-token>" \
  https://<org_id>.app.dstl8.ai/mcp
```

A `401` means the token is invalid. A `200` or `400` means the endpoint is reachable and the issue is on the ChatGPT side.

> **Note:** ChatGPT MCP support is relatively new and connector behavior may vary. If you run into issues, reach out to us at <support@controltheory.com>.


# Cursor

Boiling up.....

Connect Dstl8 to Cursor for observability access in your editor.

### Prerequisites

* Cursor installed
* Node.js 18+
* Your [MCP endpoint and API token](/controltheory-documentation/dstl8-docs/mcp-integration)

### Setup

Open your Cursor MCP config file at `~/.cursor/mcp.json` (or create it if it doesn't exist).

Add the following:

```json
{
  "mcpServers": {
    "Dstl8": {
      "command": "npx",
      "args": [
        "-y",
        "mcp-remote",
        "https://<org_id>.app.dstl8.ai/mcp",
        "--header",
        "Authorization: Bearer <your-token>"
      ]
    }
  }
}
```

Replace `<org-id>` and `<your-token>` with your credentials.

For project-scoped config, create a `.cursor/mcp.json` file in your project root instead.

### Verify

1. Restart Cursor
2. Open the MCP panel (**Cursor Settings → MCP**) to confirm Dstl8 shows as connected
3. In Composer or Agent mode, ask Cursor to list available tools

### Troubleshooting

**Server not connecting** — Test `mcp-remote` directly:

```bash
npx -y mcp-remote https://<org_id>.app.dstl8.ai/mcp \
  --header "Authorization: Bearer <your-token>"
```

**Windows users** — Use the `cmd /c` wrapper:

```json
{
  "mcpServers": {
    "Dstl8": {
      "command": "cmd",
      "args": [
        "/c",
        "npx",
        "-y",
        "mcp-remote",
        "https://<org_id>.app.dstl8.ai/mcp",
        "--header",
        "Authorization: Bearer <your-token>"
      ]
    }
  }
}
```


# Incidents

An incident is the unit Dstl8 uses to group everything it knows about a single problem in your system over a window of time. It is the container that holds the overall status, severity, time span, and a synthesized summary of what happened.

Most incidents and their events are created automatically by Möbius, the Dstl8 agent, as it analyzes your telemetry. You can also create an incident manually, which triggers Möbius to investigate it.

Each incident is made up of one or more events. An event is a single entry on the incident's timeline, scoped to one specific object such as a service, deployment, pod, or host. The relationship is one to many: an incident has many events, and every event belongs to exactly one incident.

### Incident (the parent)

The incident holds the aggregate view of the problem.

| Field                            | Description                                          |
| -------------------------------- | ---------------------------------------------------- |
| Title                            | Short description of the problem                     |
| Status                           | Workflow state in the incident lifecycle (see below) |
| Impact                           | Overall severity, for example major or critical      |
| Start / End time                 | The full window the incident spans                   |
| Summary / Description / Evidence | The rolled-up narrative of what happened             |

#### Incident lifecycle

An incident moves through a fixed set of workflow states:

`Open` → `Investigating` → `Active` → `Resolved` → `Closed`

This is a workflow state. It is not the same thing as an event's state, described below.

### Event (the child)

An event is one datapoint on the incident's timeline. Each event is anchored to a specific object and carries its own values, independent of the incident's aggregate.

| Field                     | Description                                              |
| ------------------------- | -------------------------------------------------------- |
| Object type / Object name | What the event is about (service, deployment, pod, host) |
| Impact                    | Per-event severity                                       |
| State                     | `open` or `resolved`, independent of the incident        |
| Start / End time          | The event's own, usually narrower, window                |
| Occurrences               | How many times the event fired                           |

### How incidents and events relate

* An incident says "something is wrong in this window, here is the overall status and story."
* Events are the individual symptoms on that incident's timeline. There is one event per object or symptom, and each event resolves independently.
* Because they are tracked separately, an event can be resolved while the incident is still moving through its lifecycle toward `Closed`.

A useful way to read it: incident status is a workflow state (`Open` through `Closed`), while an event's state is just `open` or `resolved`. They are different fields tracking different things.

### Creating an incident manually

While Möbius creates most incidents on its own, you can open one manually from the Incidents page. Creating an incident this way triggers Möbius to investigate it.

The form takes:

* **Workspace**: the workspace the incident belongs to.
* **Title**: a short description of the problem.
* **Summary**: a one-line summary.
* **Description** (optional): more detail.
* **Impact**: severity, defaulting to None.
* **Status**: starting lifecycle state, defaulting to Investigating.
* **Start Time**: when the incident began, defaulting to now.
* **End Time** (optional): leave empty for an ongoing incident.


# Alerts and Notifications

Alerts turn incidents into notifications. This page covers how alerting works in Dstl8 and how to create and edit alert rules.

### How alerting works

The flow has four parts:

`Incident` → `Alert rule` → `Detection` → `Notifications` (one per channel)

* An **alert rule** defines which incidents you care about and where to send notifications. Incident is the only rule Kind currently supported.
* When an incident matches a rule, Dstl8 creates a single **detection** that records the rule firing.
* That detection is distributed as a **notification** to each channel attached to the rule.
* Detections are also a persistent record in the UI, so you can always see which rules fired and when.

### Channels

A channel is a destination for notifications. Dstl8 supports three channel types:

* **Email**: a default email channel (**Default Admin Alerts**) is created automatically and sends to the org admin who signed up for the account. You can add more email channels for other addresses/users.
* **Slack**: requires a Slack integration at the org level.
* **Teams**: requires a Teams integration at the org level.

To add a channel, go to **Channels**, click **Add Channel**, give it a name, choose the channel type, and (for Slack or Teams) select the integration to use.

### Integrations

Slack and Teams channels are backed by org-level integrations. Set these up under **Integrations** before creating a channel of that type. Email is already setup and needs no integration.

### Creating an alert rule

From **Alert Rules**, click **Create Alert Rule**. There are two steps.

#### Step 1: Basic Info

* **Name**: a label for the rule.
* **Kind**: Incident. This is fixed and cannot be changed after creation.
* **Enabled**: whether the rule is active.
* **Channels** (optional): the channels that receive notifications when the rule fires.
* **Workspaces** (optional): scope the rule to specific workspaces.

#### Step 2: Detection

These conditions control which incidents match the rule:

* **Statuses**: scope the rule to incidents in selected lifecycle statuses.
* **Environments** (optional): scope to specific deployment environments.
* **Impact**: filter by incident severity.
* **Resource Types**: scope to specific resource kinds such as pod or service.
* **Trigger Mode**: when the rule fires relative to the incident lifecycle. `Creation` fires when an incident is first created. `Status Change` fires when an incident changes status.
* **Min Age (seconds)**: minimum incident age before the rule triggers. Only applies when Trigger Mode is `Status Change`.

Click **Create** to save the rule.

### Editing an alert rule

From **Alert Rules**, open a rule and edit it. On the **Basic Info** step you can update the name, channels, and workspaces. Kind cannot be changed.

### Detections

Detections are the persistent log of rule activity. Each row shows when the detection was created, the timestamp of interest, the rule Kind and value (for example `critical`), the workspace and environment, and which rule fired.

### Example: send default incident emails to a teammate

To have another team member receive email notifications for incidents:

1. Go to **Channels** and click **Add Channel**.
2. Set the channel type to **Email** and enter the teammate's address, for example `new_user@example.com`.
3. Go to **Alert Rules** and edit the **Default incident rule**.
4. Add the new channel under **Channels** and save.

The teammate now receives email for every incident that matches the rule.


# Release Notes

What's new in Dstl8

## July 20, 2026

### Log Viewer

* **Better filtering** — select multiple values within a single dimension, and filter by sentiment.
* **Source labels** — every log line now shows which source it came from.
* **Drag-to-select improvements** — selecting a time range on the chart now shows the selected time as you drag, adds a reset button to clear the selection, and no longer leaves a gap at the end of the range.
* Fixed a vertical spacing issue that could cause log lines to overlap.

### Log detail modal

* Active filters are easier to see, and sentiment is now shown.
* Source labels appear here too, matching the Log Viewer.

### Incidents

* Changing an incident's state now prompts for a reason, so the incident timeline stays complete.
* The Sources section is now clickable — jump straight to a source's details page.
* The **Investigating** label is now legible in dark mode.

### Topology

* A new **Namespaces** section in the resource tree makes it clearer what you're looking at.
* Selecting an object now shows its related logs and log patterns right in the details panel.

### Anomalies

* Anomalies are now surfaced on the workspace dashboard, source details, and incident details pages.
* Each anomaly shows what was detected, why it was flagged, and its related log patterns.
* A **View Logs** button drops you into the Log Viewer, pre-filtered to the logs that triggered the anomaly.

### Other improvements

* Delete buttons and confirmations are now consistent across the UI.
* The workspace list is now sorted alphabetically.
* The setup guide's **Need a hand?** button now hides once you've completed the setup flow.
* The setup guide has a new **Chat instead** button to jump straight into Möbius Chat.
* Sources shown on workspace views are now clickable and link to the source details page — including sources that are still loading.
* The **MCP** section in the left navigation is now **MCP / CLI**, with CLI setup instructions added alongside the MCP integrations.
* Fixed: the source details page showed the source ID instead of its name.


# User Guide

Master Gonzo's features and workflows with these comprehensive guides. Whether you're analyzing application logs, debugging system issues, or monitoring services in real-time, this section covers everything you need to become proficient with Gonzo.

### What You'll Learn

The User Guide is organized to take you from understanding the interface to mastering advanced analysis techniques:

#### 🖥️ **Understanding the Interface**

Learn how Gonzo's k9s-inspired 2x2 grid layout provides four specialized views of your log data, each optimized for different aspects of analysis.

#### 🎮 **Mastering Navigation**

Discover keyboard shortcuts, mouse controls, and navigation techniques that make log analysis fast and efficient.

#### 📊 **Input Methods & Sources**

Explore all the ways to get log data into Gonzo - from simple files to real-time streams, OpenTelemetry integration, and advanced piping scenarios.

#### 🔍 **Search & Filtering**

Master advanced filtering techniques, regex patterns, and search strategies to quickly find what matters in your logs.

#### 🚀 **Advanced Workflows**

Put it all together with real-world usage patterns, performance optimization, and power-user techniques.

### Guide Overview

{% hint style="info" %}
**New to Gonzo?** Start with Interface Overview to understand the core layout, then work through the guides in order.
{% endhint %}

#### Interface Overview

**Essential foundation for all Gonzo usage**

Understand the 2x2 grid layout and what each panel does:

* **Log Viewer** - Real-time log feed with color-coded severity levels
* **Word Frequency** - Most common terms and keywords in your logs
* **Attributes** - Structured data extracted from JSON and logfmt logs
* **Counts** - Analytics hub with patterns, trends, and time-series data

**Time to complete:** 10-15 minutes\
**Prerequisites:** Basic Gonzo installation

***

#### Navigation & Controls

**Master efficient log analysis workflows**

Complete reference for keyboard shortcuts and mouse controls:

* Panel switching and focus management
* Scrolling and selection techniques
* Global controls (pause, reset, filtering)
* Context-sensitive shortcuts for each panel

**Time to complete:** 15-20 minutes\
**Prerequisites:** Interface Overview

***

#### Log Input Methods

**Get data into Gonzo from any source**

Comprehensive coverage of all input methods:

* File analysis (single, multiple, glob patterns)
* Real-time log following (`--follow` mode)
* Stdin processing and piping workflows
* OpenTelemetry Protocol (OTLP) integration
* Advanced streaming scenarios

**Time to complete:** 20-25 minutes\
**Prerequisites:** Basic command-line familiarity

***

#### Filtering & Search

**Find exactly what you need in your logs**

Advanced techniques for log filtering and search:

* Regex patterns and examples
* Attribute-based filtering
* Severity-level filtering
* Text highlighting and search
* Performance optimization for large datasets

**Time to complete:** 20-30 minutes\
**Prerequisites:** Interface Overview, basic regex knowledge helpful

***

#### Detailed Usage Guide

**Real-world patterns and advanced techniques**

Comprehensive usage patterns and power-user techniques:

* Complex multi-source analysis
* Performance tuning and optimization
* Integration with existing toolchains
* Troubleshooting common scenarios
* Best practices from the community

**Time to complete:** 30-45 minutes\
**Prerequisites:** All previous User Guide sections

### Learning Paths

Choose your path based on your current experience and goals:

{% tabs %}
{% tab title="New User Path" %}
**Complete beginner to Gonzo**

1. Interface Overview - Understand the layout
2. Navigation & Controls - Learn basic shortcuts
3. Log Input Methods - Start with file analysis
4. Filtering & Search - Find relevant logs
5. Practice with your own log files

**Estimated time:** 2-3 hours total
{% endtab %}

{% tab title="Experienced User Path" %}
**Familiar with log analysis tools**

1. Interface Overview - See what's unique about Gonzo
2. Log Input Methods - Advanced integration patterns
3. Filtering & Search - Regex and advanced techniques
4. Detailed Usage Guide - Power-user workflows

**Estimated time:** 1-2 hours total
{% endtab %}

{% tab title="Integration Focused" %}
**Need to integrate Gonzo into existing workflows**

1. Log Input Methods - OTLP and streaming integration
2. Interface Overview - Understand output and analysis
3. Detailed Usage Guide - Advanced patterns
4. Check Integration Examples section

**Estimated time:** 1-2 hours total
{% endtab %}
{% endtabs %}

### Quick Reference

Once you're familiar with the basics, these quick references will be handy:

#### Most-Used Keyboard Shortcuts

| Key                 | Action            | Context       |
| ------------------- | ----------------- | ------------- |
| `Tab` / `Shift+Tab` | Switch panels     | Global        |
| `Space`             | Pause/unpause     | Global        |
| `/`                 | Enter filter mode | Global        |
| `↑/↓` or `k/j`      | Navigate          | Any list      |
| `Enter`             | View details      | Selected item |
| `r`                 | Reset data        | Global        |
| `q`                 | Quit              | Global        |

#### Essential Command Patterns

```bash
# Basic file analysis
gonzo -f application.log

# Real-time monitoring
gonzo -f /var/log/app.log --follow

# Multiple sources
gonzo -f "*.log" --follow

# Piping from other tools
kubectl logs -f deployment/app | gonzo
```

### What's Next?

After completing the User Guide, you'll be ready for:

* **Advanced Features** - AI integration, pattern analysis, and complex workflows
* **Configuration** - Customize Gonzo for your specific needs
* **Integration Examples** - Real-world scenarios and use cases
* **Troubleshooting** - Solutions to common problems

### Getting Help

If you get stuck while working through these guides:

* 📖 Check the specific guide's troubleshooting sections
* 🔍 Use the search function to find related topics
* 🐛 Report documentation issues on [GitHub](https://github.com/control-theory/gonzo/issues)
* 💬 Ask questions in [GitHub Discussions](https://github.com/control-theory/gonzo/discussions)

***

**Ready to become a Gonzo power user?** 🚀 Start with the Interface Overview and work your way through each guide!


# Interface Overview

Gonzo's terminal interface is designed for efficiency and insight. The k9s-inspired 2x2 grid layout provides four specialized views of your log data, each optimized for different aspects of log analysis.

### The 2x2 Grid Layout

```
┌─────────────────────┬─────────────────────┐
│                     │                     │
│    LOG VIEWER       │  WORD FREQUENCY     │
│   (Top Left)        │   (Top Right)       │
│                     │                     │
│  📄 Real-time logs  │  📊 Keyword counts  │
│  Color-coded by     │  Most frequent      │
│  severity level     │  terms ranked       │
│                     │                     │
├─────────────────────┼─────────────────────┤
│                     │                     │
│   ATTRIBUTES        │      COUNTS         │
│  (Bottom Left)      │  (Bottom Right)     │
│                     │                     │
│  🏷️ Structured data │  📈 Analytics hub   │
│  Key-value pairs    │  Patterns & trends  │
│  from logs          │  Time-series data   │
│                     │                     │
└─────────────────────┴─────────────────────┘
```

{% hint style="info" %}
**Navigation Tip:** Use `Tab` and `Shift+Tab` to move between panels, or click directly on any panel to focus it.
{% endhint %}

### Panel 1: Log Viewer (Top Left)

The **Log Viewer** is your primary interface for examining individual log entries in real-time.

#### What You'll See

```
┌─ LOG VIEWER ─────────────────────────┐
│ 2024-01-15 10:30:00 [INFO] web-api  │ ← Timestamp, level, service
│ 2024-01-15 10:30:05 [ERROR] web-api │ ← Color-coded by severity
│ 2024-01-15 10:30:10 [WARN] auth     │ ← Auto-scroll with new entries
│ 2024-01-15 10:30:15 [INFO] web-api  │
│ 2024-01-15 10:30:20 [ERROR] db      │
│ ▼ More logs below...                │ ← Scroll indicator
└─────────────────────────────────────┘
```

#### Color Coding

Gonzo uses intuitive color coding to help you quickly identify issues:

| Level        | Color          | When You'll See It                           |
| ------------ | -------------- | -------------------------------------------- |
| 🔴 **ERROR** | Red/Bright Red | Critical failures, exceptions, system errors |
| 🟡 **WARN**  | Yellow/Orange  | Warnings, deprecations, potential issues     |
| 🔵 **INFO**  | Blue/Cyan      | General information, successful operations   |
| ⚪ **DEBUG**  | White/Gray     | Detailed debugging information               |
| 🟣 **TRACE** | Purple/Magenta | Verbose tracing information                  |

#### Features

* **Auto-scroll**: New logs automatically appear at the bottom
* **Smart pause**: Auto-scroll stops when you navigate up, resumes when you go to bottom
* **Intelligent parsing**: Automatic detection of timestamps, levels, and services
* **Overflow handling**: Maintains performance with high-volume log streams
* **Selection highlighting**: Current entry is highlighted for easy reference

#### Navigation

| Key                | Action         | Description                             |
| ------------------ | -------------- | --------------------------------------- |
| **↑/↓** or **k/j** | Move up/down   | Navigate through log entries            |
| **Page Up/Down**   | Jump by pages  | Navigate quickly through large sets     |
| **Home**           | Jump to top    | Go to oldest log in buffer              |
| **End**            | Jump to bottom | Go to newest logs (resumes auto-scroll) |
| **Enter**          | View details   | Open detailed modal for selected log    |

{% tabs %}
{% tab title="Real-time Mode" %}
**When following logs (`--follow`):**

* New entries automatically scroll into view
* Pauses auto-scroll when you navigate up
* Resume by pressing `End` or scrolling to bottom
* Use `Space` to globally pause/unpause the entire dashboard
  {% endtab %}

{% tab title="File Analysis Mode" %}
**When analyzing static files:**

* Shows all log entries from the file
* Full navigation through the complete dataset
* No auto-scrolling behavior
* Perfect for investigating historical issues
  {% endtab %}
  {% endtabs %}

### Panel 2: Word Frequency (Top Right)

The **Word Frequency** panel shows the most common words and terms across all your logs.

#### What You'll See

```
┌─ WORD FREQUENCY ─────────────────────┐
│ error        (1,247) ████████████████ │ ← Most frequent term
│ timeout      (892)   ████████████     │
│ database     (654)   ████████         │
│ connection   (521)   ██████           │
│ user         (445)   █████            │
│ login        (398)   █████            │
│ failed       (234)   ███              │
│ success      (198)   ██               │
│ request      (156)   ██               │
│ response     (134)   █                │
└─────────────────────────────────────┘
```

#### Features

* **Real-time updates**: Frequency counts update as new logs arrive
* **Visual bars**: Bar length represents relative frequency
* **Automatic filtering**: Ignores common words like "the", "and", "of"
* **Case insensitive**: "Error" and "error" are counted together
* **Memory efficient**: Configurable limit on tracked words

#### Use Cases

{% tabs %}
{% tab title="Problem Identification" %}
**Spot issues quickly:**

* High frequency of "error", "fail", "timeout"
* Unusual spikes in specific service names
* New error messages appearing in top words
  {% endtab %}

{% tab title="System Health" %}
**Monitor overall health:**

* Balance between "success" and "error" terms
* Frequency of performance-related words
* Appearance of new warning indicators
  {% endtab %}

{% tab title="Service Analysis" %}
**Understand service activity:**

* Which services are most active
* Common operations being performed
* Resource usage patterns
  {% endtab %}
  {% endtabs %}

#### Interaction

* **Click on words**: Filter logs to show only entries containing that word
* **Arrow navigation**: Browse through the frequency list
* **Enter**: Apply word as a filter to the Log Viewer

### Panel 3: Attributes (Bottom Left)

The **Attributes** panel displays structured data extracted from your logs, perfect for JSON and logfmt formats.

#### What You'll See

```
┌─ ATTRIBUTES ─────────────────────────┐
│ service      = "web-api"             │ ← Key-value pairs
│ level        = "error"               │
│ user_id      = "12345"               │ ← Extracted from JSON/logfmt
│ duration     = "30.5s"               │
│ method       = "POST"                │
│ status_code  = "500"                 │
│ endpoint     = "/api/users"          │
│ error        = "database timeout"    │
│ trace_id     = "abc123def456"        │
│ timestamp    = "2024-01-15T10:30:00" │
└─────────────────────────────────────┘
```

#### Supported Formats

{% tabs %}
{% tab title="JSON Logs" %}

```json
{
  "timestamp": "2024-01-15T10:30:00Z",
  "level": "error",
  "service": "web-api",
  "message": "Database timeout",
  "user_id": "12345",
  "duration": 30.5,
  "trace_id": "abc123def456"
}
```

**Features:**

* Nested object support
* Array handling
* Type preservation (strings, numbers, booleans)
* Automatic flattening of complex structures
  {% endtab %}

{% tab title="Logfmt Format" %}

```
time=2024-01-15T10:30:00Z level=error service=web-api msg="Database timeout" user_id=12345 duration=30.5s trace_id=abc123def456
```

**Features:**

* Key-value pair extraction
* Quoted value support
* Space-separated format
* Mixed data type handling
  {% endtab %}

{% tab title="Plain Text" %}

```
2024-01-15 10:30:00 [ERROR] web-api: Database timeout (user: 12345, duration: 30.5s)
```

**Features:**

* Pattern-based extraction
* Common log format recognition
* Timestamp and level detection
* Service name identification
  {% endtab %}
  {% endtabs %}

#### Features

* **Smart extraction**: Automatically detects and parses structured data
* **Type awareness**: Preserves data types (strings, numbers, booleans)
* **Nested support**: Handles complex JSON objects and arrays
* **Real-time updates**: Shows attributes from the currently selected log entry
* **Search integration**: Click attributes to filter logs

#### Navigation

* **↑/↓ arrows**: Browse through attribute list
* **Click attributes**: Use as search terms
* **Copy-friendly**: Easily copy attribute names and values

### Panel 4: Counts (Bottom Right)

The **Counts** panel is your analytics hub, providing insights into log patterns, severity distribution, and trends.

#### What You'll See

```
┌─ COUNTS ─────────────────────────────┐
│ Severity Distribution:               │
│ ERROR  █████████████████████   (45%) │
│ WARN   ██████████████          (30%) │
│ INFO   ███████                 (20%) │
│ DEBUG  ██                       (5%) │
│                                      │
│ Total Entries: 2,847                 │
│ Time Span: 2h 15m                    │
│ Entries/min: 21.2                    │
│                                      │
│ Press Enter for detailed analysis... │
└─────────────────────────────────────┘
```

#### Key Metrics

| Metric                    | Description                        | What It Tells You     |
| ------------------------- | ---------------------------------- | --------------------- |
| **Severity Distribution** | Percentage breakdown by log level  | Overall system health |
| **Total Entries**         | Count of all processed log entries | Volume of activity    |
| **Time Span**             | Duration from first to last log    | Analysis window       |
| **Entries/min**           | Average log frequency              | System activity level |
| **Pattern Count**         | Number of identified patterns      | Log complexity        |

#### Detailed Analysis Modal

Press `Enter` on the Counts panel to open the comprehensive analysis modal:

```
┌─ LOG ANALYSIS (Press ESC to close) ──────────────────────────────┐
│                                                                  │
│ Time-Series Heatmap (60-minute rolling window):                  │
│ ┌────────────────────────────────────────────────────────────┐   │
│ │Time: 60  50  40  30  20  10  0 (minutes ago)              │   │  
│ │ERROR ████░░██████░░░░████████████████ High intensity      │   │
│ │WARN  ░░██████░░████░░░░██████░░░░░░░░ Medium intensity    │   │
│ │INFO  ░░░░░░░░░░░░░░░░████░░░░░░░░░░░░ Low intensity       │   │
│ │DEBUG ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ Minimal activity    │   │
│ └────────────────────────────────────────────────────────────┘   │
│                                                                  │
│ Top 3 Patterns by Severity:                                     │
│ ┌────────────────────────────────────────────────────────────┐   │
│ │ ERROR:                                                     │   │
│ │ 1. Database connection timeout (247 occurrences)          │   │
│ │ 2. User authentication failed (156 occurrences)           │   │
│ │ 3. API rate limit exceeded (89 occurrences)               │   │
│ │                                                            │   │
│ │ WARN:                                                      │   │
│ │ 1. Slow query detected (324 occurrences)                  │   │
│ │ 2. Memory usage high (198 occurrences)                    │   │
│ │ 3. Cache miss rate elevated (156 occurrences)             │   │
│ └────────────────────────────────────────────────────────────┘   │
│                                                                  │
│ Service Distribution:                                            │
│ web-api: 1,247 entries (44%)  database: 892 entries (31%)      │
│ auth: 654 entries (23%)       cache: 54 entries (2%)           │
│                                                                  │
│ Navigation: ↑/↓ Scroll, Mouse Wheel, ESC to close               │
└──────────────────────────────────────────────────────────────────┘
```

#### Advanced Features

{% tabs %}
{% tab title="Heatmap Visualization" %}
**Time-series heatmap shows:**

* 60-minute rolling window
* Severity levels vs. time
* 1-minute resolution buckets
* ASCII intensity indicators (░▒▓█)
* Real-time updates as logs arrive

**Best for:**

* Identifying when problems occurred
* Spotting patterns over time
* Correlating events across severity levels
  {% endtab %}

{% tab title="Pattern Detection" %}
**Powered by drain3 algorithm:**

* Automatic pattern extraction
* Separate tracking per severity level
* Real-time pattern discovery
* Count tracking for each pattern

**Best for:**

* Finding recurring issues
* Identifying root causes
* Understanding log diversity
  {% endtab %}

{% tab title="Service Analysis" %}
**Service distribution tracking:**

* Extracts service names from logs
* Tracks activity per service
* Real-time service health overview
* Identifies chatty or silent services

**Best for:**

* Multi-service debugging
* Load balancing insights
* Service health monitoring
  {% endtab %}
  {% endtabs %}

### Global Interface Features

#### Status Indicators

```
┌─ Gonzo v1.0.0 ─────── Status: LIVE ── Paused: No ── AI: Ready ──┐
│                                                                  │
│ [Active filter: level.*error] [Update: 1.2s] [Entries: 1,247]   │
```

| Indicator         | Meaning                  | States                     |
| ----------------- | ------------------------ | -------------------------- |
| **Status**        | Data source state        | LIVE, FILE, STDIN, OTLP    |
| **Paused**        | Global pause state       | Yes, No                    |
| **AI**            | AI analysis availability | Ready, Disabled, Error     |
| **Active filter** | Current regex filter     | Shows active pattern       |
| **Update**        | Last refresh time        | Real-time update indicator |
| **Entries**       | Total log count          | Running total              |

#### Visual Cues

* **Scrollbars**: Indicate more content available
* **Selection highlighting**: Current focused item
* **Color consistency**: Same colors across all panels
* **Progress indicators**: Loading states and progress
* **Overflow indicators**: "..." when content is truncated

### Customization & Settings

#### Display Options

| Key     | Action                 | Effect                                |
| ------- | ---------------------- | ------------------------------------- |
| **c**   | Toggle columns         | Show/hide Host and Service columns    |
| **u/U** | Cycle update intervals | Adjust refresh rate (1s, 2s, 5s, 10s) |
| **r**   | Reset data             | Clear all panels and restart analysis |

#### Performance Tuning

The interface adapts to your system and log volume:

* **Buffer management**: Automatically maintains optimal memory usage
* **Update throttling**: Adjusts refresh rate based on log frequency
* **Render optimization**: Only redraws changed content
* **Memory limits**: Configurable limits prevent resource exhaustion

### Best Practices

#### 🎯 **Efficient Usage**

1. **Start with Counts panel** - Get overview before diving into details
2. **Use Word Frequency for quick insights** - Spot problems immediately
3. **Leverage color coding** - Train your eye to spot red (errors) quickly
4. **Master panel switching** - Tab through panels efficiently

#### 🔍 **Effective Analysis**

1. **Pause when needed** - Use `Space` to freeze the view for examination
2. **Filter progressively** - Start broad, then narrow down
3. **Use attributes for correlation** - Click attributes to find related logs
4. **Explore patterns** - Press Enter on Counts for deep analysis

#### ⚡ **Performance Tips**

1. **Adjust buffer sizes** - Increase for better history, decrease for performance
2. **Use appropriate update intervals** - Slower updates for high-volume logs
3. **Filter early** - Reduce processing overhead with targeted filters
4. **Monitor memory usage** - Reset data periodically for long-running sessions

### What's Next?

Now that you understand the interface, explore these guides for deeper functionality:

* **Navigation & Controls** - Master all keyboard shortcuts and mouse controls
* **Log Input Methods** - Advanced ways to feed data into Gonzo
* **Filtering & Search** - Advanced search techniques and regex patterns
* **AI Integration** - Add intelligent analysis to your workflow

***

**You now understand Gonzo's interface design!** 🚀 The 2x2 layout gives you four different perspectives on your log data, each optimized for specific analysis tasks.


# Navigation & Controls

Master Gonzo's keyboard shortcuts and mouse controls to analyze logs efficiently. This comprehensive reference covers all navigation techniques, from basic panel switching to advanced power-user workflows.

{% hint style="info" %}
**Quick Reference Needed?** Jump to the Complete Shortcut Reference at the bottom of this page.
{% endhint %}

### Navigation Philosophy

Gonzo's navigation is designed around three core principles:

1. **🎯 Efficiency** - Common actions have single-key shortcuts
2. **🔄 Consistency** - Same shortcuts work across similar contexts
3. **🖱️ Flexibility** - Both keyboard and mouse work seamlessly

The interface supports both **vim-style navigation** (hjkl) and **arrow keys**, plus **point-and-click** for users who prefer mouse interaction.

### Global Navigation

These shortcuts work from anywhere in Gonzo:

#### Essential Global Shortcuts

| Key                | Action               | Description                   | Pro Tip                         |
| ------------------ | -------------------- | ----------------------------- | ------------------------------- |
| **Tab**            | Next panel           | Move clockwise through panels | Fastest way to switch focus     |
| **Shift+Tab**      | Previous panel       | Move counter-clockwise        | Reverse direction navigation    |
| **Space**          | Global pause/unpause | Freeze entire dashboard       | Use to examine data closely     |
| **q** / **Ctrl+C** | Quit Gonzo           | Exit application              | Always works, even from modals  |
| **?** / **h**      | Show help            | Display help overlay          | Quick reference without leaving |
| **r**              | Reset all data       | Clear analysis, restart       | Fresh start with same config    |

#### Advanced Global Controls

| Key   | Action                            | Description                         | When to Use                       |
| ----- | --------------------------------- | ----------------------------------- | --------------------------------- |
| **u** | Cycle update intervals (forward)  | 1s → 2s → 5s → 10s                  | Slow down for high-volume logs    |
| **U** | Cycle update intervals (backward) | 10s → 5s → 2s → 1s                  | Speed up for real-time monitoring |
| **c** | Toggle Host/Service columns       | Show/hide extra columns in log view | Adjust for terminal width         |
| **m** | Switch AI model                   | Open model selection modal          | Change AI provider on the fly     |

{% tabs %}
{% tab title="Panel Navigation" %}
**Moving Between Panels:**

```
┌─────────────────────┬─────────────────────┐
│ 1. Log Viewer   ←──→│ 2. Word Frequency   │
│    (Tab from 4)     │    (Tab from 1)     │
│         ↑           │         ↓           │
│         │           │         │           │
│         │           │         │           │
│         ↓           │         ↑           │
├─────────────────────┼─────────────────────┤
│ 4. Counts       ←──→│ 3. Attributes       │
│    (Tab from 3)     │    (Tab from 2)     │
└─────────────────────┴─────────────────────┘
```

**Order:** Log Viewer → Word Frequency → Attributes → Counts → repeat\
**Reverse:** Use `Shift+Tab` to go backwards through this cycle
{% endtab %}

{% tab title="Mouse Navigation" %}
**Click to Focus:**

* Click anywhere in a panel to focus it immediately
* No need to Tab through panels - just click where you want to go
* Mouse wheel works in focused panels for scrolling

**Mouse + Keyboard Combo:**

* Click to focus, then use keyboard for precise navigation
* Best of both worlds for different interaction styles
  {% endtab %}
  {% endtabs %}

### Panel-Specific Navigation

Each panel has specialized navigation optimized for its content:

#### Log Viewer (Top Left)

**Basic Movement:**

| Key                | Action           | Description                               |
| ------------------ | ---------------- | ----------------------------------------- |
| **↑/↓** or **k/j** | Move up/down     | Navigate through log entries line by line |
| **Page Up/Down**   | Jump by pages    | Navigate by 10 entries at a time          |
| **Home**           | Jump to top      | Go to oldest log (stops auto-scroll)      |
| **End**            | Jump to bottom   | Go to newest log (resumes auto-scroll)    |
| **Enter**          | View log details | Open detailed modal for selected entry    |

**Smart Auto-Scroll Behavior:**

```bash
# Auto-scroll is ACTIVE when:
- You're at the bottom of the log list
- New logs appear automatically
- Status shows "Following" or "Live"

# Auto-scroll PAUSES when:
- You navigate up from the bottom
- You use Home, Page Up, or ↑ keys
- Status shows "Paused" indicator

# Auto-scroll RESUMES when:
- You press End to jump to bottom
- You scroll down to the latest entry
- You press Space to unpause globally
```

**Advanced Log Navigation:**

| Key                 | Action              | Use Case                                 |
| ------------------- | ------------------- | ---------------------------------------- |
| **Mouse Wheel**     | Scroll up/down      | Quick browsing through logs              |
| **Click log entry** | Select specific log | Jump to particular entry                 |
| **Shift+Click**     | Range selection     | Select multiple entries (future feature) |

{% hint style="success" %}
**Pro Tip:** Use `Home` to jump to the beginning of your log buffer, then `End` to return to live mode. This is perfect for comparing current issues with earlier events.
{% endhint %}

#### Word Frequency (Top Right)

| Key                | Action               | Description                       |
| ------------------ | -------------------- | --------------------------------- |
| **↑/↓** or **k/j** | Navigate word list   | Browse through frequency rankings |
| **Enter**          | Filter by word       | Apply selected word as log filter |
| **Click word**     | Quick filter         | Mouse alternative to Enter        |
| **Mouse Wheel**    | Scroll through words | Browse long frequency lists       |

**Filtering Workflow:**

1. Focus Word Frequency panel (`Tab` to navigate there)
2. Use arrows to highlight interesting word
3. Press `Enter` to filter logs containing that word
4. Press `/` and clear filter to return to all logs

#### Attributes (Bottom Left)

| Key                 | Action              | Description                           |
| ------------------- | ------------------- | ------------------------------------- |
| **↑/↓** or **k/j**  | Browse attributes   | Navigate through key-value pairs      |
| **Enter**           | Search by attribute | Filter logs containing this attribute |
| **Click attribute** | Quick search        | Mouse alternative to Enter            |
| **Mouse Wheel**     | Scroll attributes   | Browse through longer attribute lists |

**Real-time Updates:**

* Attributes panel updates based on **currently selected log** in Log Viewer
* Navigate through logs to see how attributes change
* Perfect for correlating structured data with specific log entries

#### Counts (Bottom Right)

| Key             | Action              | Description                        |
| --------------- | ------------------- | ---------------------------------- |
| **Enter**       | Open analysis modal | View detailed patterns and heatmap |
| **Click panel** | Open analysis modal | Mouse alternative to Enter         |

**Analysis Modal Navigation:**

| Key                | Action           | Description                           |
| ------------------ | ---------------- | ------------------------------------- |
| **↑/↓** or **k/j** | Scroll content   | Navigate through analysis sections    |
| **Page Up/Down**   | Jump by sections | Quick movement through large analysis |
| **Mouse Wheel**    | Scroll smoothly  | Alternative to keyboard scrolling     |
| **ESC**            | Close modal      | Return to main dashboard              |

### Filtering and Search Navigation

#### Filter Mode

| Key        | Action            | Description                                |
| ---------- | ----------------- | ------------------------------------------ |
| **/**      | Enter filter mode | Type regex patterns to filter logs         |
| **ESC**    | Exit filter mode  | Cancel filter input, return to normal mode |
| **Enter**  | Apply filter      | Activate the typed filter pattern          |
| **Ctrl+C** | Clear filter      | Remove current filter and show all logs    |

**Filter Mode Workflow:**

```bash
1. Press '/' from any panel
2. Type your regex pattern (e.g., "error", "level.*warn")
3. Press Enter to apply
4. Use normal navigation on filtered results
5. Press '/' again and clear to remove filter
```

#### Search and Highlight

| Key     | Action         | Description                             |
| ------- | -------------- | --------------------------------------- |
| **s**   | Search mode    | Find and highlight text in current view |
| **n**   | Next match     | Jump to next highlighted occurrence     |
| **N**   | Previous match | Jump to previous highlighted occurrence |
| **ESC** | Clear search   | Remove highlighting and exit search     |

**Search vs Filter:**

* **Filter (/)**: Shows only matching logs, hides others
* **Search (s)**: Highlights matches but shows all logs

### Modal Navigation

Several features open detailed modals that have their own navigation:

#### Log Details Modal

**Opened by:** Pressing `Enter` on a log entry in Log Viewer

| Key                | Action                | Description                                 |
| ------------------ | --------------------- | ------------------------------------------- |
| **↑/↓** or **k/j** | Scroll content        | Navigate through log details                |
| **Tab**            | Switch between panels | Toggle between log details and chat         |
| **i**              | AI analysis           | Get intelligent insights (if AI configured) |
| **c**              | Start AI chat         | Interactive chat about current log          |
| **m**              | Switch AI model       | Change AI model without closing modal       |
| **ESC**            | Close modal           | Return to main dashboard                    |

#### AI Analysis Modal

**Opened by:** Pressing `i` in log details or using AI features

| Key                | Action              | Description                               |
| ------------------ | ------------------- | ----------------------------------------- |
| **↑/↓** or **k/j** | Navigate analysis   | Scroll through AI insights                |
| **Tab**            | Switch sections     | Move between analysis and recommendations |
| **Enter**          | Interactive prompts | Respond to AI questions (if available)    |
| **m**              | Switch model        | Change AI model mid-analysis              |
| **ESC**            | Close analysis      | Return to previous view                   |

#### Model Selection Modal

**Opened by:** Pressing `m` anywhere in the interface

| Key                | Action           | Description                          |
| ------------------ | ---------------- | ------------------------------------ |
| **↑/↓** or **k/j** | Navigate models  | Browse available AI models           |
| **Page Up/Down**   | Jump by sections | Quick navigation through many models |
| **Enter**          | Select model     | Switch to highlighted model          |
| **ESC**            | Cancel selection | Keep current model, close modal      |
| **Mouse Wheel**    | Scroll models    | Alternative to keyboard navigation   |

### Advanced Navigation Techniques

#### Power User Workflows

{% tabs %}
{% tab title="Quick Problem Investigation" %}
**Scenario:** You notice errors in Word Frequency

```bash
1. Tab to Word Frequency panel
2. Navigate to "error" entry with ↑/↓
3. Press Enter to filter logs
4. Tab to Log Viewer to see filtered results  
5. Navigate through errors with ↑/↓
6. Press Enter on suspicious entry for details
7. Press 'i' for AI analysis if configured
```

{% endtab %}

{% tab title="Pattern Analysis Workflow" %}
**Scenario:** Investigating recurring issues

```bash
1. Tab to Counts panel
2. Press Enter to open analysis modal
3. Use ↑/↓ to browse pattern analysis
4. Note interesting patterns
5. Press ESC to close modal
6. Use '/' to filter for specific patterns
7. Tab to Log Viewer to examine instances
```

{% endtab %}

{% tab title="Multi-Source Correlation" %}
**Scenario:** Correlating events across services

```bash
1. Start with Space to pause live feed
2. Tab to Attributes panel
3. Look for trace_id or correlation_id
4. Press Enter to search by that attribute
5. Navigate through correlated logs
6. Use Home/End to see time sequence
7. Space to resume live monitoring
```

{% endtab %}
{% endtabs %}

#### Efficiency Tips

**🚀 Speed Navigation:**

* Learn the Tab cycle: Log → Words → Attributes → Counts → repeat
* Use Home/End for quick time-based navigation
* Master Space for pause/unpause during investigation

**🎯 Context Switching:**

* Click panels for instant focus switching
* Use mouse wheel + keyboard combo for best of both worlds
* Remember ESC always gets you out of modals

**🔍 Search Strategy:**

* Start broad with Word Frequency filtering
* Narrow down with regex filters (/)
* Use search (s) for highlighting without filtering
* Combine with AI analysis (i) for insights

### Customization Options

#### Update Interval Control

Adjust how often the interface refreshes:

```bash
# Real-time monitoring (default)
u → 1s updates (most responsive)

# Balanced performance  
u → 2s updates (good balance)

# Resource conservation
u → 5s updates (lighter on system)

# Slow analysis
u → 10s updates (minimal resource usage)
```

#### Display Customization

```bash
# Toggle extra columns on/off
c → Show/hide Host and Service columns

# Helpful for:
- Narrow terminals (hide columns)
- Wide terminals (show more context)
- Focus on log content vs metadata
```

### Accessibility Features

#### Visual Indicators

* **Focus highlighting** - Current panel has distinct border
* **Selection highlighting** - Current item is clearly marked
* **Color coding** - Severity levels use consistent colors
* **Progress indicators** - Loading states and scroll positions

#### Alternative Navigation

* **Mouse support** - Full click navigation for users who prefer pointing
* **Arrow key alternatives** - Both hjkl (vim) and arrow keys work
* **Multiple ways to same action** - keyboard shortcuts + mouse + menu options

### Troubleshooting Navigation Issues

#### Terminal Size Issues

```bash
# Minimum recommended: 80x24
# Optimal: 120x40 or larger

# If interface looks cramped:
- Resize terminal window
- Use 'c' to hide extra columns
- Focus on single panel analysis
```

#### Key Conflicts

```bash
# If shortcuts don't work:
- Check terminal key mappings
- Try alternative shortcuts (arrows vs hjkl)
- Use mouse navigation as backup

# Common conflicts:
- Ctrl+C (might be intercepted by terminal)
- Tab (might be intercepted by shell)
- Use mouse clicking as alternative
```

#### Performance Issues

```bash
# If navigation feels sluggish:
- Use 'u' to increase update interval (2s or 5s)
- Use 'r' to reset data and clear memory
- Filter logs early to reduce processing

# For high-volume logs:
- Pause with Space during analysis
- Use larger buffers: --log-buffer=5000
- Filter at source when possible
```

### Complete Shortcut Reference

#### Global Shortcuts

| Key                     | Action                      | Context |
| ----------------------- | --------------------------- | ------- |
| **Tab** / **Shift+Tab** | Navigate panels             | Always  |
| **Space**               | Pause/unpause dashboard     | Always  |
| **q** / **Ctrl+C**      | Quit                        | Always  |
| **/**                   | Filter mode                 | Always  |
| **s**                   | Search and highlight        | Always  |
| **r**                   | Reset data                  | Always  |
| **u** / **U**           | Cycle update intervals      | Always  |
| **c**                   | Toggle Host/Service columns | Always  |
| **m**                   | Switch AI model             | Always  |
| **?** / **h**           | Show help                   | Always  |

#### Panel Navigation

| Key                | Action             | Context       |
| ------------------ | ------------------ | ------------- |
| **↑/↓** or **k/j** | Move up/down       | Any list      |
| **Page Up/Down**   | Jump by pages      | Any list      |
| **Home** / **End** | Jump to top/bottom | Any list      |
| **Enter**          | Select/details     | Selected item |
| **Mouse Click**    | Focus/select       | Any panel     |
| **Mouse Wheel**    | Scroll             | Focused panel |

#### Modal Controls

| Key     | Action                | Context              |
| ------- | --------------------- | -------------------- |
| **ESC** | Close modal           | Any modal            |
| **Tab** | Switch modal sections | Multi-section modals |
| **i**   | AI analysis           | Log details          |
| **c**   | AI chat               | Log details          |

#### Advanced Features

| Key           | Action                     | Context       |
| ------------- | -------------------------- | ------------- |
| **n** / **N** | Next/previous search match | Search mode   |
| **Ctrl+C**    | Clear filter               | Filter active |

***

**Master these navigation techniques and you'll analyze logs with incredible efficiency!** 🚀 The key is building muscle memory for the Tab cycle and essential shortcuts like Space for pause/unpause.


# Filtering & Search

Master Gonzo's powerful filtering and search capabilities to quickly find the logs that matter. From simple text matching to advanced regex patterns, this guide covers all techniques for efficient log analysis.

{% hint style="info" %}
**Quick Start:** Press `/` to filter logs with regex patterns, or `s` to highlight text without filtering. Most users start with simple text filters and progress to regex mastery.
{% endhint %}

### Filtering vs Search Overview

Gonzo provides two complementary approaches to finding relevant logs:

| Feature                 | Key              | Behavior                               | Best For                                |
| ----------------------- | ---------------- | -------------------------------------- | --------------------------------------- |
| **🔍 Filtering**        | `/`              | Shows only matching logs, hides others | Reducing data volume, focusing analysis |
| **📍 Search**           | `s`              | Highlights matches, shows all logs     | Finding text while preserving context   |
| **🎯 Attribute Filter** | Click attributes | Filters by structured data values      | JSON/logfmt field-based analysis        |
| **📊 Word Filter**      | Click words      | Filters by frequency panel selections  | Quick filtering from common terms       |

### Basic Filtering Techniques

#### Text-Based Filtering

The simplest way to filter logs is by searching for specific text:

```bash
# Enter filter mode with '/'
# Then type any of these patterns:

error           # Show logs containing "error"
database        # Show logs containing "database"  
timeout         # Show logs containing "timeout"
user_id         # Show logs containing "user_id"
```

**Workflow:**

1. Press `/` from any panel
2. Type your search term
3. Press `Enter` to apply filter
4. Navigate filtered results with normal keys
5. Press `/` again and clear to remove filter

#### Case Sensitivity

```bash
# Case-insensitive by default
error           # Matches: error, Error, ERROR, eRrOr

# Force case-sensitive with regex
(?-i)Error      # Matches only: Error (not error or ERROR)

# Mixed case patterns
[Ee]rror        # Matches: Error or error (but not ERROR)
```

#### Multiple Term Filtering

```bash
# AND logic - both terms must appear
error.*database     # Logs containing both "error" AND "database"
user.*login.*fail   # Logs with "user" AND "login" AND "fail"

# OR logic - either term can appear  
(error|warning)     # Logs containing "error" OR "warning"
(timeout|slow|lag)  # Performance-related terms
```

### Regular Expression Filtering

Gonzo supports full regex patterns for powerful filtering:

#### Basic Regex Patterns

```bash
# Exact word boundaries
\berror\b          # "error" as complete word (not "errors")
\btimeout\b        # "timeout" but not "timeouts"

# Start/end of line
^ERROR             # Lines starting with "ERROR"
failed$            # Lines ending with "failed"

# Any character wildcards
user.id            # "user_id", "user-id", "userid", etc.
data.*base         # "database", "data_base", "data-base", etc.
```

#### Advanced Regex Techniques

{% tabs %}
{% tab title="Log Level Patterns" %}

```bash
# Specific log levels
level.*error       # JSON: "level":"error"
level.*warn        # JSON: "level":"warn"
\[(ERROR|WARN)\]   # Plain text: [ERROR] or [WARN]

# Multiple severity levels
level.*(error|warn|fatal)     # Multiple JSON levels
\[(ERROR|WARN|FATAL)\]        # Multiple plain text levels

# Exclude debug logs
^(?!.*DEBUG).*     # Everything except DEBUG logs
level.*(?!debug)   # JSON levels except debug
```

{% endtab %}

{% tab title="Service & Component" %}

```bash
# Specific services
service.*api       # JSON: "service":"api"
service.*(web|api) # Multiple services

# Component patterns
component.*auth    # Authentication component
module.*payment    # Payment module

# Microservice patterns
(user-service|payment-service|auth-service)
```

{% endtab %}

{% tab title="Time & Date Patterns" %}

```bash
# Specific dates
2024-01-15         # January 15, 2024
2024-01-1[5-9]     # January 15-19, 2024

# Time ranges
(10|11|12):[0-5][0-9]    # 10 AM to 12:59 PM
1[0-2]:[0-5][0-9]        # 10 AM to 12:59 PM

# Recent timestamps (last hour)
$(date +%Y-%m-%d\ %H)    # Current hour (requires shell)
```

{% endtab %}

{% tab title="Error & Exception Patterns" %}

```bash
# Exception types
(Exception|Error|Fault)$     # Lines ending with exception types
NullPointer.*Exception       # Specific exception types
timeout.*exception           # Timeout-related exceptions

# HTTP status codes
status.*[45][0-9]{2}         # 4xx and 5xx HTTP status codes
"status":\s*[45][0-9]{2}     # JSON HTTP error statuses

# Database errors
(connection.*refused|deadlock|constraint)
```

{% endtab %}
{% endtabs %}

#### Performance-Oriented Regex

```bash
# Efficient patterns (fast)
^ERROR             # Anchored to start
\berror\b          # Word boundaries
(error|warn)       # Simple alternation

# Avoid these patterns (slow on large datasets)
.*error.*          # Unnecessary .* at start
(.*error.*|.*warn.*) # Complex nested patterns
error.*database.*timeout  # Too many .* wildcards
```

### Structured Data Filtering

For JSON and logfmt logs, leverage structured field filtering:

#### JSON Log Filtering

```bash
# Field-specific filtering
"level":"error"              # Exact JSON field match
"user_id":"12345"            # Specific user
"status":50[0-9]             # 500-509 status codes
"duration":[1-9][0-9]+       # Duration > 10

# Nested field filtering
"request".*"method":"POST"   # Nested object fields
"metadata".*"trace_id"       # Nested trace information

# Array and complex structures
"tags".*"production"         # Array containing "production"
"errors".*\[.*\]             # Non-empty error arrays
```

#### Logfmt Filtering

```bash
# Key-value pattern filtering
level=error                  # Exact logfmt match
user_id=12345               # Specific user ID
method=(POST|PUT|DELETE)    # HTTP methods
duration=[1-9][0-9]+        # Numeric values

# Combined logfmt patterns
level=error.*user_id=       # Error logs with user context
method=POST.*status=4[0-9]{2} # POST requests with 4xx errors
```

#### Attribute-Based Filtering

Use the Attributes panel for point-and-click filtering:

1. **Navigate to Attributes panel** (bottom-left)
2. **Click any attribute name or value**
3. **Gonzo automatically creates filter** for that attribute
4. **Refine with additional patterns** if needed

**Example Workflow:**

```bash
# 1. See "trace_id": "abc123" in Attributes panel
# 2. Click "abc123"
# 3. Filter automatically becomes: trace_id.*abc123
# 4. All logs with that trace ID are shown
```

### Search and Highlighting

Use search mode to find text while preserving full context:

#### Basic Search Operations

```bash
# Enter search mode
s                 # Press 's' to start search

# Type search term
error            # Highlights all instances of "error"

# Navigate matches
n                # Jump to next match
N                # Jump to previous match

# Clear search
ESC              # Remove highlighting and exit search
```

#### Advanced Search Patterns

```bash
# Search supports regex too
timeout.*second   # Highlight timeout patterns
user.*[0-9]+     # Highlight user IDs
\b[A-Z]{3,}\b    # Highlight all-caps words (like HTTP, API, SQL)
```

#### Search vs Filter Decision Guide

| Use Search When                    | Use Filter When                     |
| ---------------------------------- | ----------------------------------- |
| Want to see context around matches | Want to focus only on relevant logs |
| Investigating pattern frequency    | Reducing data volume                |
| Understanding log flow             | Debugging specific issues           |
| Learning about log structure       | Performance analysis                |

### Interactive Filtering Workflows

#### Word Frequency Panel Filtering

Leverage the Word Frequency panel for quick filtering:

1. **Focus Word Frequency panel** (Tab to top-right)
2. **Navigate to interesting word** (↑/↓ arrows)
3. **Press Enter** to filter by that word
4. **Examine filtered results** in Log Viewer
5. **Clear filter** (press `/` and clear) to see all logs again

**Power User Tip:**

```bash
# Quick workflow for problem investigation:
1. Tab to Word Frequency
2. Look for "error", "fail", "timeout" near top
3. Enter on highest frequency problem word
4. Tab to Log Viewer to see filtered results
5. Enter on specific log for details
```

#### Multi-Step Filtering

Build complex filters progressively:

```bash
# Step 1: Start broad
level.*error

# Step 2: Add service context  
level.*error.*service.*api

# Step 3: Add time context
level.*error.*service.*api.*2024-01-15

# Step 4: Add specific component
level.*error.*service.*api.*2024-01-15.*auth
```

#### Filter Refinement Techniques

```bash
# Start with common terms, then refine
database                    # Too broad - 1000 results
database.*error            # Better - 50 results  
database.*connection.*error # Specific - 5 results

# Use exclusion to remove noise
error.*(?!debug)           # Errors but not debug errors
timeout.*(?!test)          # Timeouts but not test timeouts
```

### Severity-Based Filtering

Quickly focus on specific log levels using both regex patterns and the interactive severity filter modal:

#### Severity Filter Modal (Ctrl+F)

The fastest way to filter by log level is using the severity filter modal:

**Quick Access:** Press `Ctrl+F` from anywhere in Gonzo

**Features:**

* Visual selection of severity levels
* Real-time count of logs at each level
* Color-coded severity display
* Quick select all/none options
* Combines with other active filters

**Workflow:**

```bash
# 1. Open severity filter
Press Ctrl+F

# 2. Quick clear all (optional)
Navigate to "Select None" → Press Enter (applies and closes instantly)

# 3. Select desired levels
Press Ctrl+F to reopen
Navigate to "ERROR" → Press Space (toggles checkbox)
Navigate to "FATAL" → Press Space (toggles checkbox)

# 4. Apply filter
Press Enter

# Result: Only ERROR and FATAL logs are displayed
```

**Interactive Features:**

| Action                            | Result                                         |
| --------------------------------- | ---------------------------------------------- |
| Navigate to "Select All" + Enter  | Show all severity levels (applies immediately) |
| Navigate to "Select None" + Enter | Hide all levels (applies immediately)          |
| Space on individual level         | Toggle that specific level                     |
| Enter (after changes)             | Apply selections and close                     |
| ESC                               | Cancel changes and close                       |

**Combining with Other Filters:**

```bash
# Show only database-related errors:
1. Press / → Type "database" → Enter (regex filter)
2. Press Ctrl+F → Select only "ERROR" → Enter (severity filter)
# Both filters are active simultaneously
```

#### Standard Severity Patterns

```bash
# JSON log levels
level.*error         # Error level only
level.*(error|warn)  # Error and warning levels
level.*info          # Info level only

# Plain text log levels
\[ERROR\]           # [ERROR] markers
\[(ERROR|WARN)\]    # Multiple levels with brackets
(ERROR|WARN|FATAL): # Colon-separated levels
```

#### Custom Severity Systems

```bash
# Priority-based systems
priority.*high           # High priority logs
priority.*(high|critical) # High and critical

# Numeric severity
severity.*[89]           # Severity 8 or 9
severity.*1[0-9]         # Severity 10+

# Custom level names
(CRITICAL|ALERT|EMERGENCY)  # Custom high-severity terms
```

### Performance Filtering

Find performance-related issues efficiently:

#### Response Time Analysis

```bash
# Slow requests
duration.*[5-9][0-9]{3}     # Duration > 5000ms
response_time.*[1-9][0-9]+s # Response time > 10s
elapsed.*[1-9][0-9]+        # Elapsed time patterns

# Timeout patterns
timeout                     # Any timeout mentions
.*timeout.*[0-9]+          # Timeouts with specific durations
connection.*timeout        # Connection timeouts specifically
```

#### Resource Usage Filtering

```bash
# Memory issues
(memory|mem).*high          # Memory alerts
out.*of.*memory            # OOM errors
heap.*size.*exceeded       # Heap exhaustion

# CPU issues
cpu.*high                  # CPU alerts
load.*average.*[5-9]       # High load averages
processing.*slow           # Slow processing alerts
```

### Security-Focused Filtering

Identify security-related events:

#### Authentication Filtering

```bash
# Login failures
(login|auth).*fail         # Authentication failures
invalid.*credential        # Credential issues
access.*denied            # Access control issues

# Suspicious activity
brute.*force              # Brute force attempts
rate.*limit.*exceeded     # Rate limiting triggers
suspicious.*activity      # General suspicious events
```

#### Network Security Filtering

```bash
# Network issues
(firewall|iptables).*block    # Firewall blocks
connection.*refused          # Connection rejections
unauthorized.*access         # Unauthorized access attempts

# Attack patterns
(sql.*injection|xss|csrf)    # Common attack types
malicious.*request          # Malicious activity
```

### Filter Management

#### Clearing and Modifying Filters

```bash
# Clear current filter
/                   # Enter filter mode
                   # Delete all text
Enter              # Apply empty filter (shows all logs)

# Modify existing filter
/                  # Enter filter mode
                  # Edit existing pattern
Enter             # Apply modified filter

# Quick clear
Ctrl+C            # Clear filter immediately (context-dependent)
```

#### Filter History and Patterns

**Common Filter Patterns to Remember:**

```bash
# Error investigation starter pack
level.*error
(error|fail|exception)
timeout.*[0-9]+
status.*[45][0-9]{2}

# Performance investigation
(slow|timeout|high|exceed)
duration.*[5-9][0-9]{3}
response.*time.*[1-9][0-9]+

# Security investigation  
(auth|login|access).*fail
(block|deny|refuse)
rate.*limit
```

### Advanced Filter Techniques

#### Lookahead and Lookbehind

```bash
# Positive lookahead
error(?=.*database)        # "error" followed by "database"
user(?=.*login)           # "user" in login context

# Negative lookahead  
error(?!.*test)           # "error" not followed by "test"
timeout(?!.*retry)        # "timeout" without retry

# Positive lookbehind
(?<=POST\s).*error        # "error" preceded by "POST"
(?<=user\s).*fail         # "fail" after "user"
```

#### Context-Aware Filtering

```bash
# Same-line requirements
user.*login.*success      # All three on same line
error.*code.*[0-9]+      # Error with numeric code

# Multi-line context (limited support)
error.*\n.*stacktrace    # Error followed by stacktrace
exception.*\n.*at.*line  # Exception with line reference
```

### Filter Performance Optimization

#### Efficient Filter Design

```bash
# Fast filters (use these patterns)
^ERROR                    # Anchored to start
\berror\b                # Word boundaries
level.*error             # Structured field matching

# Slow filters (avoid when possible)
.*error.*               # Unanchored wildcards
(.*user.*|.*admin.*)    # Complex alternation
error.*user.*login.*fail # Too many wildcards
```

#### Large Dataset Strategies

```bash
# Pre-filter at source when possible
tail -f /var/log/app.log | grep ERROR | gonzo

# Use progressive filtering
# Start: error
# Refine: error.*database  
# Specific: error.*database.*connection

# Combine with buffer adjustments
gonzo -f large.log --log-buffer=10000  # More history
gonzo -f busy.log --log-buffer=1000    # Less memory
```

### Troubleshooting Filters

#### Common Filter Problems

**Filter not working:**

```bash
# Check regex syntax
# Test patterns: https://regex101.com
# Use simple text first: error
# Then add complexity: level.*error
```

**Too many/few results:**

```bash
# Too many results - add specificity
error                     # Too broad
error.*database          # Better
error.*database.*timeout # Specific

# Too few results - remove constraints
level.*error.*database.*connection.*timeout  # Too specific
level.*error.*database                      # Broader
level.*error                               # Even broader
```

**Performance issues:**

```bash
# Simplify complex patterns
(.*error.*|.*warn.*|.*fail.*)  # Complex
(error|warn|fail)              # Simple

# Avoid nested wildcards
error.*database.*timeout.*connection  # Slow
error.*connection                     # Faster
```

#### Filter Testing Strategies

```bash
# Test filters progressively
1. Start with simple text: "error"
2. Add structure: "level.*error"  
3. Add context: "level.*error.*database"
4. Refine specificity: "level.*error.*database.*timeout"

# Validate with known logs
# Find a specific log entry you can see
# Create filter that should match it
# Verify it appears in results
```

### Filter Best Practices

#### 🎯 **Effective Filter Strategies**

1. **Start broad, narrow down** - Begin with simple terms, add specificity
2. **Use structured fields** - Leverage JSON/logfmt field names
3. **Combine with search** - Filter to reduce, search to highlight
4. **Save common patterns** - Remember frequently used regex patterns

#### 🔍 **Investigation Workflows**

1. **Problem identification** - Use Word Frequency panel to spot issues
2. **Initial filtering** - Filter by problem type (error, timeout, etc.)
3. **Context gathering** - Search for related terms while preserving context
4. **Deep dive** - Progressive filtering to isolate specific issues

#### ⚡ **Performance Tips**

1. **Anchor patterns** - Use ^ and $ when possible
2. **Word boundaries** - Use \b for exact word matches
3. **Avoid excessive wildcards** - Minimize .\* usage
4. **Pre-filter when possible** - Filter at source before Gonzo

### What's Next?

Now that you've mastered filtering and search, explore these advanced topics:

* **Detailed Usage Guide** - Real-world patterns and power-user workflows
* **AI Integration** - Let AI help identify patterns
* **Log Analysis** - Advanced pattern detection techniques
* **Configuration** - Save filter patterns and preferences

***

**You now have complete mastery over finding relevant information in your logs!** 🚀 From simple text filtering to complex regex patterns, you can quickly isolate the logs that matter for any investigation.


# Detailed Usage Guide

Master advanced Gonzo workflows, real-world scenarios, and power-user techniques. This comprehensive guide covers everything from complex multi-source analysis to performance optimization and troubleshooting strategies.

{% hint style="success" %}
**Prerequisites:** Complete the other User Guide sections first - this builds on Interface Overview, Navigation & Controls, Log Input Methods, and Filtering & Search.
{% endhint %}

### Advanced Analysis Workflows

#### Multi-Service Investigation

Analyze logs from multiple services to understand system-wide issues:

{% tabs %}
{% tab title="Microservices Debugging" %}
**Scenario:** API gateway timeouts affecting user experience

```bash
# 1. Start with all related services
gonzo -f api-gateway.log -f user-service.log -f auth-service.log --follow

# 2. Filter for error timeframe
/2024-01-15.*1[0-2]:[0-5][0-9]  # Focus on specific time window

# 3. Look for correlation patterns
# Tab to Word Frequency - look for "timeout", "503", "error"

# 4. Progressive filtering
/timeout.*[0-9]+     # Find timeout events
/trace_id.*abc123    # Follow specific request trace

# 5. Cross-service correlation
# Use Attributes panel to click trace_id values
# Follow the request path across services
```

**Key Techniques:**

* Start broad with all services, narrow by time and error type
* Use trace IDs or correlation IDs to follow requests
* Compare Word Frequency across different time periods
* Leverage Attributes panel for structured data correlation
  {% endtab %}

{% tab title="Infrastructure Problem Analysis" %}
**Scenario:** Database slowdown impacting multiple applications

```bash
# 1. Monitor infrastructure and applications
gonzo -f /var/log/postgresql/postgresql.log \
      -f /var/log/nginx/access.log \
      -f /var/log/app/*.log --follow

# 2. Look for performance indicators
/(slow|timeout|high|lag|delay)

# 3. Correlate timing patterns
# Press Enter on Counts panel for time-series analysis
# Look for spikes in error frequency

# 4. Identify root cause service
# Filter by service: service.*database
# Look for connection pool exhaustion, slow queries

# 5. Impact assessment
# Remove database filter, look for cascade effects
/(503|timeout|unavailable)
```

**Analysis Strategy:**

* Monitor both infrastructure and application layers
* Use time-series analysis in Counts modal
* Identify the root cause service first
* Assess cascade effects on dependent services
  {% endtab %}
  {% endtabs %}

#### Performance Analysis Workflows

**Response Time Investigation**

```bash
# 1. Identify slow operations
gonzo -f app.log --follow
/duration.*[5-9][0-9]{3}   # Duration > 5000ms

# 2. Categorize slow operations  
# Tab to Attributes panel, look for:
# - endpoint patterns
# - user_id patterns  
# - method types
# - database query patterns

# 3. Pattern analysis
# Press Enter on Counts panel
# Look for:
# - Time correlation (when do slowdowns occur?)
# - Pattern frequency (which operations are consistently slow?)
# - Service distribution (which services are affected?)

# 4. Deep dive investigation
/endpoint.*\/api\/users.*duration.*[5-9][0-9]{3}
# Focus on specific slow endpoints

# 5. AI-powered insights (if configured)
# Press 'i' in log details for AI analysis
# Ask: "Why are these operations slow?"
```

**Resource Utilization Analysis**

```bash
# Monitor resource-related logs
gonzo -f app.log -f /var/log/syslog --follow

# Filter for resource indicators
/(memory|cpu|disk|network).*high
/(out.*of.*memory|heap.*exceeded|disk.*full)

# Correlate with application performance
# Look for patterns like:
# - Memory pressure -> GC pauses -> slow responses
# - CPU spikes -> request queueing -> timeouts
# - Disk I/O -> database slowdown -> cascade failures

# Use time-series analysis
# Press Enter on Counts panel
# Look for resource usage spikes correlating with error spikes
```

#### Security Monitoring Workflows

**Authentication Analysis**

```bash
# Monitor authentication-related logs
sudo gonzo -f /var/log/auth.log -f /var/log/app/auth.log --follow

# Look for suspicious patterns
/(fail|invalid|denied|brute.*force)

# Analyze attack patterns
# Tab to Word Frequency - look for:
# - High frequency of specific usernames
# - Repeated IP addresses
# - Unusual user agents

# Geographic analysis (if available)
/country.*CN.*fail   # Failed logins from specific countries
/ip.*192\.168       # Internal vs external attempts

# Time-based analysis
# Press Enter on Counts panel
# Look for attack timing patterns
# - Off-hours activity
# - Burst patterns suggesting automation
```

**Access Control Investigation**

```bash
# Monitor access control events
gonzo -f /var/log/nginx/access.log -f app.log --follow

# Filter for access violations
/status.*(403|401|405)
/(unauthorized|forbidden|access.*denied)

# Analyze access patterns
# Look for:
# - Unusual endpoint access attempts
# - Privilege escalation attempts
# - Data exfiltration patterns

# Use structured filtering
/method.*POST.*status.*403   # POST attempts that failed
/endpoint.*admin.*status.*401 # Admin access attempts
```

### Advanced Configuration Strategies

#### Environment-Specific Configurations

**Development Environment Setup**

```bash
# Create ~/.config/gonzo/dev-config.yml
files:
  - "logs/*.log"
  - "debug/*.log"
follow: true
update-interval: 1s
log-buffer: 2000
ai-model: "gpt-3.5-turbo"  # Faster model for dev

# Usage
gonzo --config ~/.config/gonzo/dev-config.yml
```

**Production Monitoring Setup**

```bash
# Create ~/.config/gonzo/prod-config.yml  
files:
  - "/var/log/app/*.log"
  - "/var/log/nginx/*.log"
follow: true
update-interval: 5s       # Less frequent updates
log-buffer: 10000        # Larger buffer for high volume
memory-size: 50000       # More memory for complex analysis
ai-model: "gpt-4"        # More capable model for critical analysis

# Usage with additional monitoring
gonzo --config ~/.config/gonzo/prod-config.yml \
      -f /var/log/security.log
```

**CI/CD Integration Setup**

```bash
# Create build-analysis.sh
#!/bin/bash
# Analyze build logs with Gonzo

if [ $# -eq 0 ]; then
    echo "Usage: $0 <build-log-file>"
    exit 1
fi

export GONZO_LOG_BUFFER=5000
export GONZO_UPDATE_INTERVAL=2s

gonzo -f "$1" \
      --ai-model="gpt-3.5-turbo" \
      --log-buffer=5000

# Integration with CI
# - Run after failed builds
# - Pipe build output directly: build-command | gonzo
# - Generate failure reports with AI analysis
```

#### Performance Optimization Strategies

**High-Volume Log Handling**

```bash
# For logs with >1000 entries/second
gonzo -f high-volume.log \
      --follow \
      --log-buffer=20000 \
      --memory-size=100000 \
      --update-interval=10s

# Pre-filtering for performance
tail -f /var/log/high-volume.log | grep -E "(ERROR|WARN)" | gonzo

# Distributed analysis approach
# Terminal 1: Current errors
tail -f /var/log/app.log | grep ERROR | gonzo

# Terminal 2: Historical analysis  
gonzo -f /var/log/app.log.1

# Terminal 3: Performance monitoring
tail -f /var/log/app.log | grep -E "(slow|timeout|duration.*[5-9])" | gonzo
```

**Memory-Constrained Environments**

```bash
# Minimal memory configuration
gonzo -f app.log \
      --log-buffer=500 \
      --memory-size=2000 \
      --update-interval=5s

# Streaming analysis (minimal buffering)
tail -f /var/log/app.log | gonzo --log-buffer=100

# Batch processing approach
# Process logs in chunks
split -l 10000 huge.log chunk_
for chunk in chunk_*; do
    echo "Analyzing $chunk..."
    gonzo -f "$chunk"
    read -p "Press enter for next chunk..."
done
```

### Real-World Scenarios

#### Incident Response Workflows

**Production Outage Investigation**

```bash
# Step 1: Rapid triage
gonzo -f /var/log/app/*.log -f /var/log/nginx/*.log --follow

# Step 2: Focus on errors during outage timeframe  
/2024-01-15.*09:[1-3][0-9]   # 9:10-9:39 AM timeframe

# Step 3: Identify error categories
# Tab to Word Frequency
# Look for spike in: "500", "timeout", "connection", "database"

# Step 4: Follow the cascade
/(connection.*refused|timeout|circuit.*breaker)

# Step 5: Find root cause
# Press Enter on Counts panel
# Look at time-series heatmap
# Identify when errors started vs when they peaked

# Step 6: AI-assisted analysis
# Press 'i' on critical error logs
# Ask: "What caused this outage?"

# Step 7: Document timeline
# Use Home/End to build timeline of events
# Note: First error at 09:12, peak at 09:15, resolution at 09:35
```

**Performance Degradation Investigation**

```bash
# Monitor performance indicators
gonzo -f app.log --follow
/(duration|response.*time|elapsed).*[5-9][0-9]{3}

# Correlate with resource usage
gonzo -f app.log -f /var/log/syslog --follow
/(memory|cpu|load).*high

# Identify affected operations
# Use Attributes panel to group by:
# - endpoint
# - user_id  
# - operation_type

# Pattern analysis workflow:
# 1. Filter by slow operations
# 2. Press Enter on Counts for pattern analysis
# 3. Look for common attributes in slow requests
# 4. Correlate with infrastructure metrics
# 5. Identify optimization opportunities
```

#### Development Workflows

**Debugging Application Issues**

```bash
# Development debugging session
gonzo -f logs/app.log -f logs/debug.log --follow

# Focus on current development
/user_id.*12345   # Your test user

# Feature-specific debugging
/feature.*new_checkout.*error

# Exception tracing
/exception.*NullPointer
# Press Enter on specific exception
# Use 'i' for AI analysis: "Explain this exception"

# Performance profiling
/profile.*slow.*query
/(query|sql).*[1-9][0-9]{3}ms   # Queries > 1000ms
```

**Integration Testing Analysis**

```bash
# Monitor integration test logs
gonzo -f test-results.log --follow

# Filter test failures
/(FAIL|ERROR|Assert.*fail)

# API integration analysis
/http.*[45][0-9]{2}   # HTTP 4xx/5xx responses

# Database integration issues
/(connection.*fail|query.*timeout|constraint.*violation)

# Use AI for test failure analysis
# Press 'i' on failed test logs
# Ask: "Why did this integration test fail?"
```

### Advanced Integration Patterns

#### Container Orchestration

**Kubernetes Advanced Monitoring**

```bash
# Multi-namespace monitoring
kubectl logs -f -l app=backend --all-namespaces | gonzo

# Pod lifecycle analysis
kubectl get events --watch | grep -E "(Warning|Error)" | gonzo

# Resource constraint investigation
kubectl top pods --containers | gonzo

# Custom resource monitoring
kubectl logs -f -l tier=database | grep -E "(slow|timeout|error)" | gonzo

# Helm release monitoring
helm status myapp --output json | jq '.info.notes' | gonzo
```

**Docker Swarm Integration**

```bash
# Service log aggregation
docker service logs -f $(docker service ls -q) | gonzo

# Node-specific analysis
docker node ls --format "table {{.ID}}\t{{.Hostname}}\t{{.Status}}"
docker logs -f $(docker ps -q --filter node=worker1) | gonzo

# Stack monitoring
docker stack ps mystack --format "table {{.Name}}\t{{.Image}}\t{{.CurrentState}}"
docker service logs -f mystack_web | gonzo
```

#### Cloud Platform Integration

**AWS CloudWatch Integration Pattern**

```bash
# CloudWatch Logs streaming (requires aws-cli)
aws logs tail /aws/lambda/my-function --follow | gonzo

# ECS task monitoring
aws ecs describe-tasks --cluster my-cluster --tasks $(aws ecs list-tasks --cluster my-cluster --query 'taskArns[]' --output text) | gonzo

# Application Load Balancer logs
aws s3 cp s3://my-alb-logs/ . --recursive
gunzip -c *.gz | gonzo
```

**Azure Monitor Integration**

```bash
# Azure Log Analytics streaming
az monitor log-analytics query --workspace "my-workspace" \
  --analytics-query "AppTraces | where TimeGenerated > ago(1h)" \
  --output tsv | gonzo

# Container Instances monitoring  
az container logs --resource-group mygroup --name mycontainer --follow | gonzo
```

**Google Cloud Logging**

```bash
# Cloud Logging streaming
gcloud logging tail "resource.type=cloud_function" --format="value(textPayload)" | gonzo

# GKE cluster monitoring
gcloud container clusters get-credentials my-cluster
kubectl logs -f deployment/my-app | gonzo
```

### Power User Techniques

#### Multi-Terminal Analysis

**Distributed Investigation Setup**

```bash
# Terminal 1: Real-time error monitoring
gonzo -f /var/log/app.log --follow | grep ERROR | gonzo

# Terminal 2: Performance monitoring  
gonzo -f /var/log/app.log --follow | grep -E "(slow|timeout|duration.*[5-9])" | gonzo

# Terminal 3: Security monitoring
sudo gonzo -f /var/log/auth.log --follow

# Terminal 4: Infrastructure monitoring
gonzo -f /var/log/syslog --follow | grep -E "(error|warning|critical)" | gonzo
```

**Comparative Analysis**

```bash
# Compare current vs previous period
# Terminal 1: Current hour
tail -f /var/log/app.log | grep "$(date +%H):" | gonzo

# Terminal 2: Previous hour  
grep "$(date -d '1 hour ago' +%H):" /var/log/app.log | gonzo

# Terminal 3: Same time yesterday
grep "$(date -d '1 day ago' +%Y-%m-%d)" /var/log/app.log.1 | gonzo
```

#### Automation and Scripting

**Automated Monitoring Scripts**

```bash
#!/bin/bash
# smart-monitor.sh - Intelligent log monitoring

LOG_FILE="/var/log/app.log"
ERROR_THRESHOLD=10
ALERT_EMAIL="admin@company.com"

# Function to check error rate
check_error_rate() {
    local error_count=$(tail -n 100 "$LOG_FILE" | grep -c ERROR)
    if [ "$error_count" -gt "$ERROR_THRESHOLD" ]; then
        echo "High error rate detected: $error_count errors in last 100 lines"
        # Launch Gonzo with error focus
        tail -f "$LOG_FILE" | grep ERROR | gonzo --ai-model="gpt-4" &
        
        # Send alert
        echo "High error rate: $error_count errors" | mail -s "Alert: High Error Rate" "$ALERT_EMAIL"
    fi
}

# Continuous monitoring
while true; do
    check_error_rate
    sleep 300  # Check every 5 minutes
done
```

**Performance Analysis Automation**

```bash
#!/bin/bash  
# performance-analyzer.sh

analyze_performance() {
    local log_file="$1"
    local output_file="/tmp/perf-analysis-$(date +%Y%m%d-%H%M%S).txt"
    
    echo "Performance Analysis Report" > "$output_file"
    echo "Generated: $(date)" >> "$output_file"
    echo "=========================" >> "$output_file"
    
    # Extract slow operations
    grep -E "duration.*[5-9][0-9]{3}" "$log_file" | \
        gonzo --test-mode > /tmp/gonzo-perf.out
    
    # Summary statistics
    echo "Slow Operations Summary:" >> "$output_file"
    grep -c "duration.*[5-9][0-9]{3}" "$log_file" >> "$output_file"
    
    # Top slow endpoints
    echo "Top Slow Endpoints:" >> "$output_file"
    grep -oE "endpoint.*[\"'][^\"']*[\"'].*duration.*[5-9][0-9]{3}" "$log_file" | \
        sort | uniq -c | sort -nr | head -10 >> "$output_file"
    
    echo "Analysis saved to: $output_file"
}

# Usage: ./performance-analyzer.sh /var/log/app.log
analyze_performance "$1"
```

#### AI-Enhanced Analysis Workflows

**Intelligent Problem Detection**

```bash
# Set up AI-enhanced monitoring
export OPENAI_API_KEY="your-key-here"
gonzo -f /var/log/app.log --follow --ai-model="gpt-4"

# AI-guided investigation workflow:
# 1. Let Gonzo run for 10-15 minutes to collect data
# 2. Press Enter on Counts panel for pattern analysis
# 3. Identify suspicious patterns in the heatmap
# 4. Filter for specific pattern: /pattern.*from.*analysis
# 5. Press 'i' on representative log entry
# 6. Ask AI: "Is this a serious issue? What should I investigate?"
# 7. Follow AI recommendations for deeper analysis
```

**Automated Incident Analysis**

```bash
#!/bin/bash
# ai-incident-analyzer.sh

analyze_incident() {
    local start_time="$1"
    local end_time="$2"
    local log_file="$3"
    
    # Extract incident timeframe
    sed -n "/$start_time/,/$end_time/p" "$log_file" > /tmp/incident-logs.txt
    
    # Analyze with Gonzo + AI
    echo "Analyzing incident from $start_time to $end_time..."
    gonzo -f /tmp/incident-logs.txt --ai-model="gpt-4" &
    
    sleep 30  # Let analysis run
    
    # Generate AI report
    echo "Incident Analysis Report" > /tmp/incident-report.txt
    echo "Timeframe: $start_time to $end_time" >> /tmp/incident-report.txt
    
    # Add manual AI queries here based on your findings
    echo "Review the Gonzo analysis and use 'i' key for AI insights"
}

# Usage: ./ai-incident-analyzer.sh "2024-01-15 09:10" "2024-01-15 09:40" /var/log/app.log
analyze_incident "$1" "$2" "$3"
```

### Troubleshooting Advanced Scenarios

#### Performance Issues

**High CPU Usage**

```bash
# Symptoms: Gonzo consuming high CPU
# Solutions:

# 1. Reduce update frequency
gonzo -f high-volume.log --follow --update-interval=10s

# 2. Increase buffer size (fewer refreshes)
gonzo -f busy.log --follow --log-buffer=10000

# 3. Pre-filter data
tail -f /var/log/busy.log | grep -E "(ERROR|WARN)" | gonzo

# 4. Use simpler regex patterns
# Instead of: .*error.*database.*timeout.*
# Use: error.*database
```

**Memory Issues**

```bash
# Symptoms: Gonzo using too much memory
# Solutions:

# 1. Reduce memory size
gonzo -f app.log --memory-size=5000

# 2. Reduce log buffer
gonzo -f app.log --log-buffer=1000

# 3. Reset data periodically
# Press 'r' to reset data when memory usage gets high

# 4. Process logs in batches
split -l 5000 huge.log batch_
for batch in batch_*; do
    gonzo -f "$batch"
done
```

#### Complex Log Format Issues

**Mixed Format Handling**

```bash
# When logs contain multiple formats:
# JSON + plain text + logfmt

# Gonzo handles this automatically, but for optimization:

# 1. Separate by format if possible
grep "^{" mixed.log | gonzo   # JSON lines only
grep -v "^{" mixed.log | gonzo # Non-JSON lines

# 2. Use format-specific filtering
/"level":"error"              # JSON format
/level=error                  # Logfmt format
/\[ERROR\]                   # Plain text format
```

**Custom Timestamp Formats**

```bash
# For unusual timestamp formats
# Gonzo auto-detects most formats, but for custom formats:

# Use filtering to normalize timestamps
sed 's/CustomTimestamp:\([0-9-]*\)/\1/' custom.log | gonzo

# Or filter by custom timestamp patterns
/CustomTimestamp:.*2024-01-15
```

#### Integration Troubleshooting

**OTLP Connection Issues**

```bash
# Debug OTLP connection problems

# 1. Verify Gonzo is listening
netstat -ln | grep 4317
lsof -i :4317

# 2. Test with curl
curl -X POST http://localhost:4318/v1/logs \
  -H "Content-Type: application/json" \
  -d '{"logs": []}'

# 3. Check firewall settings
sudo ufw status | grep 4317

# 4. Verify OpenTelemetry configuration
# Check collector config for correct endpoints
```

**Container Integration Issues**

```bash
# Docker logs not appearing

# 1. Verify container is running
docker ps | grep my-container

# 2. Check log driver
docker inspect my-container | grep LogDriver

# 3. Test manual log access
docker logs my-container | head -10

# 4. Verify piping works
docker logs -f my-container 2>&1 | cat

# Kubernetes logs not appearing

# 1. Verify pod status
kubectl get pods -l app=my-app

# 2. Check RBAC permissions
kubectl auth can-i get pods --as=system:serviceaccount:default:default

# 3. Test manual access
kubectl logs pod/my-app | head -10
```

### Best Practices Summary

#### 🎯 **Investigation Methodology**

1. **Start broad, narrow progressively** - Begin with all relevant logs, filter by time, then by issue type
2. **Use structured data** - Leverage Attributes panel for correlation
3. **Combine multiple panels** - Word Frequency for discovery, Counts for patterns, Log Viewer for details
4. **Document timeline** - Use Home/End navigation to build incident timelines

#### ⚡ **Performance Optimization**

1. **Right-size buffers** - Balance memory usage with analysis depth
2. **Filter early** - Pre-filter at source when possible
3. **Use appropriate update intervals** - Slower for high-volume, faster for real-time
4. **Reset periodically** - Use 'r' to clear memory in long sessions

#### 🔧 **Configuration Management**

1. **Environment-specific configs** - Different settings for dev vs prod
2. **Save common patterns** - Document frequently used regex filters
3. **Automate repetitive tasks** - Create scripts for common analysis workflows
4. **Version control configs** - Track configuration changes

#### 🤖 **AI Integration**

1. **Use AI for complex patterns** - Let AI identify anomalies you might miss
2. **Ask specific questions** - Guide AI analysis with targeted queries
3. **Validate AI insights** - Cross-check AI conclusions with data
4. **Document AI findings** - Save useful AI analysis for future reference

***

**You are now a Gonzo power user!** 🚀 These advanced techniques will help you conduct sophisticated log analysis, handle complex scenarios, and integrate Gonzo into any workflow. The combination of systematic methodology, performance optimization, and AI assistance makes you capable of tackling any log analysis challenge.


# AI Providers Guide (v1)

Master each AI provider option for Gonzo. From cloud-based OpenAI to privacy-focused local models, this comprehensive guide helps you choose and configure the perfect AI solution for your needs.

{% hint style="info" %}
**Already completed basic setup?** This guide provides advanced configuration, optimization tips, and provider-specific best practices for production use.
{% endhint %}

### Provider Comparison Matrix

| Provider         | Setup Complexity | Privacy Level    | Cost Model    | Performance | Best Use Case                               |
| ---------------- | ---------------- | ---------------- | ------------- | ----------- | ------------------------------------------- |
| **OpenAI**       | Low              | Cloud            | Pay-per-use   | Excellent   | Production incidents, complex analysis      |
| **Ollama**       | Medium           | Complete         | Hardware only | Good        | Privacy-sensitive, unlimited usage          |
| **LM Studio**    | Low-Medium       | Complete         | Hardware only | Good        | Development, testing, experimentation       |
| **Azure OpenAI** | Medium           | Enterprise Cloud | Pay-per-use   | Excellent   | Enterprise compliance, hybrid cloud         |
| **Custom APIs**  | High             | Configurable     | Varies        | Varies      | Specialized models, existing infrastructure |

### OpenAI Provider Deep Dive

#### Model Selection Strategy

**Production Deployment:**

```bash
# Tier 1: Critical incidents (use best model)
export GONZO_PROD_MODEL="gpt-4"
alias gonzo-incident='gonzo --ai-model="$GONZO_PROD_MODEL"'

# Tier 2: Regular monitoring (balanced cost/performance)
export GONZO_MONITOR_MODEL="gpt-3.5-turbo"
alias gonzo-monitor='gonzo --ai-model="$GONZO_MONITOR_MODEL"'

# Tier 3: Development/testing (cost-optimized)
export GONZO_DEV_MODEL="gpt-3.5-turbo"
alias gonzo-dev='gonzo --ai-model="$GONZO_DEV_MODEL"'
```

#### Advanced OpenAI Configuration

**Cost Optimization Settings:**

```bash
# ~/.config/gonzo/openai-optimized.yml
ai-provider: "openai"
ai-model: "gpt-3.5-turbo"              # Default to cheaper model

# Context management for cost control
ai-context-size: 2000                  # Reduce token usage
ai-smart-context: true                 # Intelligent context trimming
ai-batch-requests: true                # Batch multiple questions

# Usage limits
ai-daily-token-limit: 100000          # Daily token budget
ai-warn-at-usage: 80000               # Warning threshold
ai-auto-downgrade: true                # Auto-switch to cheaper model when near limit
```

**Enterprise OpenAI Setup:**

```bash
# Enterprise organization configuration
export OPENAI_ORG_ID="org-your-organization-id"
export OPENAI_API_KEY="sk-your-enterprise-key"

# Advanced request configuration
export OPENAI_REQUEST_TIMEOUT=60       # Longer timeout for complex analysis
export OPENAI_MAX_RETRIES=5           # More retries for reliability
export OPENAI_BACKOFF_FACTOR=2        # Exponential backoff
```

#### OpenAI Model Characteristics

{% tabs %}
{% tab title="GPT-4 Family" %}
**GPT-4 (Recommended for Production)**

* **Cost:** $0.03/1K input tokens, $0.06/1K output
* **Context:** 8K tokens
* **Strengths:** Best reasoning, complex log analysis, accurate root cause identification
* **Best for:** Critical incidents, complex debugging, production monitoring

**GPT-4 Turbo**

* **Cost:** $0.01/1K input tokens, $0.03/1K output
* **Context:** 128K tokens
* **Strengths:** Large context, cost-effective, latest training data
* **Best for:** Large log files, comprehensive analysis, cost-sensitive production

```bash
# Production incident response
gonzo -f incident-logs.log --ai-model="gpt-4"

# Large log file analysis
gonzo -f huge-logfile.log --ai-model="gpt-4-turbo"
```

{% endtab %}

{% tab title="GPT-3.5 Family" %}
**GPT-3.5 Turbo (Best Balance)**

* **Cost:** $0.0015/1K input tokens, $0.002/1K output
* **Context:** 4K tokens
* **Strengths:** Fast, cost-effective, good quality
* **Best for:** Development, regular monitoring, routine analysis

**GPT-3.5 Turbo 16K**

* **Cost:** $0.003/1K input tokens, $0.004/1K output
* **Context:** 16K tokens
* **Strengths:** Larger context than standard, still affordable
* **Best for:** Medium-large log analysis, development with context needs

```bash
# Daily monitoring
gonzo -f /var/log/app.log --follow --ai-model="gpt-3.5-turbo"

# Development debugging
gonzo -f debug.log --ai-model="gpt-3.5-turbo-16k"
```

{% endtab %}

{% tab title="Usage Recommendations" %}
**Cost-Performance Matrix:**

| Use Case              | Recommended Model | Monthly Est. Cost\* |
| --------------------- | ----------------- | ------------------- |
| Development (daily)   | gpt-3.5-turbo     | $5-15               |
| Production monitoring | gpt-3.5-turbo     | $20-50              |
| Incident response     | gpt-4             | $10-30              |
| Large-scale analysis  | gpt-4-turbo       | $15-40              |

\*Based on typical log analysis usage patterns

**Model Switching Strategy:**

```bash
# Start with cheaper model, escalate as needed
gonzo -f logs.log --ai-model="gpt-3.5-turbo"
# If analysis needs more capability, press 'm' and switch to gpt-4
```

{% endtab %}
{% endtabs %}

#### OpenAI Rate Limiting and Quotas

**Understanding Rate Limits:**

```bash
# Check your current limits
curl -H "Authorization: Bearer $OPENAI_API_KEY" \
     https://api.openai.com/v1/dashboard/billing/subscription

# Monitor usage in real-time
curl -H "Authorization: Bearer $OPENAI_API_KEY" \
     https://api.openai.com/v1/dashboard/billing/usage
```

**Handling Rate Limits:**

```bash
# Configure automatic retry with backoff
export OPENAI_MAX_RETRIES=5
export OPENAI_RETRY_DELAY=1

# Use batch processing for high-volume analysis
# Filter logs first to reduce API calls
tail -f /var/log/app.log | grep ERROR | gonzo --ai-model="gpt-3.5-turbo"
```

### Ollama Provider Deep Dive

#### Model Selection for Log Analysis

**Recommended Models by Use Case:**

| Model          | Size  | RAM Required | Quality     | Best For                                    |
| -------------- | ----- | ------------ | ----------- | ------------------------------------------- |
| **llama3:8b**  | 4.7GB | 8GB+         | Excellent   | General log analysis, production ready      |
| **llama3:70b** | 40GB  | 64GB+        | Outstanding | Complex analysis, enterprise use            |
| **mistral**    | 4.1GB | 8GB+         | Good        | Fast analysis, resource-constrained systems |
| **codellama**  | 3.8GB | 8GB+         | Good        | Technical logs, code-related issues         |
| **mixtral**    | 26GB  | 32GB+        | Excellent   | Complex reasoning, multi-language logs      |

#### Advanced Ollama Configuration

**Performance Optimization:**

```bash
# ~/.ollama/config.json
{
  "gpu_layers": 35,                    # Use GPU acceleration if available
  "context_length": 4096,              # Context size for analysis
  "batch_size": 512,                   # Batch processing size
  "threads": 8,                        # CPU threads for processing
  "numa": true                         # NUMA optimization
}
```

**Memory Management:**

```bash
# Conservative memory usage
export OLLAMA_MAX_LOADED_MODELS=1     # Only keep one model in memory
export OLLAMA_FLASH_ATTENTION=1       # Memory-efficient attention

# High-performance setup
export OLLAMA_MAX_LOADED_MODELS=3     # Keep multiple models loaded
export OLLAMA_GPU_LAYERS=35           # Use GPU acceleration
```

#### Multi-Model Ollama Setup

**Strategy: Different Models for Different Tasks**

```bash
# Download specialized models
ollama pull llama3:8b                 # General analysis
ollama pull codellama                 # Technical/code logs  
ollama pull mistral                   # Fast analysis
ollama pull mixtral                   # Complex reasoning

# Model selection automation
cat > ~/.config/gonzo/ollama-smart.yml << EOF
ai-provider: "ollama"
ai-auto-select: true

# Model preferences by log type
model-preferences:
  error-analysis: "llama3:8b"
  performance-analysis: "mixtral"
  security-analysis: "llama3:8b"
  code-analysis: "codellama"
  quick-analysis: "mistral"
EOF
```

**Smart Model Switching:**

```bash
#!/bin/bash
# ollama-smart-switch.sh

select_model_for_analysis() {
    local log_type="$1"
    
    case "$log_type" in
        "error"|"exception"|"failure")
            echo "llama3:8b"
            ;;
        "performance"|"slow"|"timeout")
            echo "mixtral"
            ;;
        "security"|"auth"|"access")
            echo "llama3:8b"
            ;;
        "code"|"compile"|"syntax")
            echo "codellama"
            ;;
        *)
            echo "mistral"  # Default fast model
            ;;
    esac
}

# Usage: gonzo -f logs.log --ai-model="$(select_model_for_analysis error)"
```

#### Ollama Performance Tuning

**System Optimization:**

```bash
# CPU optimization
export OMP_NUM_THREADS=8              # Match your CPU cores
export OLLAMA_NUM_PARALLEL=2          # Parallel requests

# Memory optimization
export OLLAMA_MAX_LOADED_MODELS=1     # Conservative memory usage
sudo sysctl vm.swappiness=10          # Reduce swapping

# GPU optimization (if available)
export OLLAMA_GPU_LAYERS=35           # Use GPU acceleration
export CUDA_VISIBLE_DEVICES=0         # Select specific GPU
```

**Monitoring Ollama Performance:**

```bash
# Monitor resource usage
watch -n 1 'ps aux | grep ollama | head -5'

# Check model loading time
time ollama run llama3:8b "test"

# Monitor GPU usage (if applicable)
nvidia-smi -l 1
```

### LM Studio Provider Deep Dive

#### Model Recommendations for LM Studio

**Balanced Models (8-16GB RAM):**

```bash
# In LM Studio, search and download:
- "microsoft/DialoGPT-medium"          # 1.5GB, fast responses
- "meta-llama/Llama-2-7b-chat-hf"     # 7GB, good quality
- "mistralai/Mistral-7B-Instruct-v0.1" # 7GB, excellent instruction following
```

**High-Performance Models (32GB+ RAM):**

```bash
# Premium models for powerful systems:
- "meta-llama/Llama-2-13b-chat-hf"    # 13GB, excellent reasoning
- "meta-llama/Llama-2-70b-chat-hf"    # 70GB, GPT-4 level quality
- "microsoft/WizardCoder-15B-V1.0"    # 15GB, specialized for code/logs
```

#### LM Studio Configuration

**Server Settings:**

```json
{
  "server": {
    "port": 1234,
    "host": "localhost",
    "cors": true,
    "max_tokens": 2048,
    "temperature": 0.7,
    "top_p": 0.9,
    "context_length": 4096
  }
}
```

**Model-Specific Tuning:**

```bash
# For log analysis, optimize for factual responses
# In LM Studio server settings:
# - Temperature: 0.3 (more factual, less creative)
# - Top-p: 0.8 (focused responses)
# - Max tokens: 1024 (concise analysis)
```

#### LM Studio Best Practices

**Model Management:**

```bash
# Keep models organized
# Create folders in LM Studio:
# - "Log Analysis" folder for specialized models
# - "General" folder for multipurpose models
# - "Fast" folder for quick response models

# Monitor disk space (models are large)
du -sh ~/LMStudio/models/

# Regular cleanup of unused models
# Remove old/unused models to free space
```

**Performance Optimization:**

```bash
# System settings for LM Studio
# Allocate more RAM to LM Studio process
# Close other applications when running large models
# Use SSD storage for model files

# Network optimization
# Ensure localhost networking is optimal
ping localhost
curl -o /dev/null -s -w "%{time_total}" http://localhost:1234/v1/models
```

### Azure OpenAI Service

#### Enterprise Setup

**Azure Resource Configuration:**

```bash
# Azure CLI setup
az login
az account set --subscription "your-subscription-id"

# Create Azure OpenAI resource
az cognitiveservices account create \
  --name "gonzo-openai" \
  --resource-group "your-rg" \
  --kind "OpenAI" \
  --sku "S0" \
  --location "eastus"

# Get endpoint and keys
az cognitiveservices account show \
  --name "gonzo-openai" \
  --resource-group "your-rg" \
  --query "properties.endpoint"

az cognitiveservices account keys list \
  --name "gonzo-openai" \
  --resource-group "your-rg"
```

**Gonzo Configuration for Azure:**

```bash
# Azure OpenAI environment variables
export AZURE_OPENAI_KEY="your-azure-key"
export AZURE_OPENAI_ENDPOINT="https://your-resource.openai.azure.com/"
export AZURE_OPENAI_API_VERSION="2023-12-01-preview"

# Configure Gonzo for Azure
export OPENAI_API_KEY="$AZURE_OPENAI_KEY"
export OPENAI_API_BASE="$AZURE_OPENAI_ENDPOINT"
export OPENAI_API_TYPE="azure"
export OPENAI_API_VERSION="$AZURE_OPENAI_API_VERSION"
```

**Model Deployment in Azure:**

```bash
# Deploy models in Azure OpenAI Studio
# 1. Visit Azure OpenAI Studio
# 2. Go to "Deployments" section  
# 3. Create new deployment:
#    - Model: gpt-35-turbo or gpt-4
#    - Deployment name: gonzo-analysis
#    - Version: Latest

# Use deployed model
gonzo -f logs.log --ai-model="gonzo-analysis"
```

#### Azure-Specific Features

**Private Endpoints:**

```bash
# Configure private endpoint for enhanced security
az network private-endpoint create \
  --resource-group "your-rg" \
  --name "gonzo-openai-pe" \
  --vnet-name "your-vnet" \
  --subnet "your-subnet" \
  --private-connection-resource-id "/subscriptions/.../openai-resource" \
  --connection-name "gonzo-connection"
```

**Managed Identity:**

```bash
# Use managed identity for authentication
export AZURE_CLIENT_ID="your-managed-identity-id"
export AZURE_USE_MANAGED_IDENTITY="true"

# No API key needed with managed identity
unset OPENAI_API_KEY
```

### Custom API Providers

#### AWS Bedrock Integration

**Setup with Bedrock Proxy:**

```bash
# Use bedrock-proxy for OpenAI compatibility
# Install: https://github.com/yourcompany/bedrock-proxy

# Configuration
export AWS_REGION="us-east-1"
export AWS_ACCESS_KEY_ID="your-access-key"
export AWS_SECRET_ACCESS_KEY="your-secret-key"

# Proxy configuration
export OPENAI_API_KEY="bedrock-proxy-key"
export OPENAI_API_BASE="https://your-bedrock-proxy.amazonaws.com/v1"

# Available Bedrock models through proxy
gonzo -f logs.log --ai-model="claude-3-sonnet"
gonzo -f logs.log --ai-model="llama2-70b"
```

#### Google Cloud Vertex AI

**Vertex AI Proxy Setup:**

```bash
# Use vertex-ai-proxy for OpenAI compatibility
export GOOGLE_APPLICATION_CREDENTIALS="path/to/service-account.json"
export GOOGLE_CLOUD_PROJECT="your-project-id"

# Proxy configuration
export OPENAI_API_KEY="vertex-proxy-key"
export OPENAI_API_BASE="https://your-vertex-proxy.googleapis.com/v1"

# Available models
gonzo -f logs.log --ai-model="text-bison"
gonzo -f logs.log --ai-model="chat-bison"
```

#### Self-Hosted Models

**Hugging Face Transformers:**

```bash
# Self-hosted API using transformers
# Deploy with: https://github.com/huggingface/text-generation-inference

export OPENAI_API_KEY="hf-local-key"
export OPENAI_API_BASE="http://your-hf-server:8080/v1"

# Available self-hosted models
gonzo -f logs.log --ai-model="CodeLlama-34B-Instruct"
gonzo -f logs.log --ai-model="Mistral-7B-Instruct"
```

### Provider Selection Decision Tree

#### Choose Based on Your Needs

```bash
# Decision flowchart:

# Data Privacy Critical?
if [ "$PRIVACY_CRITICAL" = "yes" ]; then
    # Use local models
    if [ "$SYSTEM_RAM" -gt 16 ]; then
        echo "Use Ollama with llama3:8b or larger"
    else
        echo "Use LM Studio with smaller models"
    fi
    
# Cost Sensitivity High?
elif [ "$COST_SENSITIVE" = "yes" ]; then
    if [ "$USAGE_VOLUME" = "high" ]; then
        echo "Use Ollama for unlimited usage"
    else
        echo "Use OpenAI gpt-3.5-turbo"
    fi
    
# Enterprise Compliance Required?
elif [ "$ENTERPRISE" = "yes" ]; then
    echo "Use Azure OpenAI or custom enterprise API"
    
# Maximum Quality Needed?
else
    echo "Use OpenAI gpt-4"
fi
```

#### Multi-Provider Strategy

**Hybrid Approach:**

```bash
# ~/.config/gonzo/multi-provider.yml
providers:
  development:
    provider: "ollama"
    model: "mistral"
    endpoint: "http://localhost:11434"
    
  monitoring:
    provider: "openai"
    model: "gpt-3.5-turbo"
    cost_limit: 50  # Monthly USD limit
    
  incidents:
    provider: "openai"  
    model: "gpt-4"
    priority: "high"
    
  enterprise:
    provider: "azure"
    model: "gpt-4"
    endpoint: "https://company.openai.azure.com/"
```

**Provider Fallback Chain:**

```bash
#!/bin/bash
# provider-fallback.sh

try_providers() {
    local log_file="$1"
    
    # Try primary provider (OpenAI)
    if gonzo -f "$log_file" --ai-model="gpt-4" --timeout=30; then
        return 0
    fi
    
    # Fallback to local Ollama
    echo "OpenAI failed, trying Ollama..."
    if gonzo -f "$log_file" --ai-model="llama3" --timeout=60; then
        return 0
    fi
    
    # Final fallback to LM Studio
    echo "Ollama failed, trying LM Studio..."
    OPENAI_API_BASE="http://localhost:1234/v1" \
    gonzo -f "$log_file" --timeout=60
}
```

### Performance Comparison

#### Benchmark Results

**Analysis Speed (avg response time):**

| Provider  | Model         | Simple Query | Complex Analysis | Large Context |
| --------- | ------------- | ------------ | ---------------- | ------------- |
| OpenAI    | gpt-4         | 2-3s         | 8-12s            | 15-25s        |
| OpenAI    | gpt-3.5-turbo | 1-2s         | 3-5s             | 8-12s         |
| Ollama    | llama3:8b     | 5-8s         | 15-25s           | 30-45s        |
| Ollama    | mistral       | 3-5s         | 10-15s           | 20-30s        |
| LM Studio | Various       | 4-10s        | 12-30s           | 25-60s        |

**Quality Assessment (log analysis accuracy):**

| Provider | Model         | Technical Accuracy | Context Understanding | Actionable Insights |
| -------- | ------------- | ------------------ | --------------------- | ------------------- |
| OpenAI   | gpt-4         | 95%                | 90%                   | 85%                 |
| OpenAI   | gpt-3.5-turbo | 85%                | 80%                   | 75%                 |
| Ollama   | llama3:8b     | 80%                | 75%                   | 70%                 |
| Ollama   | mistral       | 75%                | 70%                   | 65%                 |

#### Resource Usage

**Memory Requirements:**

```bash
# OpenAI: Minimal local memory (API-based)
# Memory usage: ~50MB (Gonzo only)

# Ollama: Model-dependent memory
# llama3:8b: ~8GB RAM
# mistral: ~6GB RAM  
# mixtral: ~24GB RAM

# LM Studio: Model-dependent memory
# Similar to Ollama but with GUI overhead
# Add ~500MB for LM Studio application

# Monitor actual usage:
ps aux | grep -E "(gonzo|ollama|lmstudio)" | awk '{print $4, $11}'
```

### Best Practices by Provider

#### OpenAI Best Practices

✅ **Do:**

* Use gpt-3.5-turbo for development and routine analysis
* Reserve gpt-4 for complex incidents and production issues
* Monitor API usage and costs regularly
* Implement token budgets and alerts
* Use specific, targeted questions for better responses

❌ **Don't:**

* Send sensitive data without understanding OpenAI's data policies
* Use gpt-4 for simple queries that gpt-3.5-turbo can handle
* Ignore rate limits and quotas
* Include unnecessary context that increases token usage

#### Ollama Best Practices

✅ **Do:**

* Keep Ollama service running as a daemon
* Use appropriate model sizes for your hardware
* Monitor system resources during model loading
* Download models during off-peak hours
* Use GPU acceleration when available

❌ **Don't:**

* Load multiple large models simultaneously without sufficient RAM
* Ignore model update notifications
* Run Ollama on systems with insufficient memory
* Use CPU-only inference for large models

#### LM Studio Best Practices

✅ **Do:**

* Organize models in logical folders
* Test models before production use
* Monitor disk space for model storage
* Use appropriate model settings for log analysis
* Keep LM Studio updated

❌ **Don't:**

* Download models without checking system requirements
* Run multiple models simultaneously without adequate resources
* Ignore model performance metrics
* Use default settings without optimization

### What's Next?

Now that you understand all AI provider options, learn how to use them effectively:

* **Using AI Features** - Master AI-powered workflows and practical usage patterns
* **Log Analysis** - Combine AI insights with algorithmic analysis
* **Configuration** - Set up provider-specific configurations

Or start using your chosen provider immediately:

```bash
# Quick provider test
gonzo -f your-logs.log --ai-model="your-chosen-model"

# Try AI features:
# - Press 'i' for log analysis
# - Press 'c' for interactive chat  
# - Press 'm' to compare different models
```

***

**You now have complete mastery over AI provider selection and configuration!** 🚀 Whether you choose cloud-based APIs for maximum quality or local models for privacy and cost control, you can optimize your AI setup for any scenario.


# AI Providers Guide (benchmarks edited)

Master each AI provider option for Gonzo. From cloud-based OpenAI to privacy-focused local models, this comprehensive guide helps you choose and configure the perfect AI solution for your needs.

{% hint style="info" %}
**Already completed basic setup?** This guide provides advanced configuration, optimization tips, and provider-specific best practices for production use.
{% endhint %}

### Provider Comparison Matrix

| Provider         | Setup Complexity | Privacy Level    | Cost Model    | Performance | Best Use Case                               |
| ---------------- | ---------------- | ---------------- | ------------- | ----------- | ------------------------------------------- |
| **OpenAI**       | Low              | Cloud            | Pay-per-use   | Excellent   | Production incidents, complex analysis      |
| **Ollama**       | Medium           | Complete         | Hardware only | Good        | Privacy-sensitive, unlimited usage          |
| **LM Studio**    | Low-Medium       | Complete         | Hardware only | Good        | Development, testing, experimentation       |
| **Azure OpenAI** | Medium           | Enterprise Cloud | Pay-per-use   | Excellent   | Enterprise compliance, hybrid cloud         |
| **Custom APIs**  | High             | Configurable     | Varies        | Varies      | Specialized models, existing infrastructure |

### OpenAI Provider Deep Dive

#### Model Selection Strategy

**Production Deployment:**

```bash
# Tier 1: Critical incidents (use best model)
export GONZO_PROD_MODEL="gpt-4"
alias gonzo-incident='gonzo --ai-model="$GONZO_PROD_MODEL"'

# Tier 2: Regular monitoring (balanced cost/performance)
export GONZO_MONITOR_MODEL="gpt-3.5-turbo"
alias gonzo-monitor='gonzo --ai-model="$GONZO_MONITOR_MODEL"'

# Tier 3: Development/testing (cost-optimized)
export GONZO_DEV_MODEL="gpt-3.5-turbo"
alias gonzo-dev='gonzo --ai-model="$GONZO_DEV_MODEL"'
```

#### Advanced OpenAI Configuration

**Cost Optimization Settings:**

```bash
# ~/.config/gonzo/openai-optimized.yml
ai-provider: "openai"
ai-model: "gpt-3.5-turbo"              # Default to cheaper model

# Context management for cost control
ai-context-size: 2000                  # Reduce token usage
ai-smart-context: true                 # Intelligent context trimming
ai-batch-requests: true                # Batch multiple questions

# Usage limits
ai-daily-token-limit: 100000          # Daily token budget
ai-warn-at-usage: 80000               # Warning threshold
ai-auto-downgrade: true                # Auto-switch to cheaper model when near limit
```

**Enterprise OpenAI Setup:**

```bash
# Enterprise organization configuration
export OPENAI_ORG_ID="org-your-organization-id"
export OPENAI_API_KEY="sk-your-enterprise-key"

# Advanced request configuration
export OPENAI_REQUEST_TIMEOUT=60       # Longer timeout for complex analysis
export OPENAI_MAX_RETRIES=5           # More retries for reliability
export OPENAI_BACKOFF_FACTOR=2        # Exponential backoff
```

#### OpenAI Model Characteristics

{% tabs %}
{% tab title="GPT-4 Family" %}
**GPT-4 (Recommended for Production)**

* **Cost:** $0.03/1K input tokens, $0.06/1K output
* **Context:** 8K tokens
* **Strengths:** Best reasoning, complex log analysis, accurate root cause identification
* **Best for:** Critical incidents, complex debugging, production monitoring

**GPT-4 Turbo**

* **Cost:** $0.01/1K input tokens, $0.03/1K output
* **Context:** 128K tokens
* **Strengths:** Large context, cost-effective, latest training data
* **Best for:** Large log files, comprehensive analysis, cost-sensitive production

```bash
# Production incident response
gonzo -f incident-logs.log --ai-model="gpt-4"

# Large log file analysis
gonzo -f huge-logfile.log --ai-model="gpt-4-turbo"
```

{% endtab %}

{% tab title="GPT-3.5 Family" %}
**GPT-3.5 Turbo (Best Balance)**

* **Cost:** $0.0015/1K input tokens, $0.002/1K output
* **Context:** 4K tokens
* **Strengths:** Fast, cost-effective, good quality
* **Best for:** Development, regular monitoring, routine analysis

**GPT-3.5 Turbo 16K**

* **Cost:** $0.003/1K input tokens, $0.004/1K output
* **Context:** 16K tokens
* **Strengths:** Larger context than standard, still affordable
* **Best for:** Medium-large log analysis, development with context needs

```bash
# Daily monitoring
gonzo -f /var/log/app.log --follow --ai-model="gpt-3.5-turbo"

# Development debugging
gonzo -f debug.log --ai-model="gpt-3.5-turbo-16k"
```

{% endtab %}

{% tab title="Usage Recommendations" %}
**Cost-Performance Matrix:**

| Use Case              | Recommended Model | Monthly Est. Cost\* |
| --------------------- | ----------------- | ------------------- |
| Development (daily)   | gpt-3.5-turbo     | $5-15               |
| Production monitoring | gpt-3.5-turbo     | $20-50              |
| Incident response     | gpt-4             | $10-30              |
| Large-scale analysis  | gpt-4-turbo       | $15-40              |

\*Based on typical log analysis usage patterns

**Model Switching Strategy:**

```bash
# Start with cheaper model, escalate as needed
gonzo -f logs.log --ai-model="gpt-3.5-turbo"
# If analysis needs more capability, press 'm' and switch to gpt-4
```

{% endtab %}
{% endtabs %}

#### OpenAI Rate Limiting and Quotas

**Understanding Rate Limits:**

```bash
# Check your current limits
curl -H "Authorization: Bearer $OPENAI_API_KEY" \
     https://api.openai.com/v1/dashboard/billing/subscription

# Monitor usage in real-time
curl -H "Authorization: Bearer $OPENAI_API_KEY" \
     https://api.openai.com/v1/dashboard/billing/usage
```

**Handling Rate Limits:**

```bash
# Configure automatic retry with backoff
export OPENAI_MAX_RETRIES=5
export OPENAI_RETRY_DELAY=1

# Use batch processing for high-volume analysis
# Filter logs first to reduce API calls
tail -f /var/log/app.log | grep ERROR | gonzo --ai-model="gpt-3.5-turbo"
```

### Ollama Provider Deep Dive

#### Model Selection for Log Analysis

**Recommended Models by Use Case:**

| Model          | Size  | RAM Required | Quality     | Best For                                    |
| -------------- | ----- | ------------ | ----------- | ------------------------------------------- |
| **llama3:8b**  | 4.7GB | 8GB+         | Excellent   | General log analysis, production ready      |
| **llama3:70b** | 40GB  | 64GB+        | Outstanding | Complex analysis, enterprise use            |
| **mistral**    | 4.1GB | 8GB+         | Good        | Fast analysis, resource-constrained systems |
| **codellama**  | 3.8GB | 8GB+         | Good        | Technical logs, code-related issues         |
| **mixtral**    | 26GB  | 32GB+        | Excellent   | Complex reasoning, multi-language logs      |

#### Advanced Ollama Configuration

**Performance Optimization:**

```bash
# ~/.ollama/config.json
{
  "gpu_layers": 35,                    # Use GPU acceleration if available
  "context_length": 4096,              # Context size for analysis
  "batch_size": 512,                   # Batch processing size
  "threads": 8,                        # CPU threads for processing
  "numa": true                         # NUMA optimization
}
```

**Memory Management:**

```bash
# Conservative memory usage
export OLLAMA_MAX_LOADED_MODELS=1     # Only keep one model in memory
export OLLAMA_FLASH_ATTENTION=1       # Memory-efficient attention

# High-performance setup
export OLLAMA_MAX_LOADED_MODELS=3     # Keep multiple models loaded
export OLLAMA_GPU_LAYERS=35           # Use GPU acceleration
```

#### Multi-Model Ollama Setup

**Strategy: Different Models for Different Tasks**

```bash
# Download specialized models
ollama pull llama3:8b                 # General analysis
ollama pull codellama                 # Technical/code logs  
ollama pull mistral                   # Fast analysis
ollama pull mixtral                   # Complex reasoning

# Model selection automation
cat > ~/.config/gonzo/ollama-smart.yml << EOF
ai-provider: "ollama"
ai-auto-select: true

# Model preferences by log type
model-preferences:
  error-analysis: "llama3:8b"
  performance-analysis: "mixtral"
  security-analysis: "llama3:8b"
  code-analysis: "codellama"
  quick-analysis: "mistral"
EOF
```

**Smart Model Switching:**

```bash
#!/bin/bash
# ollama-smart-switch.sh

select_model_for_analysis() {
    local log_type="$1"
    
    case "$log_type" in
        "error"|"exception"|"failure")
            echo "llama3:8b"
            ;;
        "performance"|"slow"|"timeout")
            echo "mixtral"
            ;;
        "security"|"auth"|"access")
            echo "llama3:8b"
            ;;
        "code"|"compile"|"syntax")
            echo "codellama"
            ;;
        *)
            echo "mistral"  # Default fast model
            ;;
    esac
}

# Usage: gonzo -f logs.log --ai-model="$(select_model_for_analysis error)"
```

#### Ollama Performance Tuning

**System Optimization:**

```bash
# CPU optimization
export OMP_NUM_THREADS=8              # Match your CPU cores
export OLLAMA_NUM_PARALLEL=2          # Parallel requests

# Memory optimization
export OLLAMA_MAX_LOADED_MODELS=1     # Conservative memory usage
sudo sysctl vm.swappiness=10          # Reduce swapping

# GPU optimization (if available)
export OLLAMA_GPU_LAYERS=35           # Use GPU acceleration
export CUDA_VISIBLE_DEVICES=0         # Select specific GPU
```

**Monitoring Ollama Performance:**

```bash
# Monitor resource usage
watch -n 1 'ps aux | grep ollama | head -5'

# Check model loading time
time ollama run llama3:8b "test"

# Monitor GPU usage (if applicable)
nvidia-smi -l 1
```

### LM Studio Provider Deep Dive

#### Model Recommendations for LM Studio

**Balanced Models (8-16GB RAM):**

```bash
# In LM Studio, search and download:
- "microsoft/DialoGPT-medium"          # 1.5GB, fast responses
- "meta-llama/Llama-2-7b-chat-hf"     # 7GB, good quality
- "mistralai/Mistral-7B-Instruct-v0.1" # 7GB, excellent instruction following
```

**High-Performance Models (32GB+ RAM):**

```bash
# Premium models for powerful systems:
- "meta-llama/Llama-2-13b-chat-hf"    # 13GB, excellent reasoning
- "meta-llama/Llama-2-70b-chat-hf"    # 70GB, GPT-4 level quality
- "microsoft/WizardCoder-15B-V1.0"    # 15GB, specialized for code/logs
```

#### LM Studio Configuration

**Server Settings:**

```json
{
  "server": {
    "port": 1234,
    "host": "localhost",
    "cors": true,
    "max_tokens": 2048,
    "temperature": 0.7,
    "top_p": 0.9,
    "context_length": 4096
  }
}
```

**Model-Specific Tuning:**

```bash
# For log analysis, optimize for factual responses
# In LM Studio server settings:
# - Temperature: 0.3 (more factual, less creative)
# - Top-p: 0.8 (focused responses)
# - Max tokens: 1024 (concise analysis)
```

#### LM Studio Best Practices

**Model Management:**

```bash
# Keep models organized
# Create folders in LM Studio:
# - "Log Analysis" folder for specialized models
# - "General" folder for multipurpose models
# - "Fast" folder for quick response models

# Monitor disk space (models are large)
du -sh ~/LMStudio/models/

# Regular cleanup of unused models
# Remove old/unused models to free space
```

**Performance Optimization:**

```bash
# System settings for LM Studio
# Allocate more RAM to LM Studio process
# Close other applications when running large models
# Use SSD storage for model files

# Network optimization
# Ensure localhost networking is optimal
ping localhost
curl -o /dev/null -s -w "%{time_total}" http://localhost:1234/v1/models
```

### Azure OpenAI Service

#### Enterprise Setup

**Azure Resource Configuration:**

```bash
# Azure CLI setup
az login
az account set --subscription "your-subscription-id"

# Create Azure OpenAI resource
az cognitiveservices account create \
  --name "gonzo-openai" \
  --resource-group "your-rg" \
  --kind "OpenAI" \
  --sku "S0" \
  --location "eastus"

# Get endpoint and keys
az cognitiveservices account show \
  --name "gonzo-openai" \
  --resource-group "your-rg" \
  --query "properties.endpoint"

az cognitiveservices account keys list \
  --name "gonzo-openai" \
  --resource-group "your-rg"
```

**Gonzo Configuration for Azure:**

```bash
# Azure OpenAI environment variables
export AZURE_OPENAI_KEY="your-azure-key"
export AZURE_OPENAI_ENDPOINT="https://your-resource.openai.azure.com/"
export AZURE_OPENAI_API_VERSION="2023-12-01-preview"

# Configure Gonzo for Azure
export OPENAI_API_KEY="$AZURE_OPENAI_KEY"
export OPENAI_API_BASE="$AZURE_OPENAI_ENDPOINT"
export OPENAI_API_TYPE="azure"
export OPENAI_API_VERSION="$AZURE_OPENAI_API_VERSION"
```

**Model Deployment in Azure:**

```bash
# Deploy models in Azure OpenAI Studio
# 1. Visit Azure OpenAI Studio
# 2. Go to "Deployments" section  
# 3. Create new deployment:
#    - Model: gpt-35-turbo or gpt-4
#    - Deployment name: gonzo-analysis
#    - Version: Latest

# Use deployed model
gonzo -f logs.log --ai-model="gonzo-analysis"
```

#### Azure-Specific Features

**Private Endpoints:**

```bash
# Configure private endpoint for enhanced security
az network private-endpoint create \
  --resource-group "your-rg" \
  --name "gonzo-openai-pe" \
  --vnet-name "your-vnet" \
  --subnet "your-subnet" \
  --private-connection-resource-id "/subscriptions/.../openai-resource" \
  --connection-name "gonzo-connection"
```

**Managed Identity:**

```bash
# Use managed identity for authentication
export AZURE_CLIENT_ID="your-managed-identity-id"
export AZURE_USE_MANAGED_IDENTITY="true"

# No API key needed with managed identity
unset OPENAI_API_KEY
```

### Custom API Providers

#### AWS Bedrock Integration

**Setup with Bedrock Proxy:**

```bash
# Use bedrock-proxy for OpenAI compatibility
# Install: https://github.com/yourcompany/bedrock-proxy

# Configuration
export AWS_REGION="us-east-1"
export AWS_ACCESS_KEY_ID="your-access-key"
export AWS_SECRET_ACCESS_KEY="your-secret-key"

# Proxy configuration
export OPENAI_API_KEY="bedrock-proxy-key"
export OPENAI_API_BASE="https://your-bedrock-proxy.amazonaws.com/v1"

# Available Bedrock models through proxy
gonzo -f logs.log --ai-model="claude-3-sonnet"
gonzo -f logs.log --ai-model="llama2-70b"
```

#### Google Cloud Vertex AI

**Vertex AI Proxy Setup:**

```bash
# Use vertex-ai-proxy for OpenAI compatibility
export GOOGLE_APPLICATION_CREDENTIALS="path/to/service-account.json"
export GOOGLE_CLOUD_PROJECT="your-project-id"

# Proxy configuration
export OPENAI_API_KEY="vertex-proxy-key"
export OPENAI_API_BASE="https://your-vertex-proxy.googleapis.com/v1"

# Available models
gonzo -f logs.log --ai-model="text-bison"
gonzo -f logs.log --ai-model="chat-bison"
```

#### Self-Hosted Models

**Hugging Face Transformers:**

```bash
# Self-hosted API using transformers
# Deploy with: https://github.com/huggingface/text-generation-inference

export OPENAI_API_KEY="hf-local-key"
export OPENAI_API_BASE="http://your-hf-server:8080/v1"

# Available self-hosted models
gonzo -f logs.log --ai-model="CodeLlama-34B-Instruct"
gonzo -f logs.log --ai-model="Mistral-7B-Instruct"
```

### Provider Selection Decision Tree

#### Choose Based on Your Needs

```bash
# Decision flowchart:

# Data Privacy Critical?
if [ "$PRIVACY_CRITICAL" = "yes" ]; then
    # Use local models
    if [ "$SYSTEM_RAM" -gt 16 ]; then
        echo "Use Ollama with llama3:8b or larger"
    else
        echo "Use LM Studio with smaller models"
    fi
    
# Cost Sensitivity High?
elif [ "$COST_SENSITIVE" = "yes" ]; then
    if [ "$USAGE_VOLUME" = "high" ]; then
        echo "Use Ollama for unlimited usage"
    else
        echo "Use OpenAI gpt-3.5-turbo"
    fi
    
# Enterprise Compliance Required?
elif [ "$ENTERPRISE" = "yes" ]; then
    echo "Use Azure OpenAI or custom enterprise API"
    
# Maximum Quality Needed?
else
    echo "Use OpenAI gpt-4"
fi
```

#### Multi-Provider Strategy

**Hybrid Approach:**

```bash
# ~/.config/gonzo/multi-provider.yml
providers:
  development:
    provider: "ollama"
    model: "mistral"
    endpoint: "http://localhost:11434"
    
  monitoring:
    provider: "openai"
    model: "gpt-3.5-turbo"
    cost_limit: 50  # Monthly USD limit
    
  incidents:
    provider: "openai"  
    model: "gpt-4"
    priority: "high"
    
  enterprise:
    provider: "azure"
    model: "gpt-4"
    endpoint: "https://company.openai.azure.com/"
```

**Provider Fallback Chain:**

```bash
#!/bin/bash
# provider-fallback.sh

try_providers() {
    local log_file="$1"
    
    # Try primary provider (OpenAI)
    if gonzo -f "$log_file" --ai-model="gpt-4" --timeout=30; then
        return 0
    fi
    
    # Fallback to local Ollama
    echo "OpenAI failed, trying Ollama..."
    if gonzo -f "$log_file" --ai-model="llama3" --timeout=60; then
        return 0
    fi
    
    # Final fallback to LM Studio
    echo "Ollama failed, trying LM Studio..."
    OPENAI_API_BASE="http://localhost:1234/v1" \
    gonzo -f "$log_file" --timeout=60
}
```

### Performance Comparison

#### Understanding Provider Performance

**Performance varies significantly based on:**

* Network connectivity and latency (cloud providers)
* Hardware specifications (local models)
* Query complexity and context size
* Current API load and availability
* Model configuration and optimization

#### Qualitative Performance Characteristics

**Response Speed (Relative Comparison):**

| Provider  | Model          | Typical Speed        | Notes                                              |
| --------- | -------------- | -------------------- | -------------------------------------------------- |
| OpenAI    | gpt-3.5-turbo  | Fastest cloud option | Optimized for speed, good for real-time analysis   |
| OpenAI    | gpt-4          | Moderate cloud speed | Slower but higher quality, best for complex issues |
| Ollama    | mistral        | Fastest local option | Good balance of speed and capability               |
| Ollama    | llama3:8b      | Moderate local speed | Excellent quality for local deployment             |
| LM Studio | Various models | Variable             | Depends heavily on hardware and model choice       |

**Quality Characteristics (Based on Community Feedback):**

| Provider | Model         | Strengths                                  | Best Use Cases                                 |
| -------- | ------------- | ------------------------------------------ | ---------------------------------------------- |
| OpenAI   | gpt-4         | Excellent reasoning, context understanding | Complex debugging, root cause analysis         |
| OpenAI   | gpt-3.5-turbo | Good balance, fast responses               | Daily monitoring, routine analysis             |
| Ollama   | llama3:8b     | Strong technical understanding             | Privacy-required environments, unlimited usage |
| Ollama   | mistral       | Fast, decent quality                       | Quick analysis, resource-constrained systems   |

#### Benchmark Your Own Setup

**Test Response Times:**

```bash
# Create a simple benchmark script
time_test() {
    local start_time=$(date +%s.%N)
    echo "Test log: ERROR database connection failed" | gonzo --ai-model="$1" > /dev/null
    local end_time=$(date +%s.%N)
    local duration=$(echo "$end_time - $start_time" | bc)
    echo "Model $1: ${duration}s"
}

# Test different models
time_test "gpt-4"
time_test "gpt-3.5-turbo"
time_test "llama3"
```

**Quality Assessment Framework:**

```bash
# Create test scenarios for your specific use case:

# 1. Error Analysis Test
echo '{"level":"error","message":"NullPointerException in UserService.authenticate()","trace":"..."}' | \
gonzo --ai-model="your-model"
# Evaluate: Does it correctly identify the issue and suggest investigation steps?

# 2. Pattern Recognition Test  
# Use logs with known patterns and see if AI identifies them correctly

# 3. Root Cause Analysis Test
# Use logs from resolved incidents and see if AI suggests correct root causes
```

#### Community Resources and Real-World Feedback

**Where to Find Actual Performance Data:**

* **Ollama Community:** [GitHub Discussions](https://github.com/ollama/ollama/discussions) - Real user benchmarks and hardware comparisons
* **OpenAI Community:** [OpenAI Community Forum](https://community.openai.com) - API performance discussions and optimization tips
* **Reddit Communities:** r/LocalLLaMA, r/OpenAI - User experiences and comparative analysis
* **Gonzo Community:** [GitHub Discussions](https://github.com/control-theory/gonzo/discussions) - Log analysis specific experiences

**Performance Testing Tools:**

```bash
# Create your own benchmark suite
mkdir ~/gonzo-benchmarks
cd ~/gonzo-benchmarks

# Sample test logs for consistent testing
cat > test-error.log << EOF
{"timestamp":"2024-01-15T10:30:00Z","level":"error","service":"api","message":"Database connection timeout","duration":30000}
{"timestamp":"2024-01-15T10:30:01Z","level":"error","service":"auth","message":"JWT token validation failed","user":"12345"}
EOF

# Benchmark script
cat > benchmark.sh << EOF
#!/bin/bash
models=("gpt-4" "gpt-3.5-turbo" "llama3" "mistral")

for model in "\${models[@]}"; do
    echo "Testing \$model..."
    time gonzo -f test-error.log --ai-model="\$model" --test-mode
done
EOF

chmod +x benchmark.sh
./benchmark.sh
```

{% hint style="info" %}
**Contribute Your Results:** Consider sharing your benchmark results with the Gonzo community to help others make informed provider choices for their specific hardware and use cases.
{% endhint %}

### Best Practices by Provider

#### OpenAI Best Practices

✅ **Do:**

* Use gpt-3.5-turbo for development and routine analysis
* Reserve gpt-4 for complex incidents and production issues
* Monitor API usage and costs regularly
* Implement token budgets and alerts
* Use specific, targeted questions for better responses

❌ **Don't:**

* Send sensitive data without understanding OpenAI's data policies
* Use gpt-4 for simple queries that gpt-3.5-turbo can handle
* Ignore rate limits and quotas
* Include unnecessary context that increases token usage

#### Ollama Best Practices

✅ **Do:**

* Keep Ollama service running as a daemon
* Use appropriate model sizes for your hardware
* Monitor system resources during model loading
* Download models during off-peak hours
* Use GPU acceleration when available

❌ **Don't:**

* Load multiple large models simultaneously without sufficient RAM
* Ignore model update notifications
* Run Ollama on systems with insufficient memory
* Use CPU-only inference for large models

#### LM Studio Best Practices

✅ **Do:**

* Organize models in logical folders
* Test models before production use
* Monitor disk space for model storage
* Use appropriate model settings for log analysis
* Keep LM Studio updated

❌ **Don't:**

* Download models without checking system requirements
* Run multiple models simultaneously without adequate resources
* Ignore model performance metrics
* Use default settings without optimization

### What's Next?

Now that you understand all AI provider options, learn how to use them effectively:

* **Using AI Features** - Master AI-powered workflows and practical usage patterns
* **Log Analysis** - Combine AI insights with algorithmic analysis
* **Configuration** - Set up provider-specific configurations

Or start using your chosen provider immediately:

```bash
# Quick provider test
gonzo -f your-logs.log --ai-model="your-chosen-model"

# Try AI features:
# - Press 'i' for log analysis
# - Press 'c' for interactive chat  
# - Press 'm' to compare different models
```

***

**You now have complete mastery over AI provider selection and configuration!** 🚀 Whether you choose cloud-based APIs for maximum quality or local models for privacy and cost control, you can optimize your AI setup for any scenario.


# Using AI Features

Master Gonzo's AI-powered capabilities to transform log analysis from manual investigation to intelligent, automated insights. This comprehensive guide covers all AI features, workflows, and advanced techniques for getting the most out of AI-assisted log analysis.

{% hint style="success" %}
**Prerequisites:** Ensure you have AI configured - see Setup & Configuration if you haven't completed AI setup yet.
{% endhint %}

### AI Features Overview

Gonzo integrates AI throughout the interface, providing intelligent assistance at every level:

| Feature                 | Trigger                  | What It Does                        | Best For                      |
| ----------------------- | ------------------------ | ----------------------------------- | ----------------------------- |
| **Log Analysis**        | Press `i` on log entry   | Analyzes individual log entries     | Understanding specific errors |
| **AI Chat**             | Press `c` in log details | Interactive conversation about logs | Complex investigation         |
| **Model Switching**     | Press `m` anywhere       | Switch between available AI models  | Optimizing cost vs quality    |
| **Pattern Insights**    | AI + Counts panel        | Explains detected patterns          | Understanding system behavior |
| **Contextual Analysis** | AI across multiple logs  | Correlates events and trends        | Root cause analysis           |

### Basic AI Workflows

#### Single Log Analysis

**Use Case:** Understanding what a specific log entry means

```bash
# 1. Start Gonzo with AI enabled
gonzo -f application.log --ai-model="gpt-4"

# 2. Navigate to an interesting log entry
# Use ↑/↓ or mouse to select a log

# 3. Press 'i' for instant AI analysis
# Example log:
{"timestamp":"2024-01-15T10:30:05Z","level":"error","service":"payment","message":"Transaction failed: insufficient funds","user_id":"12345","amount":250.00,"account_balance":75.50}

# 4. AI provides analysis like:
```

**Example AI Response:**

```
This payment transaction failure is a business logic error, not a technical issue. 

Key details:
- User 12345 attempted a $250 transaction
- Account balance is only $75.50  
- System correctly prevented overdraft

This is normal application behavior - the user simply has insufficient funds. However, you should verify:

1. Balance calculation is accurate
2. User was notified of insufficient funds
3. No retry loops are occurring
4. Consider if this pattern indicates UI/UX issues (users not seeing balance before purchase)

Not a system error requiring technical intervention.
```

#### Interactive AI Conversation

**Use Case:** Deep investigation of complex issues

```bash
# 1. Select a log entry and press 'Enter' for details
# 2. Press 'c' to start AI chat
# 3. Have a natural conversation about the logs

# Example conversation:
```

**Example AI Chat Session:**

```
You: Why are we seeing so many payment failures?

AI: I see 47 payment failures in the last hour. The pattern breaks down as:
- 23 insufficient funds (normal user behavior)  
- 18 card declined (bank/card issues)
- 6 system timeouts (technical issue requiring attention)

The system timeouts are concerning and started 20 minutes ago.

You: What's causing the system timeouts?

AI: The timeout pattern correlates with database slow query warnings that started at the same time. I see:
- Payment queries taking 8-12 seconds (normally <1 second)
- Database connection pool showing high utilization
- No infrastructure alerts, suggesting query performance issue

Recommended investigation: Check for long-running queries, missing indexes, or table locks in the payment database.

You: Show me what to look for in the database

AI: Here's your investigation checklist:

1. Current active queries:
   SELECT * FROM pg_stat_activity WHERE state = 'active';

2. Slow queries in logs:
   Look for payment-related queries >5 seconds

3. Lock analysis:
   SELECT * FROM pg_locks WHERE NOT granted;

4. Recent schema changes:
   Check if indexes were dropped or tables altered

The timing suggests a recent change triggered this performance degradation.
```

#### Model Optimization Workflow

**Use Case:** Balancing cost, speed, and quality

```bash
# 1. Start with a fast, cost-effective model
gonzo -f logs.log --ai-model="gpt-3.5-turbo"

# 2. For basic questions, this model is sufficient
# Press 'i' on routine logs, get quick insights

# 3. When you encounter complex issues, switch models
# Press 'm' → Select "gpt-4" → Continue analysis

# 4. Use the better model for deeper investigation
# Press 'c' for complex conversations with gpt-4

# 5. Switch back to cheaper model for routine monitoring
# Press 'm' → Select "gpt-3.5-turbo" → Continue
```

### Advanced AI Techniques

#### Multi-Log Correlation Analysis

**Technique:** Use AI to understand relationships across multiple log entries

```bash
# 1. Filter logs for a specific timeframe or issue
/2024-01-15.*14:[2-3][0-9]  # 2:20-2:39 PM timeframe

# 2. Use AI analysis on multiple entries
# Navigate through filtered logs, press 'i' on several entries

# 3. Start AI chat to correlate findings
# Press 'c' and ask: "What patterns do you see across these logs?"

# 4. AI will identify cross-log relationships:
```

**Example Correlation Analysis:**

```
You: What patterns do you see across these filtered logs?

AI: Analyzing the 2:20-2:39 PM timeframe, I see a clear cascade failure pattern:

Timeline of events:
2:22 PM - Database connection pool exhaustion begins
2:23 PM - API gateway starts returning 503 errors  
2:24 PM - Authentication service becomes unresponsive
2:25 PM - Load balancer fails health checks
2:26 PM - Auto-scaling triggers but fails to help

Root cause: Database connection pool exhaustion triggered a system-wide cascade failure. The auto-scaling didn't help because the bottleneck was database connections, not compute capacity.

Recovery actions taken:
- 2:35 PM - Database connections manually reset
- 2:37 PM - Services began recovering
- 2:39 PM - Full system recovery

Prevention: Implement circuit breakers and better connection pool monitoring.
```

#### AI-Enhanced Pattern Recognition

**Technique:** Combine Gonzo's pattern detection with AI interpretation

```bash
# 1. Open the Counts panel analysis modal
# Press Enter on Counts panel (bottom-right)

# 2. Review the pattern analysis
# Note the top patterns detected by drain3 algorithm

# 3. Use AI to interpret patterns
# Press 'i' on logs matching interesting patterns
# Ask AI: "Why is this pattern significant?"

# 4. Get intelligent pattern interpretation:
```

**Example Pattern Interpretation:**

```
Detected Pattern: "User <ID> authentication failed from IP <IP>"
Occurrences: 234 in last hour

AI Analysis: This pattern indicates a distributed brute force attack:

Attack characteristics:
- 234 failed attempts across 67 different IPs
- Targeting multiple user accounts (87 unique user IDs)
- Geographic distribution suggests botnet usage
- Rate: ~4 attempts per minute (automated, not human)

Immediate actions:
1. Implement rate limiting on authentication endpoint
2. Consider geographic IP blocking
3. Enable account lockout after N failed attempts
4. Alert security team about coordinated attack

This is not a system error - it's a security incident requiring immediate attention.
```

#### Predictive Analysis Workflow

**Technique:** Use AI to identify trends and predict future issues

```bash
# 1. Analyze trends over time
# Use time-series data from Counts panel
# Look for growing patterns in heatmap

# 2. Ask AI about trend implications
# Press 'c' and describe what you see:
# "I see increasing error rates over the last 2 hours"

# 3. Get predictive insights:
```

**Example Predictive Analysis:**

```
You: I see error rates increasing steadily over the last 2 hours. What should I expect?

AI: Based on the escalating pattern, you're heading toward a system overload scenario:

Current trend analysis:
- Error rate: 5/min → 15/min → 25/min (exponential growth)
- Memory warnings appearing more frequently
- Database query times increasing linearly
- Cache hit rate declining steadily

Projected timeline if no intervention:
- Next 30 minutes: Error rate will likely reach 40-50/min
- Within 1 hour: Expect system timeouts and user impact
- Critical threshold: ~60 errors/min (based on historical data)

Recommended immediate actions:
1. Scale database connections NOW (don't wait for critical threshold)
2. Implement circuit breakers to prevent cascade failures
3. Consider temporary rate limiting to reduce load
4. Alert on-call team - intervention needed within 30 minutes

The pattern suggests underlying capacity issues that will require architectural changes long-term.
```

### AI Feature Deep Dive

#### Intelligent Log Analysis (`i` key)

**What AI Analyzes:**

* **Error significance** - Is this a critical error or expected behavior?
* **Context understanding** - What was happening when this occurred?
* **Impact assessment** - How does this affect users/system?
* **Investigation guidance** - What should you check next?
* **Pattern recognition** - Is this part of a larger issue?

**Optimizing AI Analysis:**

```bash
# Provide context for better analysis
# Instead of analyzing isolated logs, filter for relevant timeframe:
/2024-01-15.*15:[1-2][0-9]  # Focus on incident timeframe

# Then use AI analysis on logs within that context
# AI will provide more relevant insights with proper context
```

**AI Analysis Types:**

{% tabs %}
{% tab title="Error Analysis" %}
**For error-level logs, AI focuses on:**

```
Technical Details:
- What specific error occurred
- Likely root causes
- System components involved
- Data/state that might be corrupted

Business Impact:
- User experience effects
- Revenue/functionality impact
- Urgency level assessment
- Customer communication needs

Investigation Steps:
- What to check first
- Related systems to examine
- Logs/metrics to correlate
- Tools/commands to run

Prevention:
- How to prevent recurrence
- Monitoring improvements
- Code/config changes needed
- Process improvements
```

{% endtab %}

{% tab title="Performance Analysis" %}
**For performance-related logs, AI examines:**

```
Performance Metrics:
- Response time analysis
- Resource utilization patterns
- Throughput characteristics
- Bottleneck identification

Capacity Planning:
- Current vs optimal performance
- Scaling recommendations
- Resource allocation guidance
- Infrastructure optimization

Optimization Opportunities:
- Code efficiency improvements
- Database query optimization
- Caching strategies
- Architecture improvements

Monitoring Enhancements:
- Additional metrics to track
- Alert threshold recommendations
- Dashboard improvements
- SLA/SLO considerations
```

{% endtab %}

{% tab title="Security Analysis" %}
**For security-related logs, AI identifies:**

```
Security Events:
- Attack pattern recognition
- Threat level assessment
- Compromise indicators
- Data exposure risks

Response Actions:
- Immediate containment steps
- Investigation procedures
- Evidence preservation
- Communication requirements

Prevention Strategies:
- Security control improvements
- Policy/process enhancements
- Technology recommendations
- Training needs

Compliance Considerations:
- Regulatory requirements
- Audit trail preservation
- Notification obligations
- Documentation needs
```

{% endtab %}
{% endtabs %}

#### Interactive AI Chat (`c` key)

**Chat Best Practices:**

```bash
# 1. Start with specific questions
"What caused this database timeout?"

# 2. Build on AI responses
"You mentioned connection pooling - how do I check pool status?"

# 3. Ask for actionable guidance
"What specific commands should I run to investigate this?"

# 4. Request prioritization
"Which of these issues should I fix first?"

# 5. Get prevention advice
"How can I prevent this type of issue in the future?"
```

**Advanced Chat Techniques:**

```bash
# Multi-turn investigation
You: "Analyze this error pattern"
AI: [Provides analysis]
You: "What's the business impact?"
AI: [Explains user/revenue impact]
You: "Give me a 5-minute action plan"
AI: [Provides prioritized steps]
You: "Draft an incident summary for stakeholders"
AI: [Creates stakeholder communication]
```

#### Model Switching (`m` key)

**Strategic Model Usage:**

| Scenario              | Recommended Model | Reasoning                                 |
| --------------------- | ----------------- | ----------------------------------------- |
| **Quick checks**      | gpt-3.5-turbo     | Fast, cost-effective for simple questions |
| **Complex debugging** | gpt-4             | Better reasoning for root cause analysis  |
| **Large context**     | gpt-4-turbo       | Handles extensive log context             |
| **Privacy-sensitive** | Local model       | Keeps data on your infrastructure         |
| **High volume**       | Local model       | No API costs for extensive analysis       |

**Model Switching Workflow:**

```bash
# 1. Start monitoring with fast model
gonzo -f logs.log --follow --ai-model="gpt-3.5-turbo"

# 2. When issues arise, upgrade model quality
# Press 'm' → Select "gpt-4"

# 3. Conduct deep analysis with better model
# Use AI chat for complex investigation

# 4. Return to monitoring mode
# Press 'm' → Select "gpt-3.5-turbo"

# 5. Save expensive model for critical issues only
```

### Real-World AI Workflows

#### Production Incident Response

**Scenario:** Critical production issue requiring rapid resolution

```bash
# Phase 1: Rapid Assessment (2-3 minutes)
gonzo -f /var/log/prod/*.log --follow --ai-model="gpt-4"

# 1. Identify scope and timing
# Filter to incident timeframe: /2024-01-15.*14:[1-3][0-9]

# 2. Get AI overview of situation
# Press 'i' on error logs: "What's the severity and scope?"

# 3. Quick impact assessment
# Press 'c': "How many users are affected and what's broken?"

# Phase 2: Root Cause Analysis (5-10 minutes)
# 4. Deep dive with AI
# "Walk me through what happened step by step"

# 5. Get investigation plan
# "What should I check first to resolve this?"

# Phase 3: Resolution Guidance (ongoing)
# 6. Implementation assistance
# "How do I safely implement this fix?"

# 7. Validation guidance
# "How will I know if the fix worked?"
```

#### Development Debugging Session

**Scenario:** Complex bug investigation during development

```bash
# Setup: Development environment with detailed logging
gonzo -f logs/debug.log --follow --ai-model="gpt-3.5-turbo"

# 1. Reproduce issue while monitoring
# AI continuously analyzes logs as they appear

# 2. Focus on anomalies
# Press 'i' on unusual log entries during reproduction

# 3. Build understanding through conversation
# Press 'c': "What's different about this execution vs normal?"

# 4. Get debugging strategy
# "What's the most efficient way to isolate this bug?"

# 5. Validate hypotheses
# "Does this log pattern support the theory that...?"

# 6. Solution guidance
# "What's the safest way to implement this fix?"
```

#### Security Monitoring Workflow

**Scenario:** Continuous security monitoring with AI assistance

```bash
# Setup: Security-focused monitoring
gonzo -f /var/log/auth.log -f /var/log/nginx/access.log --follow --ai-model="gpt-4"

# 1. Filter for security events
/(fail|denied|blocked|suspicious|attack|breach)/i

# 2. AI assessment of security events
# Press 'i' on security-related logs for threat analysis

# 3. Pattern recognition
# Press 'c': "Are these isolated incidents or part of a campaign?"

# 4. Response prioritization
# "Which of these events requires immediate attention?"

# 5. Investigation guidance
# "What additional data should I collect for this incident?"

# 6. Prevention recommendations
# "How can I prevent this type of attack?"
```

### AI Performance Optimization

#### Context Management

**Optimize AI responses with better context:**

```bash
# Instead of: Analyzing random individual logs
# Do this: Filter first, then analyze
/error.*database.*timeout  # Focus AI on specific issue type

# Instead of: Asking vague questions
# Do this: Provide specific context
"This database timeout started after the 2 PM deployment - what should I check?"

# Instead of: Single log analysis
# Do this: Multi-log correlation
"Compare these three error patterns and tell me if they're related"
```

#### Cost Optimization Strategies

**Balance AI quality with cost:**

```bash
# Development: Use cheaper models
export GONZO_DEV_MODEL="gpt-3.5-turbo"
alias gonzo-dev='gonzo --ai-model="$GONZO_DEV_MODEL"'

# Production monitoring: Balanced approach
export GONZO_MONITOR_MODEL="gpt-3.5-turbo"
alias gonzo-monitor='gonzo --ai-model="$GONZO_MONITOR_MODEL"'

# Incident response: Use premium models
export GONZO_INCIDENT_MODEL="gpt-4"
alias gonzo-incident='gonzo --ai-model="$GONZO_INCIDENT_MODEL"'

# High-volume analysis: Local models
export GONZO_LOCAL_MODEL="llama3"
alias gonzo-local='OPENAI_API_BASE="http://localhost:11434" gonzo --ai-model="$GONZO_LOCAL_MODEL"'
```

#### Quality Optimization

**Get better AI insights:**

```bash
# 1. Use specific, targeted questions
# Instead of: "What's wrong?"
# Ask: "Why did the authentication service start timing out at 2 PM?"

# 2. Provide business context
# "This is our payment system - what's the user impact of these errors?"

# 3. Ask for actionable guidance
# "Give me the top 3 investigation steps in priority order"

# 4. Request specific formats
# "Create a timeline of events from these logs"
# "Draft an incident report for stakeholders"
# "List the exact commands I should run"
```

### Advanced AI Integration Patterns

#### AI + Pattern Detection

**Combine Gonzo's algorithms with AI interpretation:**

```bash
# 1. Use Counts panel for pattern detection
# Press Enter on Counts panel → Review drain3 patterns

# 2. Apply AI to interpret patterns
# Filter by pattern: /pattern.*from.*analysis
# Press 'i': "Why is this pattern significant?"

# 3. Get pattern evolution insights
# Press 'c': "Is this pattern getting worse over time?"

# 4. Predictive pattern analysis
# "Based on this pattern trend, what should I expect?"
```

#### AI + Time-Series Analysis

**Enhance heatmap analysis with AI insights:**

```bash
# 1. Review time-series heatmap in Counts modal
# Identify interesting time periods and intensity patterns

# 2. Filter logs to specific time periods
# /2024-01-15.*1[4-5]:[0-9]{2}  # Focus on 2-6 PM

# 3. Ask AI about timing correlations
# Press 'c': "What caused the error spike at 3 PM?"

# 4. Get predictive timeline analysis
# "Based on this trend, when will we hit critical thresholds?"
```

#### AI + Multi-Source Correlation

**Use AI to understand relationships across log sources:**

```bash
# 1. Monitor multiple related sources
gonzo -f api.log -f db.log -f cache.log --follow --ai-model="gpt-4"

# 2. Filter for specific incident timeframe
/2024-01-15.*15:[2-4][0-9]/

# 3. Ask AI to correlate across sources
# Press 'c': "How do these three services relate in this incident?"

# 4. Get cascade failure analysis
# "Which service failed first and how did it cascade?"

# 5. Architecture improvement recommendations
# "How can we prevent this type of cascade failure?"
```

### Troubleshooting AI Features

#### Common AI Issues

**AI Analysis Not Working:**

```bash
# Check AI configuration
echo $OPENAI_API_KEY
echo $OPENAI_API_BASE

# Test AI connectivity
gonzo -f test.log --ai-model="gpt-3.5-turbo" --test-mode

# Verify model availability
# Press 'm' to see available models
```

**Poor AI Response Quality:**

```bash
# 1. Provide more context
# Filter logs first: /specific.*error.*pattern
# Then ask specific questions

# 2. Use better models for complex analysis
# Press 'm' → Switch to "gpt-4"

# 3. Ask follow-up questions
# "Can you be more specific about the root cause?"
# "What exact commands should I run?"
```

**AI Responses Too Slow:**

```bash
# 1. Use faster models
# Press 'm' → Switch to "gpt-3.5-turbo"

# 2. Reduce context size
# Filter logs to smaller timeframes
# Ask more focused questions

# 3. Check network connectivity (cloud models)
ping api.openai.com

# 4. Monitor local resources (local models)
htop  # Check CPU/memory usage
```

#### Optimizing AI Workflows

**Best Practices:**

```bash
# 1. Filter before analyzing
# Reduce noise with targeted filters: /error.*payment/

# 2. Start broad, then narrow
# "What types of errors do you see?" → "Focus on payment errors"

# 3. Ask for actionable outputs
# "Give me a runbook for this issue"
# "Create a timeline I can share with stakeholders"

# 4. Validate AI insights
# Cross-check AI conclusions with data
# Ask AI to explain its reasoning
```

### What's Next?

You've now mastered AI-powered log analysis! Continue exploring:

* **Log Analysis** - Combine AI with algorithmic pattern detection
* **Format Detection** - Optimize log parsing for better AI analysis
* **Configuration** - Set up AI-specific configurations
* **Integration Examples** - Apply AI features to real-world scenarios

Or start using AI features immediately in your daily workflows:

```bash
# Start your AI-enhanced log analysis session
gonzo -f your-production-logs.log --follow --ai-model="gpt-4"

# Remember the key AI shortcuts:
# 'i' - Analyze any log entry
# 'c' - Start AI conversation
# 'm' - Switch AI models
```

***

**You're now equipped with AI superpowers for log analysis!** 🤖 From rapid incident response to deep debugging sessions, AI transforms complex log investigation into intelligent, guided analysis that helps you solve problems faster and more effectively.


# Format Detection

Gonzo's intelligent format detection automatically recognizes and parses different log formats, extracting structured data for powerful analysis. From JSON to plain text, Gonzo adapts to your logs without configuration.

{% hint style="info" %}
**Automatic Operation:** Format detection works automatically - no configuration required. Gonzo analyzes each log entry and applies the appropriate parsing strategy in real-time.
{% endhint %}

### Supported Log Formats

Gonzo intelligently detects and processes multiple log formats simultaneously:

| Format            | Detection Method    | Structured Data         | Best For                              |
| ----------------- | ------------------- | ----------------------- | ------------------------------------- |
| **JSON**          | Valid JSON syntax   | Complete object parsing | Modern applications, microservices    |
| **Logfmt**        | Key=value pairs     | Field extraction        | Go applications, Heroku-style logs    |
| **Plain Text**    | Pattern recognition | Smart field extraction  | Traditional applications, system logs |
| **Mixed Formats** | Per-line analysis   | Format-specific parsing | Legacy systems, log aggregation       |

### JSON Log Format

#### Automatic JSON Detection

Gonzo automatically detects JSON logs and extracts all fields:

```json
{
  "timestamp": "2024-01-15T10:30:00Z",
  "level": "error",
  "service": "payment-api",
  "message": "Database connection timeout",
  "user_id": "12345",
  "request_id": "req_abc123",
  "duration": 30000,
  "endpoint": "/api/payment/process",
  "error": {
    "type": "TimeoutError",
    "details": "Connection pool exhausted"
  },
  "metadata": {
    "trace_id": "trace_xyz789",
    "span_id": "span_456def"
  }
}
```

**What Gonzo Extracts:**

* **All top-level fields** appear in Attributes panel
* **Nested objects** are flattened (e.g., `error.type`, `metadata.trace_id`)
* **Arrays** are handled intelligently
* **Data types** are preserved (strings, numbers, booleans)

#### JSON Processing Features

{% tabs %}
{% tab title="Field Extraction" %}
**Automatic Field Detection:**

```
Attributes Panel Shows:
├── timestamp = "2024-01-15T10:30:00Z"
├── level = "error"  
├── service = "payment-api"
├── message = "Database connection timeout"
├── user_id = "12345"
├── request_id = "req_abc123"
├── duration = 30000
├── endpoint = "/api/payment/process"
├── error.type = "TimeoutError"
├── error.details = "Connection pool exhausted"
├── metadata.trace_id = "trace_xyz789"
└── metadata.span_id = "span_456def"
```

**Search and Filter by Fields:**

```bash
# Filter by any extracted field
/"level":"error"
/"service":"payment-api"
/"user_id":"12345"
/error\.type.*Timeout
/metadata\.trace_id.*xyz789
```

{% endtab %}

{% tab title="Nested Object Handling" %}
**Deep Object Parsing:**

```json
{
  "request": {
    "method": "POST",
    "url": "/api/users",
    "headers": {
      "authorization": "Bearer token123",
      "content-type": "application/json"
    },
    "body": {
      "user": {
        "name": "John Doe",
        "email": "john@example.com"
      }
    }
  }
}
```

**Flattened in Attributes:**

```
request.method = "POST"
request.url = "/api/users"  
request.headers.authorization = "Bearer token123"
request.headers.content-type = "application/json"
request.body.user.name = "John Doe"
request.body.user.email = "john@example.com"
```

{% endtab %}

{% tab title="Array Processing" %}
**Array Handling:**

```json
{
  "errors": ["validation failed", "missing field"],
  "tags": ["production", "critical", "database"],
  "users": [
    {"id": 1, "name": "Alice"},
    {"id": 2, "name": "Bob"}
  ]
}
```

**Array Representation:**

```
errors[0] = "validation failed"
errors[1] = "missing field"
tags[0] = "production"
tags[1] = "critical"
tags[2] = "database"
users[0].id = 1
users[0].name = "Alice"
users[1].id = 2
users[1].name = "Bob"
```

{% endtab %}
{% endtabs %}

#### JSON Best Practices

**Optimize Your JSON Logs:**

```json
{
  // ✅ Good: Consistent field naming
  "timestamp": "2024-01-15T10:30:00Z",
  "level": "error",
  "service": "payment-api",
  "message": "Clear, descriptive message",
  
  // ✅ Good: Structured context
  "context": {
    "user_id": "12345",
    "request_id": "req_abc123",
    "trace_id": "trace_xyz789"
  },
  
  // ✅ Good: Consistent data types
  "duration": 1500,           // Number, not string
  "success": false,           // Boolean, not "false"
  "retry_count": 3,           // Number for analysis
  
  // ❌ Avoid: Inconsistent field names
  // Sometimes "userId", sometimes "user_id", sometimes "UserID"
  
  // ❌ Avoid: Everything as strings
  // "duration": "1500ms" instead of duration: 1500
}
```

### Logfmt Format

#### Automatic Logfmt Detection

Gonzo detects logfmt (key=value) format commonly used by Go applications:

```
time=2024-01-15T10:30:00Z level=error service=payment-api msg="Database connection timeout" user_id=12345 request_id=req_abc123 duration=30000ms endpoint="/api/payment/process" error="connection pool exhausted" trace_id=trace_xyz789
```

**Parsing Features:**

* **Key-value extraction** - All key=value pairs become searchable fields
* **Quoted value support** - Handles `msg="complex message with spaces"`
* **Type inference** - Numbers and booleans detected automatically
* **Space handling** - Robust parsing of various spacing patterns

#### Logfmt Processing Examples

{% tabs %}
{% tab title="Basic Parsing" %}
**Input Logfmt:**

```
level=info service=web-api method=GET path=/health status=200 duration=45ms
```

**Extracted Attributes:**

```
level = "info"
service = "web-api"  
method = "GET"
path = "/health"
status = 200
duration = "45ms"
```

**Filtering Examples:**

```bash
level=error                    # Error level logs
service=web-api               # Specific service
method=POST                   # POST requests only
status=[45][0-9]{2}           # 4xx and 5xx status codes
duration=[1-9][0-9]+ms        # Duration > 10ms
```

{% endtab %}

{% tab title="Complex Values" %}
**Quoted String Handling:**

```
time=2024-01-15T10:30:00Z level=error msg="User authentication failed: invalid token format" user_id=12345 ip="192.168.1.100" user_agent="Mozilla/5.0 (compatible; bot)"
```

**Parsed Results:**

```
time = "2024-01-15T10:30:00Z"
level = "error"
msg = "User authentication failed: invalid token format"
user_id = 12345
ip = "192.168.1.100"
user_agent = "Mozilla/5.0 (compatible; bot)"
```

**Special Character Support:**

* Handles spaces in quoted values
* Escapes quotes within values
* Supports empty values: `key=""`
* Handles special characters in keys and values
  {% endtab %}

{% tab title="Mixed Data Types" %}
**Type Inference:**

```
level=warn count=42 rate=3.14 enabled=true disabled=false empty="" path="/api/users"
```

**Detected Types:**

```
level = "warn"        # String
count = 42           # Number (integer)
rate = 3.14          # Number (float)
enabled = true       # Boolean
disabled = false     # Boolean  
empty = ""           # Empty string
path = "/api/users"  # String
```

**Benefits for Analysis:**

* Numeric fields enable mathematical comparisons
* Boolean fields allow true/false filtering
* Type-aware searching and sorting
  {% endtab %}
  {% endtabs %}

#### Logfmt Optimization Tips

**Structure Your Logfmt Logs:**

```go
// ✅ Good: Consistent key naming
log.Info("Request processed",
    "service", "web-api",
    "method", "POST", 
    "path", "/api/users",
    "status", 201,
    "duration", time.Since(start),
    "user_id", userID,
    "request_id", requestID,
)

// ✅ Good: Use structured context
log.Error("Database error",
    "error", err.Error(),
    "query", "SELECT * FROM users WHERE id = ?",
    "query_duration", queryTime,
    "connection_pool_size", poolSize,
    "active_connections", activeConns,
)

// ❌ Avoid: Inconsistent formatting
// Sometimes: user_id=123
// Sometimes: userId=123  
// Sometimes: UserID=123
```

### Plain Text Format

#### Intelligent Plain Text Processing

Gonzo analyzes plain text logs and extracts structured information using pattern recognition:

```
2024-01-15 10:30:00 [ERROR] payment-api: Database connection timeout for user 12345 (duration: 30000ms, endpoint: /api/payment/process)
```

**Automatic Extraction:**

* **Timestamp detection** - Various timestamp formats
* **Log level identification** - ERROR, WARN, INFO, DEBUG, etc.
* **Service name extraction** - Service or component names
* **Contextual information** - IDs, durations, endpoints extracted via patterns

#### Plain Text Pattern Recognition

{% tabs %}
{% tab title="Timestamp Patterns" %}
**Supported Timestamp Formats:**

```bash
# ISO 8601 formats
2024-01-15T10:30:00Z
2024-01-15T10:30:00.123Z
2024-01-15 10:30:00

# Common log formats  
Jan 15 10:30:00
15/Jan/2024:10:30:00
2024-01-15 10:30:00.123

# Syslog formats
Jan 15 10:30:00
<134>Jan 15 10:30:00

# Custom formats (auto-detected)
[2024-01-15 10:30:00]
(2024-01-15 10:30:00)
```

**What Gonzo Extracts:**

* Normalizes all timestamps for time-series analysis
* Maintains original format in log display
* Enables time-based filtering and sorting
  {% endtab %}

{% tab title="Log Level Detection" %}
**Recognized Log Levels:**

```bash
# Standard levels (case-insensitive)
ERROR, ERR, E
WARN, WARNING, W
INFO, I
DEBUG, DBG, D
TRACE, T
FATAL, F

# Bracketed formats
[ERROR], [WARN], [INFO]
(ERROR), (WARN), (INFO)

# Prefixed formats  
ERROR:, WARN:, INFO:
ERR-, WARN-, INFO-

# Numeric levels
0 (Emergency), 1 (Alert), 2 (Critical)
3 (Error), 4 (Warning), 5 (Notice)
6 (Info), 7 (Debug)
```

**Color Coding:**

* All detected levels get appropriate color coding
* Consistent with JSON/logfmt level handling
* Enables severity-based filtering
  {% endtab %}

{% tab title="Service Extraction" %}
**Service Name Patterns:**

```bash
# Common service patterns Gonzo recognizes:

# After timestamp and level
2024-01-15 10:30:00 [ERROR] web-api: message
2024-01-15 10:30:00 ERROR web-api: message

# In brackets/parentheses
2024-01-15 10:30:00 [web-api] ERROR: message
2024-01-15 10:30:00 (web-api) ERROR: message

# Colon-separated
web-api: 2024-01-15 10:30:00 ERROR message
web-api ERROR: message

# Structured prefixes
[service=web-api] ERROR: message
service:web-api ERROR: message
```

**Service Distribution:**

* Extracted service names appear in service distribution analysis
* Enables service-based filtering
* Supports multi-service correlation
  {% endtab %}
  {% endtabs %}

#### Enhanced Plain Text Processing

**Contextual Information Extraction:**

```bash
# Gonzo automatically extracts common patterns:

# User IDs
"user 12345", "user_id: 12345", "uid=12345"
→ Extracted as user context

# Request IDs  
"request abc123", "req_id: abc123", "rid=abc123"
→ Extracted as request correlation

# Durations
"took 1500ms", "duration: 30s", "elapsed 2.5s"
→ Extracted as performance metrics

# HTTP Status
"status 404", "returned 500", "HTTP/1.1 200"
→ Extracted as response status

# IP Addresses
"from 192.168.1.100", "client 10.0.0.1"
→ Extracted as network context

# Error Codes
"error E001", "code TIMEOUT", "errno 404"
→ Extracted as error classification
```

### Mixed Format Handling

#### Multi-Format Log Sources

Gonzo handles mixed format sources intelligently:

```bash
# Example: Combined application and infrastructure logs
gonzo -f app.log -f nginx.log -f syslog --follow

# app.log (JSON format):
{"timestamp":"2024-01-15T10:30:00Z","level":"error","service":"app","message":"DB timeout"}

# nginx.log (Combined Log Format):
192.168.1.100 - - [15/Jan/2024:10:30:00 +0000] "GET /api/users HTTP/1.1" 504 0

# syslog (Traditional format):
Jan 15 10:30:00 server01 app[1234]: Database connection failed
```

**Per-Line Format Detection:**

* Each log line analyzed independently
* Appropriate parser applied automatically
* Consistent field extraction across formats
* Unified analysis in Attributes panel

#### Format Transition Handling

**Real-World Scenario:** Application log format changes over time

```bash
# Old format (plain text):
2024-01-15 10:29:59 ERROR: Database connection failed

# Transition period (mixed):
2024-01-15 10:30:00 ERROR: Starting JSON logging
{"timestamp":"2024-01-15T10:30:01Z","level":"info","message":"JSON logging active"}

# New format (JSON):
{"timestamp":"2024-01-15T10:30:02Z","level":"error","message":"Database timeout","duration":30000}
```

**Gonzo Handles This Seamlessly:**

* Detects format change automatically
* Continues processing without interruption
* Maintains consistent analysis across formats
* No configuration changes required

### Format Detection Optimization

#### Performance Considerations

**Optimizing Format Detection:**

```bash
# For high-volume logs, format detection adds minimal overhead:
# JSON: ~0.1ms per line (fastest)
# Logfmt: ~0.2ms per line  
# Plain text: ~0.5ms per line (most complex patterns)

# Monitor performance impact:
time gonzo -f large-log-file.log --test-mode

# Optimize for known formats:
# If you know your logs are JSON, ensure valid JSON syntax
# If using logfmt, follow consistent key=value patterns
# For plain text, use consistent timestamp/level patterns
```

#### Memory Usage Optimization

**Field Extraction Memory Management:**

```bash
# Gonzo automatically manages memory for extracted fields:
# - Limits number of unique field names tracked
# - Uses efficient string interning for repeated values
# - Automatically garbage collects old field data

# Monitor memory usage:
ps aux | grep gonzo

# Tune memory limits if needed:
gonzo -f logs.log --memory-size=20000  # Increase field storage
gonzo -f logs.log --memory-size=5000   # Reduce for constrained systems
```

### Format-Specific Features

#### JSON-Specific Enhancements

**Advanced JSON Processing:**

```bash
# Schema Evolution Detection
# Gonzo adapts when JSON schema changes:
# - New fields appear automatically in Attributes
# - Removed fields don't break processing
# - Type changes are handled gracefully

# Performance Optimization for JSON:
# - Streaming JSON parser for large objects
# - Lazy field extraction (only parse displayed fields)
# - Efficient handling of repeated field names
```

#### Logfmt-Specific Enhancements

**Logfmt Processing Optimizations:**

```bash
# Key Standardization
# Gonzo normalizes key variations:
# user_id, userId, UserID → unified for analysis

# Value Type Inference
# Automatic detection of:
# - ISO timestamps
# - Duration formats (1s, 500ms, 2h30m)
# - Size formats (1KB, 2MB, 1.5GB)
# - Boolean variations (true/false, yes/no, 1/0)
```

#### Plain Text Intelligence

**Advanced Pattern Learning:**

```bash
# Gonzo learns from your log patterns:
# - Adapts to your specific timestamp formats
# - Recognizes custom log level naming
# - Learns service name patterns
# - Extracts domain-specific identifiers

# Custom Pattern Support:
# While automatic, you can influence detection:
# - Use consistent formatting for better recognition
# - Include context clues (brackets, colons, equals signs)
# - Maintain consistent field ordering
```

### Troubleshooting Format Detection

#### Common Issues and Solutions

**Field Not Extracted:**

```bash
# Issue: Expected field doesn't appear in Attributes panel
# Solutions:

# 1. Check log format consistency
# Ensure: {"user_id": "123"}  # Consistent naming
# Avoid: {"userId": "123"} then {"user_id": "123"}  # Mixed naming

# 2. Verify JSON validity
echo '{"test": "value"}' | gonzo  # Test with simple JSON

# 3. Check logfmt syntax
echo 'level=info msg="test message"' | gonzo  # Verify parsing

# 4. Review plain text patterns
# Use consistent timestamp and level formats
```

**Performance Issues:**

```bash
# Issue: Slow processing with format detection
# Solutions:

# 1. Check for malformed logs
# Invalid JSON can slow parsing significantly
grep -v '^{' json.log  # Find non-JSON lines in JSON logs

# 2. Optimize log structure
# Avoid deeply nested objects in JSON
# Use consistent field ordering in logfmt

# 3. Monitor resource usage
htop  # Check CPU/memory during processing

# 4. Adjust buffer sizes
gonzo -f logs.log --log-buffer=2000  # Smaller buffer for memory
gonzo -f logs.log --update-interval=5s  # Slower updates
```

**Mixed Format Confusion:**

```bash
# Issue: Wrong format detection on some lines
# Solutions:

# 1. Separate by format when possible
# JSON logs: gonzo -f app-json.log
# Plain text: gonzo -f app-text.log

# 2. Use format-specific tools for preprocessing
# Clean data before Gonzo analysis
grep '^{' mixed.log | gonzo  # JSON lines only

# 3. Verify line endings and encoding
file log-file.log  # Check file encoding
dos2unix log-file.log  # Fix Windows line endings
```

### Best Practices

#### 🎯 **Optimize Log Format Design**

1. **Choose appropriate formats** - JSON for rich structure, logfmt for simplicity, plain text for human readability
2. **Maintain consistency** - Use the same field names, timestamp formats, and log levels across your application
3. **Include context** - Always include request IDs, user IDs, and correlation identifiers
4. **Structure your data** - Group related fields in objects (JSON) or use consistent prefixes (logfmt)

#### 📊 **Maximize Analysis Value**

1. **Use structured logging** - JSON and logfmt provide much richer analysis than plain text
2. **Include performance metrics** - Add duration, memory usage, and other quantitative data
3. **Add business context** - Include user IDs, feature flags, and business-relevant information
4. **Maintain type consistency** - Use numbers for numeric data, booleans for flags

#### ⚡ **Performance Optimization**

1. **Validate JSON syntax** - Invalid JSON significantly slows processing
2. **Use consistent patterns** - Helps Gonzo optimize parsing strategies
3. **Avoid extreme nesting** - Deep JSON objects can impact performance
4. **Monitor resource usage** - Adjust buffer sizes based on log volume and system capacity

#### 🔍 **Debugging Format Issues**

1. **Test with small samples** - Verify format detection with simple examples
2. **Check encoding and line endings** - Ensure logs are UTF-8 with Unix line endings
3. **Monitor field extraction** - Verify expected fields appear in Attributes panel
4. **Use format-specific tools** - Validate JSON with `jq`, test logfmt patterns manually

### Real-World Format Examples

Learn how to create custom formats for popular tools:

* [Live Tailing Grafana Loki Logs with Gonzo](https://www.controltheory.com/blog/live-tailing-grafana-loki-logs-with-gonzo/) - Loki format integration

### What's Next?

Now that you understand format detection, explore how it enhances other Gonzo features:

* **Log Analysis** - Structured data improves pattern detection and analytics
* **AI Integration** - Better format detection provides richer context for AI analysis
* **Configuration** - Tune format detection settings for your specific logs
* **Integration Examples** - See format detection in real-world scenarios

Or start optimizing your log formats immediately:

```bash
# Test your current log formats
gonzo -f your-logs.log

# Check what fields are extracted in the Attributes panel
# Optimize your logging code based on what Gonzo detects
# Use structured formats (JSON/logfmt) for richer analysis
```

***

**You now understand how Gonzo intelligently processes any log format!** 🎯 From automatic JSON parsing to intelligent plain text recognition, format detection ensures you get maximum analytical value from any log source without manual configuration.


# Log Analysis

Discover patterns, trends, and anomalies in your logs with Gonzo's advanced analytical capabilities. From automatic pattern detection to time-series analysis, these features reveal insights that would be impossible to find manually.

{% hint style="info" %}
**Access Point:** Most log analysis features are accessed through the **Counts panel** (bottom-right). Press `Enter` on the Counts panel to open the detailed analysis modal.
{% endhint %}

### Analysis Overview

Gonzo's log analysis combines multiple sophisticated algorithms to provide comprehensive insights:

| Feature                   | Algorithm                | What It Reveals               | Best For                         |
| ------------------------- | ------------------------ | ----------------------------- | -------------------------------- |
| **Pattern Detection**     | Drain3 clustering        | Recurring log templates       | Finding common issues            |
| **Time-Series Analysis**  | 60-minute rolling window | Trends over time              | Understanding incident timing    |
| **Heatmap Visualization** | ASCII intensity mapping  | Activity patterns by severity | Visual pattern recognition       |
| **Service Distribution**  | Real-time aggregation    | Which services log what       | Multi-service debugging          |
| **Anomaly Detection**     | Statistical analysis     | Unusual patterns              | Proactive problem identification |

### The Analysis Dashboard

#### Counts Panel Overview

The Counts panel (bottom-right) provides your gateway to advanced analysis:

```
┌─ COUNTS ─────────────────────────────┐
│ Severity Distribution:               │
│ ERROR  █████████████████████   (45%) │
│ WARN   ██████████████          (30%) │
│ INFO   ███████                 (20%) │
│ DEBUG  ██                       (5%) │
│                                      │
│ Total Entries: 2,847                 │
│ Time Span: 2h 15m                    │
│ Entries/min: 21.2                    │
│ Pattern Count: 23                    │
│                                      │
│ Press Enter for detailed analysis... │
└─────────────────────────────────────┘
```

**Key Metrics Explained:**

* **Severity Distribution** - Percentage breakdown by log level with visual bars
* **Total Entries** - Count of all processed log entries in current session
* **Time Span** - Duration from first to last log entry
* **Entries/min** - Average logging frequency (useful for capacity planning)
* **Pattern Count** - Number of unique patterns detected by drain3 algorithm

#### Detailed Analysis Modal

Press `Enter` on the Counts panel to access the comprehensive analysis modal:

```
┌─ LOG ANALYSIS (Press ESC to close) ──────────────────────────────┐
│                                                                  │
│ Time-Series Heatmap (60-minute rolling window):                  │
│ ┌────────────────────────────────────────────────────────────┐   │
│ │Time: 60  50  40  30  20  10  0 (minutes ago)              │   │  
│ │ERROR ████░░██████░░░░████████████████ High intensity      │   │
│ │WARN  ░░██████░░████░░░░██████░░░░░░░░ Medium intensity    │   │
│ │INFO  ░░░░░░░░░░░░░░░░████░░░░░░░░░░░░ Low intensity       │   │
│ │DEBUG ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ Minimal activity    │   │
│ └────────────────────────────────────────────────────────────┘   │
│                                                                  │
│ Top 3 Patterns by Severity:                                     │
│ ┌────────────────────────────────────────────────────────────┐   │
│ │ ERROR:                                                     │   │
│ │ 1. Database connection timeout (247 occurrences)          │   │
│ │ 2. User authentication failed (156 occurrences)           │   │
│ │ 3. API rate limit exceeded (89 occurrences)               │   │
│ │                                                            │   │
│ │ WARN:                                                      │   │
│ │ 1. Slow query detected (324 occurrences)                  │   │
│ │ 2. Memory usage high (198 occurrences)                    │   │
│ │ 3. Cache miss rate elevated (156 occurrences)             │   │
│ └────────────────────────────────────────────────────────────┘   │
│                                                                  │
│ Service Distribution:                                            │
│ web-api: 1,247 entries (44%)  database: 892 entries (31%)      │
│ auth: 654 entries (23%)       cache: 54 entries (2%)           │
│                                                                  │
│ Navigation: ↑/↓ Scroll, Mouse Wheel, ESC to close               │
└──────────────────────────────────────────────────────────────────┘
```

### Time-Series Heatmap Analysis

#### Understanding the Heatmap

The time-series heatmap is one of Gonzo's most powerful visual analysis tools:

**Time Axis (Horizontal):**

* Shows last 60 minutes in 1-minute buckets
* Reading: `60` = 60 minutes ago, `0` = current minute
* Updates in real-time as new logs arrive

**Severity Axis (Vertical):**

* Each row represents a different log severity level
* Separate tracking for ERROR, WARN, INFO, DEBUG, etc.
* Independent scaling per severity level

**Intensity Indicators:**

```
░ = Low activity (1-25% of max for this severity)
▒ = Medium activity (25-50% of max)
▓ = High activity (50-75% of max)  
█ = Very high activity (75-100% of max)
```

#### Reading Heatmap Patterns

{% tabs %}
{% tab title="Incident Detection" %}
**Identifying When Problems Started:**

```
Time: 60  50  40  30  20  10  0
ERROR ░░░░░░░░████████████░░░░░░
WARN  ░░░░░░████████████████░░░░
```

**Analysis:**

* Problem started around 40 minutes ago
* Peak error activity 30-20 minutes ago
* Warnings preceded errors (early warning signs)
* System appears to be recovering now

**Use Case:** Incident timeline reconstruction
{% endtab %}

{% tab title="Performance Patterns" %}
**Daily Performance Cycles:**

```
Time: 60  50  40  30  20  10  0
ERROR ░░░░░░░░░░░░░░░░░░░░░░░░░░
WARN  ░░░░████░░░░████░░░░████░░
INFO  ████░░░░████░░░░████░░░░░░
```

**Analysis:**

* Regular 20-minute cycles in warnings
* High info activity alternating with warnings
* Suggests scheduled job or batch processing
* No critical errors, normal operational pattern

**Use Case:** Capacity planning and optimization
{% endtab %}

{% tab title="Cascade Failures" %}
**System Failure Propagation:**

```
Time: 60  50  40  30  20  10  0
ERROR ░░░░░░░░░░█░░██████████████
WARN  ░░░░░░░░█████████████████░
INFO  ░░░░░░████████████░░░░░░░░
```

**Analysis:**

* Single error triggered cascade
* Warnings spread quickly after initial error
* Info logs dropped off (services became unresponsive)
* Classic cascade failure pattern

**Use Case:** System resilience analysis
{% endtab %}
{% endtabs %}

#### Heatmap Best Practices

**🔍 Investigation Techniques:**

1. **Start wide, zoom in** - Look for obvious patterns first
2. **Compare severity levels** - How do different levels correlate?
3. **Identify inflection points** - When did patterns change?
4. **Look for cycles** - Are there recurring patterns?

**⚡ Quick Analysis:**

```bash
# Quick heatmap analysis workflow:
1. Press Enter on Counts panel
2. Scan heatmap for obvious spikes or patterns
3. Note correlation between severity levels
4. Identify time ranges for deeper investigation
5. Use time information to filter main log view
```

### Pattern Detection with Drain3

#### How Drain3 Works

Gonzo uses the Drain3 algorithm for automatic pattern detection:

**What Drain3 Does:**

* **Clusters similar log entries** into pattern templates
* **Extracts variable parts** (IDs, timestamps, values) from static text
* **Maintains pattern counts** in real-time
* **Adapts to new patterns** as they appear

**Example Pattern Detection:**

```bash
# Original log entries:
"User 12345 login failed"
"User 67890 login failed"  
"User 54321 login failed"

# Drain3 pattern:
"User <ID> login failed" (3 occurrences)
```

#### Pattern Analysis Features

**Top Patterns by Severity:**

In the analysis modal, patterns are grouped by severity level:

```
ERROR Patterns:
1. Database connection timeout (247 occurrences)
2. User authentication failed (156 occurrences)  
3. API rate limit exceeded (89 occurrences)

WARN Patterns:
1. Slow query detected (324 occurrences)
2. Memory usage high (198 occurrences)
3. Cache miss rate elevated (156 occurrences)
```

**What This Tells You:**

{% tabs %}
{% tab title="Problem Prioritization" %}
**Focus on High-Count Patterns:**

* **Database connection timeout (247)** - Critical infrastructure issue
* **User authentication failed (156)** - Security/user experience impact
* **Slow query detected (324)** - Performance degradation

**Analysis Priority:**

1. Address database connectivity first (highest error count)
2. Investigate authentication system second
3. Optimize slow queries for long-term performance
   {% endtab %}

{% tab title="Root Cause Analysis" %}
**Pattern Correlation:**

* **High slow query warnings** might be causing database timeouts
* **Memory usage warnings** could be related to query performance
* **Cache misses** might be increasing database load

**Investigation Path:**

1. Check if slow queries correlate with connection timeouts
2. Verify if memory pressure affects query performance
3. Analyze cache efficiency impact on database load
   {% endtab %}

{% tab title="Trend Analysis" %}
**Pattern Evolution:**

* Are certain patterns increasing over time?
* Do patterns appear in clusters or continuously?
* Are new patterns emerging that weren't seen before?

**Long-term Monitoring:**

* Track pattern counts over days/weeks
* Identify patterns that are growing vs shrinking
* Spot new issues before they become critical
  {% endtab %}
  {% endtabs %}

#### Working with Pattern Data

**Pattern-Based Filtering:**

Once you identify interesting patterns, use them for focused analysis:

```bash
# From analysis modal, identify pattern:
"Database connection timeout"

# Create filter in main view:
/database.*connection.*timeout

# Or use structured filtering:
/error.*database.*timeout
```

**Pattern Evolution Tracking:**

```bash
# Compare patterns over time:
# 1. Note current top patterns
# 2. Wait 30-60 minutes  
# 3. Check analysis modal again
# 4. See which patterns increased/decreased
# 5. Identify trends and new issues
```

### Service Distribution Analysis

#### Understanding Service Metrics

The service distribution section shows which services are generating logs:

```
Service Distribution:
web-api: 1,247 entries (44%)    database: 892 entries (31%)
auth: 654 entries (23%)         cache: 54 entries (2%)
```

**What This Reveals:**

| Metric               | Meaning                | Investigation Questions             |
| -------------------- | ---------------------- | ----------------------------------- |
| **High Percentage**  | Service is very active | Is this normal? Performance issue?  |
| **Low Percentage**   | Service is quiet       | Is it supposed to be active? Down?  |
| **Sudden Changes**   | Activity shift         | What caused the change?             |
| **Missing Services** | Service not logging    | Is it running? Configuration issue? |

#### Service-Based Analysis

{% tabs %}
{% tab title="Load Distribution" %}
**Normal Load Patterns:**

```
web-api: 45%    # Frontend traffic - high normal
database: 30%   # Backend queries - moderate normal  
auth: 20%       # Authentication - low-moderate normal
cache: 5%       # Cache operations - low normal
```

**Red Flags:**

* Database suddenly becomes 60%+ (performance issue)
* Auth drops to 0% (service down)
* New unknown service appears with high percentage
  {% endtab %}

{% tab title="Problem Service Identification" %}
**Troublesome Patterns:**

```
# Before incident:
web-api: 40%, database: 35%, auth: 20%, cache: 5%

# During incident:
database: 70%, web-api: 25%, auth: 3%, cache: 2%
```

**Analysis:**

* Database percentage spike indicates it's struggling
* Web-api percentage drop suggests it's being blocked
* Auth/cache drops suggest they can't reach database
* Classic database bottleneck pattern
  {% endtab %}

{% tab title="Service Health Monitoring" %}
**Health Indicators:**

* **Consistent percentages** = Healthy steady state
* **Gradual changes** = Normal load evolution
* **Sudden spikes** = Performance issues or load shifts
* **Disappearing services** = Potential outages

**Monitoring Strategy:**

1. Note baseline percentages for each service
2. Watch for deviations > 20% from baseline
3. Investigate services with sudden percentage changes
4. Correlate with error patterns from same services
   {% endtab %}
   {% endtabs %}

### Advanced Analysis Techniques

#### Correlation Analysis

**Cross-Reference Multiple Data Points:**

```bash
# Workflow for comprehensive analysis:
1. Heatmap: When did issues occur?
2. Patterns: What specific issues happened?
3. Services: Which services were affected?
4. Main logs: Examine specific instances

# Example correlation:
# Heatmap shows error spike at 30 min ago
# Patterns show "database timeout" as top error
# Services show database % increased during that time
# Conclusion: Database performance issue at 30 min ago
```

#### Trend Identification

**Long-Term Pattern Analysis:**

```bash
# Daily analysis routine:
1. Open analysis modal first thing
2. Note current top patterns and service distribution
3. Compare with yesterday's patterns (manual tracking)
4. Identify:
   - New patterns that appeared
   - Patterns that increased in frequency
   - Services with changed activity levels
5. Investigate significant changes
```

#### Performance Baseline Establishment

**Creating Performance Baselines:**

```bash
# Week 1: Establish baselines
# Track normal patterns:
# - Typical service distribution percentages
# - Common pattern frequencies  
# - Normal heatmap intensity levels
# - Typical entries/minute rates

# Week 2+: Compare against baselines
# Alert on:
# - Service distribution changes > 25%
# - New high-frequency error patterns
# - Unusual heatmap spike patterns
# - Entry rate changes > 50%
```

### Analysis Workflows

#### Incident Investigation Workflow

```bash
# 1. Get timeline overview
# Press Enter on Counts panel
# Check heatmap for incident timing

# 2. Identify problem patterns  
# Look at top error patterns
# Note pattern frequencies

# 3. Determine affected services
# Check service distribution
# Identify services with unusual activity

# 4. Deep dive investigation
# Filter main log view by time: /2024-01-15.*14:[2-3][0-9]
# Filter by pattern: /database.*connection.*timeout
# Examine specific log entries

# 5. Root cause analysis
# Correlate timing + patterns + services
# Look for cascade failure indicators
# Check for external factors (deployments, load changes)
```

#### Performance Monitoring Workflow

```bash
# 1. Establish current state
# Review heatmap for activity patterns
# Note baseline service distributions
# Check current pattern frequencies

# 2. Set monitoring expectations
# Note normal intensity levels
# Track typical pattern counts
# Baseline entries/minute rate

# 3. Continuous monitoring
# Check analysis modal every 30-60 minutes
# Look for deviations from baseline
# Track trend directions (improving/degrading)

# 4. Proactive investigation
# Investigate patterns with increasing frequency
# Monitor services with changing activity levels
# Use early warning patterns (WARN level issues)
```

#### Capacity Planning Workflow

```bash
# 1. Long-term trend analysis
# Track entries/minute over weeks
# Monitor service distribution evolution
# Note peak activity periods

# 2. Pattern evolution tracking
# Which patterns are becoming more frequent?
# Are new error patterns emerging?
# How do patterns correlate with load?

# 3. Resource correlation
# Compare log activity with system metrics
# Identify log volume vs performance relationship
# Plan capacity based on log analysis trends
```

### Troubleshooting Analysis Issues

#### Performance Issues

**Analysis Modal Loading Slowly:**

```bash
# Causes and solutions:
# - Large datasets: Reduce log buffer size
# - Complex patterns: Reset data periodically
# - High update frequency: Increase update interval

# Optimization:
gonzo -f logs.log --log-buffer=5000 --update-interval=5s
```

**Pattern Detection Not Working:**

```bash
# Common issues:
# - Logs too unstructured: Pattern detection works best with consistent formats
# - High variability: Some logs have too many unique elements
# - Insufficient data: Need meaningful sample size

# Solutions:
# - Use structured logs (JSON, logfmt) when possible
# - Filter out highly variable elements before analysis
# - Allow more time for pattern establishment
```

#### Interpretation Issues

**Unclear Heatmap Patterns:**

```bash
# If heatmap seems random:
# - Check if time range is appropriate
# - Verify log timestamps are accurate
# - Consider if activity is actually irregular

# Debugging steps:
# 1. Focus on single severity level
# 2. Use smaller time windows
# 3. Check raw log timestamps
```

**Misleading Service Distribution:**

```bash
# Common causes:
# - Inconsistent service name extraction
# - Missing service identifiers in logs
# - Mixed log formats affecting parsing

# Solutions:
# - Standardize service naming in logs
# - Use structured logging with consistent fields
# - Manually filter by service if needed
```

### Best Practices

#### 🎯 **Effective Analysis Strategies**

1. **Start with overview, drill down** - Use heatmap for big picture, patterns for specifics
2. **Correlate multiple data sources** - Combine timing, patterns, and services
3. **Track trends over time** - Compare current state with historical baselines
4. **Focus on high-impact patterns** - Prioritize by frequency and severity

#### 📊 **Data Quality Optimization**

1. **Use structured logging** - JSON and logfmt provide better analysis
2. **Consistent field naming** - Helps with service distribution accuracy
3. **Meaningful log levels** - Proper ERROR/WARN/INFO usage improves analysis
4. **Include context** - Service names, trace IDs, and relevant metadata

#### ⚡ **Performance Optimization**

1. **Right-size analysis windows** - Balance detail with performance
2. **Reset data periodically** - Prevent memory buildup in long sessions
3. **Filter appropriately** - Reduce dataset size for complex analysis
4. **Monitor resource usage** - Adjust settings based on system capacity

### What's Next?

Now that you understand log analysis, explore these complementary features:

* **AI Integration** - Combine algorithmic analysis with AI insights
* **Format Detection** - Optimize data input for better analysis
* **Configuration** - Tune analysis settings for your needs
* **Integration Examples** - Apply analysis to real-world scenarios

***

**You now have mastery over Gonzo's analytical capabilities!** 🚀 The combination of time-series analysis, pattern detection, and service distribution gives you unprecedented insight into log behavior and system health.


# Advanced Configuration

Master sophisticated Gonzo configurations for production deployments, high-performance scenarios, and complex multi-environment setups. This guide covers performance tuning, optimization strategies, and advanced configuration patterns.

{% hint style="info" %}
**Prerequisites:** Familiarity with Configuration Files and CLI Reference recommended before diving into advanced topics.
{% endhint %}

### Performance Optimization

#### High-Volume Log Processing

**Scenario:** Handling thousands of log entries per second

```yaml
# high-volume.yml - Optimized for throughput
files:
  - "/var/log/high-traffic/*.log"
follow: true

# Large buffers for throughput
log-buffer: 50000              # Store more entries
memory-size: 200000            # Track more patterns

# Slower updates to reduce overhead
update-interval: 30s           # Update every 30 seconds

# Batch processing optimization
batch-size: 1000               # Process in large batches

# Disable expensive features if not needed
# AI analysis can be enabled on-demand with 'm' key
```

**Command-line equivalent:**

```bash
gonzo -f /var/log/high-traffic/*.log --follow \
      --log-buffer=50000 \
      --memory-size=200000 \
      --update-interval=30s
```

**Monitoring Impact:**

```bash
# Monitor Gonzo's resource usage
watch -n 1 'ps aux | grep gonzo | grep -v grep'

# Check memory consumption
top -p $(pgrep gonzo)

# Profile CPU usage
perf record -p $(pgrep gonzo) sleep 30
perf report
```

#### Resource-Constrained Systems

**Scenario:** Running on systems with limited RAM/CPU

```yaml
# low-resource.yml - Minimized footprint
files:
  - "/var/log/app.log"
follow: true

# Minimal buffers
log-buffer: 500                # Small buffer
memory-size: 2000              # Minimal pattern tracking

# Slower updates
update-interval: 10s           # Reduce CPU usage

# Conservative processing
batch-size: 50                 # Smaller batches

# Disable features that aren't critical
# Enable AI only when needed
```

**Pre-filtering for Performance:**

```bash
# Filter before Gonzo to reduce load
tail -f /var/log/app.log | grep -E "(ERROR|WARN)" | gonzo \
      --log-buffer=500 \
      --memory-size=2000 \
      --update-interval=10s
```

#### Optimizing for Different Log Volumes

{% tabs %}
{% tab title="Low Volume (<10/sec)" %}

```yaml
# Optimized for responsiveness
log-buffer: 1000               # Standard buffer
memory-size: 10000             # Standard tracking
update-interval: 1s            # Fast updates
batch-size: 50                 # Small batches for low latency
```

{% endtab %}

{% tab title="Medium Volume (10-100/sec)" %}

```yaml
# Balanced performance
log-buffer: 5000               # Larger buffer
memory-size: 25000             # More pattern capacity
update-interval: 2s            # Moderate updates
batch-size: 200                # Balanced batch size
```

{% endtab %}

{% tab title="High Volume (100-1000/sec)" %}

```yaml
# Throughput optimized
log-buffer: 20000              # Large buffer
memory-size: 100000            # Extensive tracking
update-interval: 10s           # Infrequent updates
batch-size: 500                # Large batches
```

{% endtab %}

{% tab title="Extreme Volume (>1000/sec)" %}

```yaml
# Maximum throughput
log-buffer: 50000              # Very large buffer
memory-size: 200000            # Maximum tracking
update-interval: 30s           # Minimal UI updates
batch-size: 1000               # Maximum batch size

# Consider pre-filtering or sampling
# Process only ERROR/WARN levels
# Or sample 10% of logs
```

{% endtab %}
{% endtabs %}

### Multi-Environment Configurations

#### Environment-Specific Optimization

**Development Environment:**

```yaml
# ~/.config/gonzo/dev.yml
# Optimized for fast iteration and debugging

files:
  - "logs/*.log"
  - "debug/*.log"
follow: true

# Fast, responsive
update-interval: 500ms         # Very fast updates
log-buffer: 2000              # Moderate history
memory-size: 10000            # Standard tracking

# Cost-effective AI
ai-model: "gpt-3.5-turbo"
ai-context-size: 2000

# Full visibility for debugging
show-host: true
show-service: true
verbose: false
```

**Staging Environment:**

```yaml
# ~/.config/gonzo/staging.yml
# Balanced between dev speed and prod reliability

files:
  - "/var/log/staging/app/*.log"
  - "/var/log/staging/nginx/*.log"
follow: true

# Moderate performance
update-interval: 2s
log-buffer: 5000
memory-size: 25000

# Balanced AI (test prod models)
ai-model: "gpt-4"
ai-context-size: 4000

# Production-like settings
show-host: true
show-service: true
```

**Production Environment:**

```yaml
# ~/.config/gonzo/prod.yml
# Optimized for reliability and comprehensive analysis

files:
  - "/var/log/production/app/*.log"
  - "/var/log/production/nginx/*.log"
  - "/var/log/production/db/*.log"
follow: true

# Reliable, comprehensive
update-interval: 5s            # Conservative updates
log-buffer: 20000             # Large history
memory-size: 100000           # Extensive tracking

# Best quality AI
ai-model: "gpt-4"
ai-context-size: 8000
ai-response-timeout: 90s

# Full context for incidents
show-host: true
show-service: true

# Production monitoring
# Use separate terminal or tmux for continuous monitoring
```

#### Configuration Switching

```bash
# Shell aliases for quick switching
alias gonzo-dev='gonzo --config ~/.config/gonzo/dev.yml'
alias gonzo-staging='gonzo --config ~/.config/gonzo/staging.yml'
alias gonzo-prod='gonzo --config ~/.config/gonzo/prod.yml'

# Environment-based automatic selection
GONZO_CONFIG="${ENVIRONMENT:-development}.yml"
alias gonzo='command gonzo --config ~/.config/gonzo/${GONZO_CONFIG}'

# Usage
export ENVIRONMENT=production
gonzo  # Automatically uses prod.yml
```

### Advanced Integration Patterns

#### CI/CD Pipeline Integration

**Build Analysis Configuration:**

```yaml
# ci-build-analysis.yml
# Automated analysis of build logs

files:
  - "build-logs/*.log"
  - "test-results/*.log"
follow: false                  # Batch processing

# Moderate performance for CI
update-interval: 2s
log-buffer: 5000

# Fast, cost-effective AI
ai-model: "gpt-3.5-turbo"
ai-context-size: 2000
ai-response-timeout: 30s

# CI-friendly output
test-mode: true
quiet: false
json-output: false
```

**Integration Script:**

```bash
#!/bin/bash
# ci-analyze-logs.sh
# Automated log analysis in CI/CD

set -e

LOG_DIR="build-logs"
GONZO_CONFIG="ci-build-analysis.yml"

# Run build and capture logs
build-command 2>&1 | tee "${LOG_DIR}/build.log"
BUILD_EXIT=$?

# Analyze logs with Gonzo
echo "Analyzing build logs..."
gonzo --config "${GONZO_CONFIG}" 2>&1 | tee "${LOG_DIR}/analysis.txt"

# Check for critical patterns
if grep -qi "error\|critical\|fatal" "${LOG_DIR}/build.log"; then
    echo "Critical issues found in build logs"
    exit 1
fi

exit $BUILD_EXIT
```

#### Monitoring System Integration

**Prometheus-Style Metrics:**

```yaml
# monitoring.yml
# Configuration for metrics collection

files:
  - "/var/log/app/*.log"
follow: true

# Optimized for metric collection
update-interval: 60s           # 1-minute metrics
log-buffer: 10000
memory-size: 50000

# Export metrics format
# Implement custom metrics exporter
# Count errors, warnings, patterns over time
```

**Custom Metrics Exporter:**

```bash
#!/bin/bash
# gonzo-metrics-exporter.sh
# Export Gonzo analysis as metrics

while true; do
    # Analyze logs
    gonzo --config monitoring.yml --test-mode > /tmp/gonzo-analysis.txt
    
    # Extract metrics
    ERROR_COUNT=$(grep -c "ERROR" /tmp/gonzo-analysis.txt || echo 0)
    WARN_COUNT=$(grep -c "WARN" /tmp/gonzo-analysis.txt || echo 0)
    
    # Export to metrics file
    cat > /var/lib/node_exporter/gonzo.prom << EOF
# HELP gonzo_errors_total Total error count
# TYPE gonzo_errors_total counter
gonzo_errors_total ${ERROR_COUNT}

# HELP gonzo_warnings_total Total warning count
# TYPE gonzo_warnings_total counter
gonzo_warnings_total ${WARN_COUNT}
EOF
    
    sleep 60
done
```

#### Alerting Integration

**Alert-Triggered Analysis:**

```yaml
# alert-analysis.yml
# Deep analysis when alerts trigger

files:
  - "/var/log/app/*.log"
follow: false                  # Analyze recent history

# Quick analysis
update-interval: 1s
log-buffer: 5000

# Best AI for alert context
ai-model: "gpt-4"
ai-context-size: 8000

# Generate alert context
# Use AI to explain what caused the alert
```

**Alert Handler Script:**

```bash
#!/bin/bash
# alert-handler.sh
# Triggered by monitoring alerts

ALERT_NAME="$1"
ALERT_TIME="$2"
LOG_FILE="$3"

echo "Alert: ${ALERT_NAME} at ${ALERT_TIME}"

# Analyze logs around alert time
# Extract ±15 minutes around alert
START_TIME=$(date -d "${ALERT_TIME} - 15 minutes" +%Y-%m-%dT%H:%M)
END_TIME=$(date -d "${ALERT_TIME} + 15 minutes" +%Y-%m-%dT%H:%M)

# Filter logs to timeframe
grep -E "${START_TIME}|${END_TIME}" "${LOG_FILE}" > /tmp/alert-logs.txt

# Analyze with Gonzo + AI
gonzo -f /tmp/alert-logs.txt \
      --config alert-analysis.yml \
      --ai-model="gpt-4" > /tmp/alert-analysis.txt

# Send analysis to incident channel
cat /tmp/alert-analysis.txt | send-to-slack "#incidents"
```

### Team Configuration Management

#### Shared Configuration Standards

**Base Team Configuration:**

```yaml
# team-base.yml
# Shared standards across entire team
# Version controlled in team repository

# Standard performance settings
update-interval: 2s
log-buffer: 5000
memory-size: 15000

# Team AI standards
ai-model: "gpt-3.5-turbo"      # Default cost-effective model
ai-auto-select: true           # Allow auto-upgrade
ai-context-size: 4000

# Display standards
show-service: true             # Always show service context

# Documentation
# Last updated: 2024-01-15
# Owner: DevOps Team
# Changes require PR review
```

**Personal Overrides:**

```yaml
# personal-overrides.yml
# Personal preferences layered on team standards

# Import team base (if supported)
# extends: team-base.yml

# Personal files (additional to team standards)
files:
  - "~/logs/*.log"              # Personal log directory

# Personal AI preferences
ai-model: "gpt-4"              # Personal API key, better model

# Personal display preferences
verbose: true                  # More output for learning
```

**Usage Pattern:**

```bash
# Team members create combined configs
cat team-base.yml personal-overrides.yml > ~/.config/gonzo/config.yml

# Or use layering with explicit configs
gonzo --config team-base.yml --log-buffer=10000  # CLI override
```

#### Configuration Repository Structure

```bash
# Team configuration repository
gonzo-configs/
├── README.md                   # Documentation
├── base/
│   ├── team-standard.yml      # Base team config
│   └── security-policy.yml    # Security requirements
├── environments/
│   ├── development.yml        # Dev environment
│   ├── staging.yml            # Staging environment
│   └── production.yml         # Production environment
├── profiles/
│   ├── debugging.yml          # Debugging profile
│   ├── security.yml           # Security monitoring
│   └── performance.yml        # Performance analysis
├── examples/
│   ├── kubernetes.yml         # K8s integration
│   ├── cloudwatch.yml         # AWS CloudWatch
│   └── docker.yml             # Docker containers
└── scripts/
    ├── install-configs.sh     # Install team configs
    └── validate-configs.sh    # Validate before commit
```

### Performance Monitoring

#### Benchmarking Configuration Impact

**Performance Testing Script:**

```bash
#!/bin/bash
# benchmark-config.sh
# Test configuration performance

CONFIG_FILE="$1"
TEST_LOG="test-logs/high-volume.log"
ITERATIONS=5

echo "Benchmarking configuration: ${CONFIG_FILE}"

for i in $(seq 1 $ITERATIONS); do
    echo "Run $i/${ITERATIONS}..."
    
    # Measure time and resources
    /usr/bin/time -v gonzo \
        --config "${CONFIG_FILE}" \
        -f "${TEST_LOG}" \
        --test-mode 2>&1 | tee "benchmark-run-${i}.txt"
    
    # Extract metrics
    MAX_RSS=$(grep "Maximum resident" "benchmark-run-${i}.txt" | awk '{print $6}')
    CPU_TIME=$(grep "User time" "benchmark-run-${i}.txt" | awk '{print $4}')
    
    echo "  Memory: ${MAX_RSS} KB"
    echo "  CPU Time: ${CPU_TIME}s"
done

# Calculate averages
echo "Calculating averages..."
```

#### Resource Monitoring

**Continuous Monitoring:**

```bash
#!/bin/bash
# monitor-gonzo-resources.sh
# Monitor Gonzo resource usage

LOG_FILE="gonzo-resources-$(date +%Y%m%d-%H%M%S).log"

echo "Monitoring Gonzo resources to ${LOG_FILE}"
echo "Timestamp,PID,CPU%,MEM%,VSZ,RSS" > "${LOG_FILE}"

while true; do
    GONZO_PID=$(pgrep gonzo)
    
    if [ -n "$GONZO_PID" ]; then
        ps -p $GONZO_PID -o pid,pcpu,pmem,vsz,rss --no-headers | \
        awk -v ts="$(date +%Y-%m-%d\ %H:%M:%S)" '{print ts","$1","$2","$3","$4","$5}' >> "${LOG_FILE}"
    fi
    
    sleep 1
done
```

### Advanced Troubleshooting

#### Configuration Debugging

**Verbose Configuration Analysis:**

```bash
# Show what configuration is actually being used
gonzo --config myconfig.yml --show-config

# Detailed verbose output
gonzo --config myconfig.yml --verbose --dry-run

# Test mode with logging
gonzo --config myconfig.yml --test-mode 2>&1 | tee config-test.log

# Validate configuration syntax
python3 -c "import yaml; yaml.safe_load(open('myconfig.yml'))"
```

**Common Configuration Issues:**

{% tabs %}
{% tab title="Performance Problems" %}
**Symptoms:**

* High CPU usage
* High memory consumption
* Slow UI updates

**Diagnosis:**

```bash
# Check current settings
gonzo --show-config | grep -E "(buffer|memory|interval)"

# Monitor resource usage
top -p $(pgrep gonzo)

# Profile performance
perf record -p $(pgrep gonzo) sleep 10
```

**Solutions:**

```yaml
# Reduce resource usage
log-buffer: 2000              # Smaller buffer
memory-size: 5000             # Less memory
update-interval: 10s          # Slower updates
batch-size: 100               # Smaller batches
```

{% endtab %}

{% tab title="AI Not Working" %}
**Symptoms:**

* AI analysis not available
* Model selection fails
* Timeout errors

**Diagnosis:**

```bash
# Check AI configuration
echo $OPENAI_API_KEY
echo $OPENAI_API_BASE

# Test AI connectivity
curl -H "Authorization: Bearer $OPENAI_API_KEY" \
     https://api.openai.com/v1/models

# Verbose AI debugging
gonzo --ai-model="gpt-4" --verbose
```

**Solutions:**

```yaml
# Increase timeouts
ai-response-timeout: 90s      # Longer timeout
ai-max-retries: 5             # More retries

# Use more reliable model
ai-model: "gpt-3.5-turbo"     # Faster, more reliable

# Check API key environment variable
# OPENAI_API_KEY should be set
```

{% endtab %}

{% tab title="File Access Issues" %}
**Symptoms:**

* Files not found
* Permission denied
* Glob patterns not working

**Diagnosis:**

```bash
# Check file exists
ls -la /path/to/logfile.log

# Check permissions
ls -l /path/to/logfile.log

# Test glob expansion
ls -la /var/log/*.log

# Run with verbose mode
gonzo -f /path/to/log --verbose
```

**Solutions:**

```yaml
# Use absolute paths
files:
  - "/absolute/path/to/logs/*.log"

# Check file permissions
# Run with appropriate user permissions
# sudo gonzo -f /var/log/secure.log

# Verify glob patterns work
# Test: ls -la "your-glob-pattern"
```

{% endtab %}
{% endtabs %}

### Security Hardening

#### Secure Configuration Practices

**Sensitive Data Management:**

```yaml
# secure-config.yml
# Production configuration with security focus

# File paths (no sensitive data)
files:
  - "/var/log/app/*.log"
follow: true

# Performance settings (no secrets)
update-interval: 5s
log-buffer: 10000

# AI configuration (NO API KEYS IN CONFIG FILE)
ai-model: "gpt-4"
# API key set via environment variable: OPENAI_API_KEY

# Notes:
# - NEVER commit API keys to version control
# - Use environment variables for secrets
# - Rotate API keys regularly
# - Use different keys for dev/staging/prod
```

**Environment Variable Management:**

```bash
# .env.production (NOT version controlled)
OPENAI_API_KEY=sk-prod-key-here
OPENAI_API_BASE=https://api.openai.com/v1

# Load in production
set -a
source .env.production
set +a

gonzo --config prod.yml
```

#### Audit and Compliance

**Audit Logging Configuration:**

```yaml
# audit-config.yml
# Configuration with audit requirements

# Log all analyzed files
files:
  - "/var/log/app/*.log"
  - "/var/log/audit/*.log"

# Comprehensive tracking
log-buffer: 20000             # Large history for audit
memory-size: 100000           # Extensive pattern tracking

# Detailed logging
verbose: true                 # Full audit trail
json-output: false            # Keep structured logs

# AI usage tracking
# Track all AI queries for compliance
# Implement custom AI usage logger
```

### What's Next?

You've mastered advanced Gonzo configuration! Continue exploring:

* **Integration Examples** - Apply advanced configs to real scenarios
* **API & Architecture** - Understand how Gonzo works
* **Troubleshooting** - Advanced troubleshooting techniques

Or start implementing advanced configurations:

```bash
# Create your advanced configuration
mkdir -p ~/.config/gonzo/{profiles,environments}

# Set up environment-specific configs
cp examples/prod.yml ~/.config/gonzo/environments/
cp examples/dev.yml ~/.config/gonzo/environments/

# Create performance profiles
cp examples/high-volume.yml ~/.config/gonzo/profiles/
cp examples/low-resource.yml ~/.config/gonzo/profiles/

# Use them
gonzo --config ~/.config/gonzo/environments/prod.yml
gonzo --config ~/.config/gonzo/profiles/high-volume.yml
```

***

**Master advanced configuration for production-ready Gonzo deployments!** 🚀 From performance optimization to multi-environment management, sophisticated configuration strategies ensure Gonzo scales with your needs.


# API & Architecture

Welcome to the API & Architecture section! This documentation provides deep technical insights into how Gonzo works internally, how it implements protocols, and how you can extend it.

### Overview

This section is designed for:

* **Developers** who want to understand Gonzo's internals
* **Contributors** who want to add features or fix bugs
* **Integrators** who want to connect Gonzo with other systems
* **Technical users** who want to optimize Gonzo's performance
* **Curious minds** who want to learn how it all works

### What You'll Learn

#### Architecture

Understand Gonzo's design and structure:

* Component organization and responsibilities
* Data flow through the system
* Technology stack and frameworks
* Design patterns and decisions
* Extension mechanisms

**Start here**: Architecture Overview

#### OTLP Protocol

Deep dive into OpenTelemetry Protocol implementation:

* gRPC and HTTP transport details
* OTLP log data model
* Receiver implementation
* Configuration and integration
* Performance optimization

**Start here**: OTLP Protocol Details

#### Extension Points

Learn how to extend Gonzo's functionality:

* Custom log format parsers
* Custom skins and themes
* AI provider integration
* Input pipeline extensions
* Plugin development (future)

**Start here**: Extension Points

### Quick Navigation

#### For Different Audiences

**If you're a new contributor**:

1. Read Architecture Overview to understand the big picture
2. Browse the codebase structure
3. Check Contributing Guidelines
4. Pick a "good first issue" to work on

**If you're integrating with OTLP**:

1. Review OTLP Protocol Details
2. Check configuration examples
3. Test with your OpenTelemetry setup
4. See Troubleshooting if needed

**If you're extending Gonzo**:

1. Explore Extension Points
2. Review examples in the repository
3. Create your custom formats or skins
4. Share with the community!

**If you're optimizing performance**:

1. Understand architecture from Architecture Overview
2. Review performance considerations
3. Profile your specific use case
4. Adjust configuration accordingly

### Architecture at a Glance

Gonzo follows a clean, modular architecture:

```
┌─────────────────────────────────────────────────┐
│                   CLI Layer                     │
│            (Entry Point & Config)               │
└─────────────────┬───────────────────────────────┘
                  │
    ┌─────────────┼─────────────┐
    │             │             │
    ▼             ▼             ▼
┌─────────┐  ┌─────────┐  ┌──────────┐
│  Input  │  │   TUI   │  │   AI     │
│ Sources │  │ Engine  │  │ Engine   │
└────┬────┘  └────┬────┘  └────┬─────┘
     │            │            │
     │       ┌────▼────┐       │
     └──────►│Analyzer │◄──────┘
             │ Engine  │
             └────┬────┘
                  │
             ┌────▼────┐
             │ Memory  │
             │ Store   │
             └─────────┘
```

#### Key Components

**Input Layer**: File readers, stdin, OTLP receivers\
**Processing Layer**: Format detection, parsing, analysis\
**Storage Layer**: Buffering, frequency tracking\
**Display Layer**: Terminal UI with Bubble Tea\
**Integration Layer**: AI providers, external systems

Learn more: Architecture Overview

### Technology Stack

#### Core Frameworks

* [**Bubble Tea**](https://github.com/charmbracelet/bubbletea) - Terminal UI framework (MVU pattern)
* [**Lipgloss**](https://github.com/charmbracelet/lipgloss) - Styling and layout
* [**Bubbles**](https://github.com/charmbracelet/bubbles) - Reusable TUI components
* [**Cobra**](https://github.com/spf13/cobra) - CLI framework
* [**Viper**](https://github.com/spf13/viper) - Configuration management

#### Protocols & Standards

* **OpenTelemetry** - OTLP protocol implementation
* **gRPC** - High-performance RPC framework
* **Protocol Buffers** - Efficient serialization
* **JSON** - Data exchange format

#### Algorithms & Libraries

* **drain3** - Log pattern extraction
* **Go standard library** - Core functionality
* **regex** - Pattern matching

Learn more: Architecture Overview

### Design Principles

#### Modularity

Components are loosely coupled and can be modified independently:

* Input sources are pluggable
* Parsers are format-agnostic
* Display is separate from logic
* AI providers are abstracted

#### Performance

Optimized for real-time log processing:

* Streaming architecture
* Bounded memory usage
* Incremental updates
* Efficient data structures

#### Extensibility

Designed to be extended:

* Custom format parsers (YAML-based)
* Custom skins (YAML-based)
* AI provider abstraction
* Configuration-driven behavior

#### User Experience

Terminal UI designed for efficiency:

* Keyboard-first navigation
* Vim-style shortcuts
* Mouse support
* Responsive updates
* Clear visual hierarchy

### Common Use Cases

#### 1. Understanding the Codebase

**Goal**: Contribute code to Gonzo

**Path**:

1. Architecture Overview - Understand structure
2. Development Setup - Set up environment
3. Contribution Guidelines - Follow process

#### 2. Implementing OTLP Integration

**Goal**: Send logs to Gonzo via OpenTelemetry

**Path**:

1. OTLP Protocol Details - Understand implementation
2. Review configuration examples
3. Test integration
4. Troubleshooting - If issues

#### 3. Creating Custom Parsers

**Goal**: Parse non-standard log formats

**Path**:

1. Extension Points - Learn format system
2. Study example formats
3. Create your parser
4. Test and share

#### 4. Optimizing Performance

**Goal**: Handle high-volume logs efficiently

**Path**:

1. Architecture Overview - Understand data flow
2. Review performance sections
3. Adjust buffer sizes and intervals
4. Profile and tune

### Technical Specifications

#### System Requirements

**Runtime**:

* Go 1.21 or higher (if building from source)
* Modern terminal with Unicode support
* 256 color support recommended

**Resources**:

* CPU: Minimal (scales with log volume)
* Memory: Configurable (default \~50MB)
* Network: Optional (for OTLP receiver)

#### Supported Platforms

* **Linux**: All major distributions
* **macOS**: 10.15 and later
* **Windows**: Windows 10+ (WSL recommended)

#### Protocol Support

* **OTLP**: v1.0.0+ (gRPC and HTTP)
* **JSON**: Standard JSON format
* **Logfmt**: Key=value format
* **Plain Text**: Basic text logs
* **Custom**: User-defined formats

### Performance Characteristics

#### Throughput

**Typical performance** (depends on hardware and configuration):

* **Low volume**: <100 logs/sec - Default settings work well
* **Medium volume**: 100-1,000 logs/sec - May need tuning
* **High volume**: 1,000-10,000 logs/sec - Requires optimization
* **Very high**: >10,000 logs/sec - Consider sampling or filtering

#### Memory Usage

**Baseline**: \~20-30 MB\
**With 1,000 log buffer**: \~30-50 MB\
**With 10,000 log buffer**: \~100-200 MB\
**Factors**: Log size, attributes, word frequency tracking

#### Latency

**Display updates**: Configurable (default 1 second)\
**OTLP ingestion**: <10ms per log\
**AI analysis**: 1-5 seconds (depends on provider)\
**Search/filter**: Near-instant (<100ms)

### API Stability

#### Current Status

**Version**: 0.1.x (Early stages)

**Stability**:

* **CLI Interface**: Stable, unlikely to change
* **Configuration Format**: Stable
* **OTLP Protocol**: Stable (follows OpenTelemetry spec)
* **Internal APIs**: May change between versions
* **Extension APIs**: Evolving (formats and skins are stable)

#### Versioning

Gonzo follows [Semantic Versioning](https://semver.org/):

* **Major** (x.0.0): Breaking changes
* **Minor** (0.x.0): New features (backward compatible)
* **Patch** (0.0.x): Bug fixes (backward compatible)

### Future Direction

#### Planned Enhancements

**Near-term**:

* Enhanced OTLP features
* Additional AI providers
* Performance optimizations
* More built-in formats

**Medium-term**:

* Plugin system architecture
* REST API for remote control
* Web-based interface option
* Advanced analytics

**Long-term**:

* Distributed log analysis
* Clustering and aggregation
* Machine learning integration
* Enterprise features

See Changelog and [Roadmap](https://github.com/control-theory/gonzo/projects) for details.

### Getting Help

#### Documentation

* **Architecture Overview** - System design
* **OTLP Protocol Details** - Protocol implementation
* **Extension Points** - How to extend

#### Community

* **GitHub Issues**: [Report bugs or request features](https://github.com/control-theory/gonzo/issues)
* **GitHub Discussions**: [Ask questions](https://github.com/control-theory/gonzo/discussions)
* **Email**: <support@controltheory.com>

#### Contributing

Want to contribute to Gonzo's architecture?

1. Review Architecture Overview
2. Check Development Setup
3. Read Contribution Guidelines
4. Start with [good first issues](https://github.com/control-theory/gonzo/labels/good%20first%20issue)

### Additional Resources

#### Related Documentation

* **Configuration Reference** - Configure Gonzo
* **Troubleshooting** - Solve problems
* **Contributing** - Join development

#### External Resources

* **OpenTelemetry**: <https://opentelemetry.io/>
* **Bubble Tea**: <https://github.com/charmbracelet/bubbletea>
* **Go Documentation**: <https://go.dev/doc/>

#### Examples

* **Repository**: <https://github.com/control-theory/gonzo>
* **Examples Directory**: <https://github.com/control-theory/gonzo/tree/main/examples>
* **Discussions**: <https://github.com/control-theory/gonzo/discussions>

***

### Ready to Dive In?

Choose your path:

**📚 Learn the architecture**: Start with Architecture Overview

**🔌 Implement OTLP**: Jump to OTLP Protocol Details

**🔧 Extend Gonzo**: Explore Extension Points

**💻 Contribute code**: Check Contributing Guidelines

{% hint style="info" %}
**New to the codebase?** Start with the Architecture Overview to get a solid understanding of how everything fits together.
{% endhint %}

{% hint style="success" %}
**Building integrations?** The OTLP Protocol Details page has everything you need to connect Gonzo to your OpenTelemetry pipeline.
{% endhint %}


# Architecture Overview

Understanding Gonzo's architecture helps you extend it, contribute to it, or integrate it into your systems. This page provides a high-level overview of how Gonzo is structured.

### High-Level Architecture

Gonzo follows a clean, modular architecture with clear separation of concerns:

```
┌─────────────────────────────────────────────────┐
│                   CLI Layer                     │
│            (cmd/gonzo - Entry Point)            │
└─────────────────┬───────────────────────────────┘
                  │
    ┌─────────────┼─────────────┐
    │             │             │
    ▼             ▼             ▼
┌─────────┐  ┌─────────┐  ┌──────────┐
│  Input  │  │   TUI   │  │   AI     │
│ Sources │  │ Engine  │  │ Engine   │
└────┬────┘  └────┬────┘  └────┬─────┘
     │            │            │
     │       ┌────▼────┐       │
     └──────►│Analyzer │◄──────┘
             │ Engine  │
             └────┬────┘
                  │
             ┌────▼────┐
             │ Memory  │
             │ Store   │
             └─────────┘
```

### Directory Structure

```
gonzo/
├── cmd/
│   └── gonzo/          # Application entry point
│       └── main.go     # CLI initialization
│
├── internal/           # Private application code
│   ├── tui/           # Terminal UI implementation
│   │   ├── model.go   # Bubble Tea model
│   │   ├── view.go    # UI rendering
│   │   └── update.go  # Event handling
│   │
│   ├── analyzer/      # Log analysis engine
│   │   ├── parser.go  # Format detection & parsing
│   │   ├── filter.go  # Filtering logic
│   │   └── stats.go   # Statistical analysis
│   │
│   ├── memory/        # Frequency tracking & storage
│   │   ├── buffer.go  # Log buffer management
│   │   └── freq.go    # Word frequency tracking
│   │
│   ├── otlplog/       # OTLP format handling
│   │   ├── receiver.go # OTLP receiver server
│   │   ├── grpc.go    # gRPC handler
│   │   └── http.go    # HTTP handler
│   │
│   └── ai/            # AI integration
│       ├── client.go   # OpenAI client
│       ├── provider.go # Multi-provider support
│       └── analysis.go # Analysis logic
│
├── examples/          # Example configs & formats
│   ├── config.yaml    # Sample configuration
│   ├── formats/       # Custom format definitions
│   └── send_otlp_logs.py # OTLP example
│
├── docs/             # Documentation
└── tests/            # Test files
```

### Core Components

#### 1. CLI Layer (`cmd/gonzo`)

**Purpose**: Application entry point and command-line interface.

**Responsibilities**:

* Parse command-line arguments using Cobra
* Load configuration from files and environment
* Initialize and start the TUI or OTLP receiver
* Handle graceful shutdown

**Key Files**:

* `main.go` - Entry point
* `root.go` - Root command definition
* `version.go` - Version command

#### 2. TUI Engine (`internal/tui`)

**Purpose**: Terminal user interface using Bubble Tea framework.

**Responsibilities**:

* Render the 2x2 dashboard layout
* Handle keyboard and mouse input
* Update UI in response to events
* Manage focus and navigation

**Architecture Pattern**: Model-View-Update (MVU/Elm architecture)

**Key Components**:

```go
type Model struct {
    logViewer    viewport.Model
    wordFreq     table.Model
    attributes   list.Model
    counts       statsModel
    focusIndex   int
    paused       bool
}

func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd)
func (m Model) View() string
```

**Styling**: Uses Lipgloss for colors, borders, and layout.

#### 3. Analyzer Engine (`internal/analyzer`)

**Purpose**: Core log processing and analysis.

**Responsibilities**:

* Detect log format (JSON, logfmt, plain text)
* Parse logs into structured format
* Extract attributes and severity
* Apply filters and search patterns
* Generate statistics

**Key Algorithms**:

* **Format Detection**: Heuristic-based per-line detection
* **Pattern Extraction**: Uses drain3 algorithm for pattern mining
* **Severity Extraction**: Keyword matching and field extraction

**Flow**:

```
Raw Log → Format Detection → Parser → Structured Log → Analyzer → Stats
```

#### 4. Memory Store (`internal/memory`)

**Purpose**: Efficient in-memory storage and tracking.

**Responsibilities**:

* Buffer recent logs (circular buffer)
* Track word frequencies
* Maintain attribute counts
* Manage memory limits

**Data Structures**:

* **Log Buffer**: Ring buffer (default 1000 entries)
* **Word Frequency**: Hash map with LRU eviction (default 10,000 words)
* **Attribute Store**: Nested maps for fast lookup

**Memory Management**:

* Configurable buffer sizes
* Automatic eviction of old data
* Optimized for real-time streaming

#### 5. OTLP Handler (`internal/otlplog`)

**Purpose**: OpenTelemetry Protocol log receiver.

**Responsibilities**:

* Run gRPC server (port 4317)
* Run HTTP server (port 4318)
* Accept OTLP log data
* Convert to internal log format
* Feed to analyzer engine

**Protocol Support**:

* gRPC: Full OTLP logs specification
* HTTP: OTLP/HTTP with JSON encoding
* Both: Resource and log record attributes

**Architecture**:

```
OTLP Client → [gRPC/HTTP] → OTLP Receiver → Log Converter → Analyzer
```

#### 6. AI Integration (`internal/ai`)

**Purpose**: AI-powered log analysis.

**Responsibilities**:

* Connect to AI providers (OpenAI, Ollama, LM Studio)
* Send log context for analysis
* Parse AI responses
* Manage chat conversations

**Provider Support**:

* OpenAI API
* OpenAI-compatible APIs
* Local models (Ollama, LM Studio)
* Automatic model selection

**Integration Points**:

* Instant analysis (`i` key)
* Chat mode (`c` key)
* Model switching (`m` key)

### Data Flow

#### Log Ingestion Flow

```
Input Source
    ↓
┌───────────────────────┐
│  File / Stdin / OTLP  │
└───────┬───────────────┘
        ↓
┌───────────────────────┐
│  Format Detection     │
│  (JSON/logfmt/text)   │
└───────┬───────────────┘
        ↓
┌───────────────────────┐
│  Parser               │
│  (Extract fields)     │
└───────┬───────────────┘
        ↓
┌───────────────────────┐
│  Analyzer             │
│  (Stats, patterns)    │
└───────┬───────────────┘
        ↓
┌───────────────────────┐
│  Memory Store         │
│  (Buffer, frequency)  │
└───────┬───────────────┘
        ↓
┌───────────────────────┐
│  TUI Update           │
│  (Render dashboard)   │
└───────────────────────┘
```

#### User Interaction Flow

```
User Input (keyboard/mouse)
    ↓
┌───────────────────────┐
│  TUI Event Handler    │
└───────┬───────────────┘
        ↓
┌───────────────────────┐
│  Action Processor     │
│  (filter, pause, etc) │
└───────┬───────────────┘
        ↓
┌───────────────────────┐
│  State Update         │
└───────┬───────────────┘
        ↓
┌───────────────────────┐
│  UI Re-render         │
└───────────────────────┘
```

#### AI Analysis Flow

```
User selects log + presses 'i'
    ↓
┌───────────────────────┐
│  Extract Log Context  │
└───────┬───────────────┘
        ↓
┌───────────────────────┐
│  Format Prompt        │
└───────┬───────────────┘
        ↓
┌───────────────────────┐
│  Send to AI Provider  │
└───────┬───────────────┘
        ↓
┌───────────────────────┐
│  Parse Response       │
└───────┬───────────────┘
        ↓
┌───────────────────────┐
│  Display in Modal     │
└───────────────────────┘
```

### Key Design Patterns

#### 1. Model-View-Update (MVU)

The TUI uses Bubble Tea's MVU pattern:

```go
// Model: Application state
type Model struct { ... }

// Update: State transitions
func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { ... }

// View: Render current state
func (m Model) View() string { ... }
```

**Benefits**:

* Predictable state management
* Easy testing
* Clear separation of concerns

#### 2. Plugin Architecture

Custom formats are pluggable:

```yaml
# formats/my-format.yaml
name: my-format
pattern: '(\d+) (\w+) (.+)'
fields:
  - timestamp
  - level
  - message
```

**Benefits**:

* Extend without code changes
* Community-contributed formats
* Easy testing of parsers

#### 3. Streaming Pipeline

Logs flow through processing pipeline:

```go
input → detect → parse → analyze → store → display
```

**Benefits**:

* Real-time processing
* Low memory footprint
* Handles unlimited log streams

#### 4. Provider Abstraction

AI providers implement common interface:

```go
type Provider interface {
    Analyze(log Log) (string, error)
    Chat(messages []Message) (string, error)
    ListModels() ([]Model, error)
}
```

**Benefits**:

* Easy to add new providers
* Swap providers at runtime
* Consistent API

### Technology Stack

#### Core Framework

* [**Bubble Tea**](https://github.com/charmbracelet/bubbletea) - TUI framework (MVU pattern)
* [**Lipgloss**](https://github.com/charmbracelet/lipgloss) - Styling and layout
* [**Bubbles**](https://github.com/charmbracelet/bubbles) - Reusable TUI components

#### CLI & Configuration

* [**Cobra**](https://github.com/spf13/cobra) - CLI framework
* [**Viper**](https://github.com/spf13/viper) - Configuration management

#### Protocols & APIs

* **OpenTelemetry** - OTLP protocol implementation
* **gRPC** - For OTLP gRPC receiver
* **HTTP/JSON** - For OTLP HTTP receiver

#### Log Processing

* **drain3** - Pattern extraction algorithm
* **regex** - Format parsing
* Standard library - JSON, text processing

#### AI Integration

* **OpenAI API** - Primary AI provider
* **HTTP client** - For API calls
* **JSON** - Request/response format

### Performance Considerations

#### Memory Management

**Bounded Buffers**:

* Log buffer: Default 1000 entries (configurable)
* Word frequency: Default 10,000 words (configurable)
* Automatic eviction prevents unlimited growth

**Efficient Storage**:

* Circular buffers for logs
* Hash maps for fast lookup
* Lazy evaluation where possible

#### CPU Optimization

**Incremental Processing**:

* Process logs as they arrive
* Update statistics incrementally
* Avoid re-processing entire dataset

**Configurable Update Rate**:

* Dashboard updates: Default 1 second (configurable)
* Reduces CPU for high-volume logs

#### Network Efficiency

**OTLP Receiver**:

* Batched processing
* Efficient protobuf serialization
* Concurrent request handling

**AI Requests**:

* Single requests (not streamed currently)
* Reusable HTTP connections
* Configurable timeouts

### Extension Points

Gonzo is designed to be extended in several ways:

1. **Custom Formats** - Add new log format parsers
2. **Custom Skins** - Create new color schemes
3. **AI Providers** - Integrate new AI services
4. **Input Sources** - Add new log sources
5. **Export Formats** - Add new export options

See Extension Points for detailed information.

### Testing Strategy

**Unit Tests**:

* Parser logic
* Analyzer algorithms
* Format detection

**Integration Tests**:

* End-to-end log processing
* OTLP receiver
* File input handling

**Manual Testing**:

* TUI interactions
* Visual regressions
* Performance with large datasets

### Building & Development

#### Build Process

```bash
# Development build
make build

# All platforms
make cross-build

# With tests
make dev
```

#### Development Mode

```bash
# Format, vet, test, build
make dev

# Run tests
make test

# Race detection
make test-race
```

#### Release Process

1. Version bump in code
2. Update CHANGELOG.md
3. Create Git tag
4. GitHub Actions builds binaries
5. Publish to releases page

### Related Documentation

* **OTLP Protocol Details** - Deep dive into OTLP implementation
* **Extension Points** - How to extend Gonzo
* **Contributing Guide** - How to contribute

{% hint style="info" %}
**Want to contribute?** Check the Contributing Guide and Development Setup to get started!
{% endhint %}


# OTLP Protocol Details

Deep dive into Gonzo's OpenTelemetry Protocol (OTLP) implementation for receiving and processing logs.

### Overview

Gonzo implements a complete OTLP logs receiver supporting both gRPC and HTTP transports. This allows Gonzo to receive logs directly from OpenTelemetry SDKs, collectors, and other OTLP-compatible sources.

### OTLP Specification

Gonzo follows the [OpenTelemetry Protocol Specification](https://opentelemetry.io/docs/specs/otlp/) for logs:

* **Version**: OTLP 1.0.0+
* **Transports**: gRPC and HTTP
* **Encoding**: Protocol Buffers (gRPC), JSON (HTTP)
* **Endpoints**:
  * gRPC: `localhost:4317`
  * HTTP: `http://localhost:4318/v1/logs`

### Architecture

```
┌─────────────────────────────────────────┐
│         OTLP Client (Sender)            │
│    (App, Collector, SDK, etc)           │
└──────────────┬──────────────────────────┘
               │
               ├──────────┐
               │          │
           gRPC:4317   HTTP:4318
               │          │
    ┌──────────▼────┐  ┌──▼──────────┐
    │  gRPC Server  │  │ HTTP Server │
    │               │  │             │
    └──────┬────────┘  └─┬───────────┘
           │             │
           └─────┬───────┘
                 │
        ┌────────▼─────────┐
        │  OTLP Processor  │
        │  - Decode proto  │
        │  - Extract logs  │
        │  - Map fields    │
        └────────┬─────────┘
                 │
        ┌────────▼─────────┐
        │  Log Converter   │
        │  - Resource attr │
        │  - Log record    │
        │  - Timestamps    │
        └────────┬─────────┘
                 │
        ┌────────▼─────────┐
        │   Analyzer       │
        │   Engine         │
        └──────────────────┘
```

### Transport Details

#### gRPC Transport

**Endpoint**: `localhost:4317`

**Protocol**: HTTP/2 with Protocol Buffers

**Service Definition**:

```protobuf
service LogsService {
  rpc Export(ExportLogsServiceRequest) 
    returns (ExportLogsServiceResponse) {}
}
```

**Features**:

* Bidirectional streaming support
* Built-in compression (gzip)
* Connection multiplexing
* Automatic reconnection

**Starting gRPC Receiver**:

```bash
# Default port 4317
gonzo --otlp-enabled

# Custom port
gonzo --otlp-enabled --otlp-grpc-port=5317
```

#### HTTP Transport

**Endpoint**: `http://localhost:4318/v1/logs`

**Protocol**: HTTP/1.1 or HTTP/2

**Method**: POST

**Content-Type**: `application/json` or `application/x-protobuf`

**Features**:

* Standard HTTP clients work
* JSON encoding (more debuggable)
* No special libraries required
* Works through HTTP proxies

**Starting HTTP Receiver**:

```bash
# Default port 4318
gonzo --otlp-enabled

# Custom port
gonzo --otlp-enabled --otlp-http-port=5318
```

### OTLP Log Data Model

#### Structure Hierarchy

```
ExportLogsServiceRequest
└── ResourceLogs[]
    ├── Resource
    │   └── Attributes[]
    │       ├── service.name
    │       ├── host.name
    │       └── ... (resource attributes)
    └── ScopeLogs[]
        ├── Scope
        │   ├── name
        │   └── version
        └── LogRecords[]
            ├── timeUnixNano
            ├── observedTimeUnixNano
            ├── severityNumber
            ├── severityText
            ├── body (AnyValue)
            ├── attributes[]
            └── traceId/spanId (optional)
```

#### Resource Attributes

Resource attributes describe the source of logs:

```json
{
  "service.name": "payment-api",
  "service.version": "1.2.3",
  "host.name": "prod-server-01",
  "deployment.environment": "production",
  "cloud.provider": "aws",
  "cloud.region": "us-east-1"
}
```

**How Gonzo Uses Resource Attributes**:

* Merged with log record attributes
* Displayed in Attributes panel
* Available for filtering
* Shown in log details

#### Log Record

Individual log entry:

```json
{
  "timeUnixNano": "1705315805000000000",
  "observedTimeUnixNano": "1705315805123456789",
  "severityNumber": 13,  // ERROR
  "severityText": "error",
  "body": {
    "stringValue": "Database connection failed"
  },
  "attributes": [
    {"key": "user_id", "value": {"intValue": "12345"}},
    {"key": "endpoint", "value": {"stringValue": "/api/users"}},
    {"key": "error.type", "value": {"stringValue": "timeout"}}
  ],
  "traceId": "1234567890abcdef",
  "spanId": "1234567890abcdef"
}
```

**Gonzo Mapping**:

```
timeUnixNano        → Timestamp
severityText        → Level (error, warn, info, debug)
body                → Message
attributes          → Extracted to Attributes panel
traceId/spanId      → Available for tracing correlation
```

#### Severity Levels

OTLP defines numerical severity levels:

| Number | Name  | Gonzo Display |
| ------ | ----- | ------------- |
| 1-4    | TRACE | ⚪ White       |
| 5-8    | DEBUG | 🔵 Blue       |
| 9-12   | INFO  | 🟢 Green      |
| 13-16  | WARN  | 🟡 Yellow     |
| 17-20  | ERROR | 🔴 Red        |
| 21-24  | FATAL | 🔴 Red        |

Gonzo reads both `severityNumber` and `severityText` fields.

#### Body Types

The log body can be various types:

**String** (most common):

```json
{
  "body": {
    "stringValue": "User logged in"
  }
}
```

**Structured**:

```json
{
  "body": {
    "kvlistValue": {
      "values": [
        {"key": "event", "value": {"stringValue": "login"}},
        {"key": "user_id", "value": {"intValue": 12345}}
      ]
    }
  }
}
```

Gonzo handles all OTLP value types and displays them appropriately.

### Configuration Examples

#### OpenTelemetry Collector

**Configure collector to send to Gonzo**:

```yaml
# otel-collector-config.yaml
receivers:
  filelog:
    include: [/var/log/app/*.log]
  otlp:
    protocols:
      grpc:
        endpoint: 0.0.0.0:4317
      http:
        endpoint: 0.0.0.0:4318

processors:
  batch:
    timeout: 1s
    send_batch_size: 100

exporters:
  # Send to Gonzo via gRPC
  otlp/gonzo_grpc:
    endpoint: localhost:4317
    tls:
      insecure: true
  
  # Or via HTTP
  otlphttp/gonzo_http:
    endpoint: http://localhost:4318/v1/logs

service:
  pipelines:
    logs:
      receivers: [filelog, otlp]
      processors: [batch]
      exporters: [otlp/gonzo_grpc]  # or otlphttp/gonzo_http
```

**Start collector and Gonzo**:

```bash
# Terminal 1: Start Gonzo
gonzo --otlp-enabled

# Terminal 2: Start collector
otelcol --config otel-collector-config.yaml
```

#### Application SDK Integration

**Python Example**:

```python
from opentelemetry import _logs
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporter
from opentelemetry.sdk.resources import Resource
import logging

# Create resource with service information
resource = Resource.create({
    "service.name": "my-python-app",
    "service.version": "1.0.0",
    "deployment.environment": "production"
})

# Configure OTLP exporter (gRPC)
exporter = OTLPLogExporter(
    endpoint="localhost:4317",
    insecure=True
)

# Set up logger provider
logger_provider = LoggerProvider(resource=resource)
logger_provider.add_log_record_processor(
    BatchLogRecordProcessor(exporter)
)
_logs.set_logger_provider(logger_provider)

# Integrate with standard logging
handler = LoggingHandler(
    level=logging.NOTSET,
    logger_provider=logger_provider
)
logging.getLogger().addHandler(handler)
logging.getLogger().setLevel(logging.INFO)

# Now logs go to Gonzo
logging.info("Application started")
logging.error("Something went wrong", extra={
    "user_id": 12345,
    "endpoint": "/api/users"
})
```

**Go Example**:

```go
package main

import (
    "context"
    "go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc"
    "go.opentelemetry.io/otel/log"
    "go.opentelemetry.io/otel/sdk/log"
    "go.opentelemetry.io/otel/sdk/resource"
    semconv "go.opentelemetry.io/otel/semconv/v1.24.0"
)

func main() {
    // Create resource
    res, _ := resource.New(context.Background(),
        resource.WithAttributes(
            semconv.ServiceName("my-go-app"),
            semconv.ServiceVersion("1.0.0"),
        ),
    )

    // Create OTLP exporter
    exporter, _ := otlploggrpc.New(context.Background(),
        otlploggrpc.WithEndpoint("localhost:4317"),
        otlploggrpc.WithInsecure(),
    )

    // Create logger provider
    provider := sdklog.NewLoggerProvider(
        sdklog.WithResource(res),
        sdklog.WithProcessor(sdklog.NewBatchProcessor(exporter)),
    )
    defer provider.Shutdown(context.Background())

    // Get logger
    logger := provider.Logger("app-logger")

    // Send logs
    logger.Emit(context.Background(), log.Record{
        Severity:  log.SeverityInfo,
        Body:      log.StringValue("Application started"),
    })
}
```

**Node.js Example**:

```javascript
const { LoggerProvider } = require('@opentelemetry/sdk-logs');
const { OTLPLogExporter } = require('@opentelemetry/exporter-logs-otlp-grpc');
const { Resource } = require('@opentelemetry/resources');
const { SemanticResourceAttributes } = require('@opentelemetry/semantic-conventions');

// Create resource
const resource = new Resource({
  [SemanticResourceAttributes.SERVICE_NAME]: 'my-node-app',
  [SemanticResourceAttributes.SERVICE_VERSION]: '1.0.0',
});

// Create exporter
const exporter = new OTLPLogExporter({
  url: 'grpc://localhost:4317',
});

// Create logger provider
const loggerProvider = new LoggerProvider({ resource });
loggerProvider.addLogRecordProcessor(
  new BatchLogRecordProcessor(exporter)
);

// Get logger
const logger = loggerProvider.getLogger('app-logger');

// Send logs
logger.emit({
  severityText: 'INFO',
  body: 'Application started',
  attributes: {
    userId: 12345,
    endpoint: '/api/users',
  },
});
```

### HTTP API Reference

#### POST /v1/logs

**Request Format** (JSON):

```json
{
  "resourceLogs": [
    {
      "resource": {
        "attributes": [
          {
            "key": "service.name",
            "value": { "stringValue": "my-service" }
          }
        ]
      },
      "scopeLogs": [
        {
          "scope": {
            "name": "my-logger"
          },
          "logRecords": [
            {
              "timeUnixNano": "1705315805000000000",
              "severityNumber": 9,
              "severityText": "info",
              "body": {
                "stringValue": "Log message"
              },
              "attributes": [
                {
                  "key": "user_id",
                  "value": { "intValue": "12345" }
                }
              ]
            }
          ]
        }
      ]
    }
  ]
}
```

**Response** (Success):

```json
{
  "partialSuccess": {}
}
```

**Response** (Partial Failure):

```json
{
  "partialSuccess": {
    "rejectedLogRecords": 5,
    "errorMessage": "Some records were invalid"
  }
}
```

**Status Codes**:

* `200 OK` - All logs accepted
* `206 Partial Content` - Some logs rejected (see partialSuccess)
* `400 Bad Request` - Invalid request format
* `500 Internal Server Error` - Server error

#### Testing HTTP Endpoint

```bash
# Simple test
curl -X POST http://localhost:4318/v1/logs \
  -H "Content-Type: application/json" \
  -d '{
    "resourceLogs": [
      {
        "scopeLogs": [
          {
            "logRecords": [
              {
                "timeUnixNano": "1705315805000000000",
                "severityText": "info",
                "body": {"stringValue": "Test log"}
              }
            ]
          }
        ]
      }
    ]
  }'

# Should see log appear in Gonzo
```

### gRPC API Reference

#### Service: opentelemetry.proto.collector.logs.v1.LogsService

**Method**: Export

**Request**: ExportLogsServiceRequest

**Response**: ExportLogsServiceResponse

**Protocol Buffers Definition**:

```protobuf
service LogsService {
  rpc Export(ExportLogsServiceRequest) 
    returns (ExportLogsServiceResponse) {}
}

message ExportLogsServiceRequest {
  repeated ResourceLogs resource_logs = 1;
}

message ExportLogsServiceResponse {
  ExportLogsPartialSuccess partial_success = 1;
}

message ExportLogsPartialSuccess {
  int64 rejected_log_records = 1;
  string error_message = 2;
}
```

#### Testing gRPC Endpoint

```bash
# Using grpcurl
grpcurl -plaintext \
  -d '{
    "resource_logs": [{
      "scope_logs": [{
        "log_records": [{
          "time_unix_nano": "1705315805000000000",
          "severity_text": "info",
          "body": {"string_value": "Test log"}
        }]
      }]
    }]
  }' \
  localhost:4317 \
  opentelemetry.proto.collector.logs.v1.LogsService/Export
```

### Performance & Optimization

#### Batching

Gonzo processes logs in batches for efficiency:

**Incoming Batches**:

* OTLP senders should batch logs (recommended 100-1000 per batch)
* Reduces network overhead
* Improves throughput

**Internal Processing**:

* Logs processed individually after receipt
* Real-time display without buffering delay

#### Concurrency

**gRPC Handler**:

* Concurrent request handling
* One goroutine per connection
* Thread-safe log ingestion

**HTTP Handler**:

* Standard HTTP server concurrency
* Multiple simultaneous POST requests supported

#### Memory Management

**Bounded Buffers**:

* OTLP messages are streamed, not accumulated
* Converted logs go to main log buffer (configurable size)
* No unlimited memory growth

**Large Messages**:

* Default max receive message size: 4MB (configurable)
* Larger messages can be split by sender

```bash
# Increase max message size if needed
# (requires code modification currently)
```

### Security Considerations

#### TLS/SSL

**Production Recommendation**: Always use TLS in production.

**Current Implementation**:

* gRPC: Insecure mode (no TLS)
* HTTP: Plain HTTP

**For Production Use**:

* Run Gonzo behind TLS-terminating proxy (nginx, envoy)
* Use OTLP collector with TLS, forward to Gonzo locally

**Example with nginx**:

```nginx
server {
    listen 443 ssl http2;
    server_name gonzo.example.com;
    
    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;
    
    # gRPC proxy
    location / {
        grpc_pass grpc://localhost:4317;
    }
}
```

#### Authentication

**Current Implementation**: No built-in authentication

**Recommendations**:

* Use in trusted networks only
* Deploy behind authenticated proxy
* Use firewall rules to restrict access
* Consider VPN for remote access

#### Network Isolation

**Best Practice**: Don't expose OTLP ports to public internet

```bash
# Bind to localhost only (default)
gonzo --otlp-enabled  # Listens on 127.0.0.1

# For containers, use bridge networking
# For Kubernetes, use ClusterIP service
```

### Troubleshooting OTLP Issues

#### Connection Refused

**Symptom**: Sender can't connect to Gonzo

**Checks**:

```bash
# Verify Gonzo is running with OTLP enabled
ps aux | grep gonzo

# Check ports are listening
lsof -i :4317  # gRPC
lsof -i :4318  # HTTP

# Test connectivity
telnet localhost 4317
curl http://localhost:4318/v1/logs
```

#### Logs Not Appearing

**Symptom**: Connection works but no logs in Gonzo

**Diagnosis**:

1. Check request format matches OTLP spec
2. Verify severityText or severityNumber is set
3. Check body field is present
4. Look for error responses from Gonzo

**Test with minimal payload**:

```bash
curl -X POST http://localhost:4318/v1/logs \
  -H "Content-Type: application/json" \
  -d '{"resourceLogs":[{"scopeLogs":[{"logRecords":[{"body":{"stringValue":"test"}}]}]}]}'
```

#### Message Size Exceeded

**Symptom**: "message size exceeded" errors

**Solution**:

* Reduce batch size in sender
* Split large log messages
* Currently no config option (fixed at 4MB)

#### Performance Issues

**Symptom**: Slow log processing or high CPU

**Solutions**:

```bash
# Reduce update frequency
gonzo --otlp-enabled --update-interval=5s

# Reduce buffer sizes
gonzo --otlp-enabled --log-buffer=500
```

### Compatibility

#### OTLP Version Support

* **Specification Version**: 1.0.0+
* **Protocol Version**: v1
* **Backward Compatibility**: Follows semantic versioning

#### OpenTelemetry SDK Compatibility

Tested with:

* ✅ OpenTelemetry Collector v0.90+
* ✅ Python SDK v1.20+
* ✅ Go SDK v1.20+
* ✅ Node.js SDK v0.45+
* ✅ Java SDK v1.32+
* ✅ .NET SDK v1.6+

#### Transport Support Matrix

| Transport | Encoding | Status          |
| --------- | -------- | --------------- |
| gRPC      | Protobuf | ✅ Supported     |
| HTTP      | JSON     | ✅ Supported     |
| HTTP      | Protobuf | ✅ Supported     |
| WebSocket | -        | ❌ Not supported |

### Future Enhancements

**Planned Features**:

* TLS support (direct, without proxy)
* Authentication (API keys, mTLS)
* Compression (gzip, zstd)
* Configurable message size limits
* Metrics export (self-monitoring)
* Multiple OTLP receivers (different ports for different sources)

### Resources

#### Specifications

* [OTLP Specification](https://opentelemetry.io/docs/specs/otlp/)
* [OTLP Log Data Model](https://opentelemetry.io/docs/specs/otel/logs/data-model/)
* [Protocol Buffers](https://protobuf.dev/)

#### OpenTelemetry Documentation

* [OpenTelemetry Logs](https://opentelemetry.io/docs/concepts/signals/logs/)
* [Collector Configuration](https://opentelemetry.io/docs/collector/configuration/)
* [SDK Documentation](https://opentelemetry.io/docs/instrumentation/)

#### Related Gonzo Docs

* Architecture Overview
* Common Issues - OTLP
* Configuration Reference

{% hint style="success" %}
**Quick Start**: `gonzo --otlp-enabled` starts both gRPC (4317) and HTTP (4318) receivers. Point your OTLP exporter to these endpoints and logs will appear in Gonzo immediately!
{% endhint %}


# Extension Points


# Changelog

All notable changes to Gonzo are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

### [Unreleased](https://github.com/control-theory/gonzo/compare/v0.1.6...HEAD)

#### Added

* Additional documentation and examples
* Enhanced GitBook documentation site

#### Changed

* Improved error messages and user feedback

#### Fixed

* Various bug fixes and stability improvements

### [0.1.6](https://github.com/control-theory/gonzo/releases/tag/v0.1.6) - 2024-08-27

#### Added

* Full screen log viewing with `f` key
* Extended character limit for search and filter (200 chars)
* Increased OTLP receive message size for larger log payloads

#### Changed

* Improved search and filter input handling
* Enhanced OTLP receiver performance

#### Fixed

* Search and filter character limit issues
* OTLP message size limitations

#### Contributors

* @destari - Full screen viewing feature
* @rbg - OTLP message size improvements
* @jon-spyder - Search/filter character limit
* @vine-mxm - Documentation updates

### [0.1.5](https://github.com/control-theory/gonzo/releases/tag/v0.1.5) - 2024-08-24

#### Fixed

* OTLP handling now matches stdin processing
* Improved OTLP log receiver stability

#### Changed

* Unified OTLP and stdin log processing pipeline
* Better error handling for OTLP connections

#### Contributors

* @destari - OTLP handling fixes

### [0.1.4](https://github.com/control-theory/gonzo/releases/tag/v0.1.4) - 2024-08-21

#### Added

* Enhanced pattern extraction with drain3 algorithm
* Improved service distribution tracking
* Better severity-specific pattern analysis

#### Changed

* Optimized pattern detection performance
* Improved Counts modal visualization

#### Fixed

* Pattern extraction accuracy improvements
* Service tracking edge cases

### [0.1.3](https://github.com/control-theory/gonzo/releases/tag/v0.1.3) - 2024-08-15

#### Added

* AI model selection modal (`m` key)
* Support for multiple AI providers (OpenAI, Ollama, LM Studio)
* Automatic model detection and selection
* AI chat mode for interactive log analysis

#### Changed

* Improved AI integration architecture
* Better model compatibility checking
* Enhanced AI response formatting

#### Fixed

* AI provider connection issues
* Model switching stability

### [0.1.2](https://github.com/control-theory/gonzo/releases/tag/v0.1.2) - 2024-08-10

#### Added

* Custom log format support
* Format configuration via YAML files
* Built-in formats for Loki and common log types
* Format auto-detection improvements

#### Changed

* Enhanced log parsing flexibility
* Improved format detection accuracy

#### Fixed

* Format detection edge cases
* Custom format loading issues

### [0.1.1](https://github.com/control-theory/gonzo/releases/tag/v0.1.1) - 2024-08-05

#### Added

* Custom skins/themes support
* Multiple built-in themes (Dracula, Nord, Monokai, etc.)
* Theme configuration via YAML
* ControlTheory branded themes

#### Changed

* Improved color scheme architecture
* Better theme switching performance

#### Fixed

* Theme rendering issues
* Color contrast problems

### [0.1.0](https://github.com/control-theory/gonzo/releases/tag/v0.1.0) - 2024-08-01

#### Added

* Initial public release
* Real-time log analysis TUI
* OTLP receiver (gRPC and HTTP)
* AI-powered log insights
* Pattern detection with drain3
* Word frequency tracking
* Attribute extraction and analysis
* Counts modal with heatmap visualization
* File input with glob support
* Follow mode (tail -f behavior)
* Multiple log format support (JSON, logfmt, plain text)
* Configurable update intervals
* Pause/resume functionality
* Search and filter capabilities
* Vim-style navigation
* Mouse support
* 11+ built-in themes
* Configuration file support

#### Technical Details

* Built with Bubble Tea TUI framework
* Lipgloss for styling
* Cobra for CLI
* Viper for configuration
* OpenTelemetry OTLP support
* Go 1.21+ required

### Version History Summary

| Version | Date       | Highlights                           |
| ------- | ---------- | ------------------------------------ |
| 0.1.6   | 2024-08-27 | Full screen viewing, extended search |
| 0.1.5   | 2024-08-24 | OTLP handling improvements           |
| 0.1.4   | 2024-08-21 | Enhanced pattern extraction          |
| 0.1.3   | 2024-08-15 | AI model selection, multi-provider   |
| 0.1.2   | 2024-08-10 | Custom log formats                   |
| 0.1.1   | 2024-08-05 | Custom skins/themes                  |
| 0.1.0   | 2024-08-01 | Initial release                      |

### Upgrade Notes

#### Upgrading to 0.1.6

**No breaking changes**. New features available immediately:

* Press `f` in log viewer for full screen mode
* Search and filter now support up to 200 characters
* OTLP receiver handles larger messages

#### Upgrading to 0.1.5

**No breaking changes**. OTLP improvements are automatic.

#### Upgrading to 0.1.4

**No breaking changes**. Pattern extraction improvements are automatic.

#### Upgrading to 0.1.3

**New AI features**:

* Press `m` to select AI models
* Automatic model detection for Ollama and LM Studio
* No configuration changes needed

#### Upgrading to 0.1.2

**Custom formats now supported**:

* Place format files in `~/.config/gonzo/formats/`
* Use `--format=name` to specify custom format
* See documentation for format syntax

#### Upgrading to 0.1.1

**Custom skins now supported**:

* Place skin files in `~/.config/gonzo/skins/`
* Use `--skin=name` or set in config file
* See documentation for skin syntax

#### Upgrading to 0.1.0

Initial release - no upgrade path.

### Installation Methods

#### Go Install

```bash
go install github.com/control-theory/gonzo/cmd/gonzo@latest
```

#### Homebrew

```bash
brew tap control-theory/gonzo
brew install gonzo
```

#### Binary Download

Download from [GitHub Releases](https://github.com/control-theory/gonzo/releases)

#### Build from Source

```bash
git clone https://github.com/control-theory/gonzo.git
cd gonzo
make build
```

### Deprecations

No features have been deprecated yet.

### Breaking Changes

No breaking changes in any release to date.

### Known Issues

#### Current Known Issues

* **Custom formats**: Some complex regex patterns may have performance impact
* **OTLP**: Very large batch sizes may cause memory spikes
* **AI**: Rate limiting may occur with high-frequency analysis requests
* **Terminal**: Some older terminals may have limited mouse support

See [GitHub Issues](https://github.com/control-theory/gonzo/issues) for complete list.

### Roadmap

#### Upcoming Features

**Short-term (Next Release)**:

* Performance optimizations for high-volume logs
* Additional built-in log formats
* Enhanced AI prompt templates
* Better error messages

**Medium-term (3-6 months)**:

* Plugin system for custom extensions
* Export and reporting capabilities
* Additional AI provider support
* Advanced filtering DSL

**Long-term (6+ months)**:

* Distributed log analysis
* Web-based interface option
* Log aggregation features
* Enterprise features

See [GitHub Projects](https://github.com/control-theory/gonzo/projects) for detailed roadmap.

### Contributing

We welcome contributions! See:

* Contributing Guidelines
* Development Setup
* [GitHub Issues](https://github.com/control-theory/gonzo/issues)

### Release Process

1. **Version Bump**: Update version in code
2. **Changelog**: Update this file
3. **Tag**: Create git tag (e.g., `v0.1.6`)
4. **Push**: Push tag to GitHub
5. **Build**: GitHub Actions builds binaries
6. **Release**: Automated release creation
7. **Announce**: Community announcement

### Support

* **Documentation**: <https://docs.controltheory.com/gonzo>
* **Issues**: <https://github.com/control-theory/gonzo/issues>
* **Discussions**: <https://github.com/control-theory/gonzo/discussions>
* **Email**: <support@controltheory.com>

### License

Gonzo is licensed under the MIT License. See [LICENSE](https://github.com/control-theory/gonzo/blob/main/LICENSE) for details.

### Credits

#### Core Team

* [ControlTheory](https://github.com/control-theory) - Development and maintenance

#### Contributors

Thanks to all contributors! See [Contributors](https://github.com/control-theory/gonzo/graphs/contributors) for complete list.

#### Special Thanks

* [Charm](https://charm.sh/) - Bubble Tea, Lipgloss, Bubbles
* [OpenTelemetry](https://opentelemetry.io/) - OTLP specification
* [k9s](https://k9scli.io/) - TUI inspiration
* Community contributors and users

### Archive

For historical versions before 0.1.0, see the [Git history](https://github.com/control-theory/gonzo/commits/main).

***

### Changelog Format

This changelog follows these conventions:

* **Added**: New features
* **Changed**: Changes to existing functionality
* **Deprecated**: Soon-to-be removed features
* **Removed**: Removed features
* **Fixed**: Bug fixes
* **Security**: Security fixes

**Version Format**: `MAJOR.MINOR.PATCH`

* **MAJOR**: Breaking changes
* **MINOR**: New features (backward compatible)
* **PATCH**: Bug fixes (backward compatible)

***

{% hint style="info" %}
**Stay Updated**: Watch the [GitHub repository](https://github.com/control-theory/gonzo) to be notified of new releases.
{% endhint %}

{% hint style="success" %}
**Latest Version**: Check [Releases](https://github.com/control-theory/gonzo/releases) for the most recent version and download links.
{% endhint %}


# Input Methods Overflow

Gonzo offers multiple powerful ways to feed log data into its analysis engine. From simple file analysis to real-time OpenTelemetry streams, this guide covers all input methods and their optimal use cases.

### Input Method Overview

Gonzo supports four primary input methods, each optimized for different scenarios:

| Method                | Best For                       | Command Example                | Real-time? |
| --------------------- | ------------------------------ | ------------------------------ | ---------- |
| **📁 File Input**     | Static log analysis, debugging | `gonzo -f app.log`             | No         |
| **📈 File Following** | Real-time monitoring           | `gonzo -f app.log --follow`    | Yes        |
| **🔄 Stdin Piping**   | Integration with tools         | `kubectl logs -f pod \| gonzo` | Yes        |
| **🌐 OTLP Receiver**  | OpenTelemetry integration      | `gonzo --otlp-enabled`         | Yes        |

### File Input Methods

#### Single File Analysis

Perfect for debugging specific issues or analyzing archived logs:

```bash
# Basic file analysis
gonzo -f application.log

# Absolute paths
gonzo -f /var/log/nginx/access.log

# Relative paths  
gonzo -f logs/app.log

# Compressed files (via piping)
zcat app.log.gz | gonzo
gunzip -c error.log.gz | gonzo
```

**Best Practices:**

* Start with single files to understand the data structure
* Use absolute paths to avoid "file not found" errors
* Check file permissions if Gonzo can't access the file

#### Multiple File Analysis

Combine logs from related services for comprehensive analysis:

```bash
# Multiple specific files
gonzo -f api.log -f database.log -f cache.log

# Mix different log types
gonzo -f application.log -f /var/log/syslog -f error.log

# Different directories
gonzo -f /var/log/app.log -f /home/user/debug.log
```

{% tabs %}
{% tab title="Related Services" %}
**Microservices Architecture:**

```bash
# Analyze all service logs together
gonzo -f api-gateway.log -f user-service.log -f payment-service.log

# Include infrastructure logs
gonzo -f app.log -f nginx.log -f postgres.log
```

**Benefits:**

* Correlate events across services
* See timing relationships
* Identify cascade failures
  {% endtab %}

{% tab title="Different Severities" %}
**Separate Log Levels:**

```bash
# Combine different severity files
gonzo -f application.log -f error.log -f debug.log

# Include system and application logs
gonzo -f app.log -f /var/log/syslog
```

**Benefits:**

* Complete picture of system state
* Context around error events
* Debug information correlation
  {% endtab %}
  {% endtabs %}

#### Glob Pattern Input

Automatically include multiple files using pattern matching:

```bash
# All .log files in current directory
gonzo -f "*.log"

# All log files in a directory
gonzo -f "/var/log/*.log"

# Specific patterns
gonzo -f "/var/log/app-*.log"
gonzo -f "/logs/**/*.log"

# Multiple patterns
gonzo -f "/var/log/app*.log" -f "/var/log/nginx*.log"
```

**Glob Pattern Examples:**

| Pattern                | Matches                                 | Use Case                  |
| ---------------------- | --------------------------------------- | ------------------------- |
| `"*.log"`              | All .log files in current dir           | Development debugging     |
| `"/var/log/*.log"`     | All .log files in /var/log              | System administration     |
| `"app-*.log"`          | app-2024.log, app-error.log             | Application-specific logs |
| `"/logs/**/*.log"`     | All .log files recursively              | Complex log hierarchies   |
| `"*-{error,warn}.log"` | Files ending in -error.log or -warn.log | Specific severity levels  |

{% hint style="warning" %}
**Important:** Always quote glob patterns to prevent shell expansion. Use `"*.log"` not `*.log`.
{% endhint %}

**Advanced Glob Techniques:**

```bash
# Rotated log files
gonzo -f "/var/log/app.log*"  # app.log, app.log.1, app.log.2, etc.

# Date-based logs
gonzo -f "/logs/app-2024-*.log"  # app-2024-01-15.log, etc.

# Multiple services with patterns
gonzo -f "/var/log/{nginx,apache}/*.log"

# Exclude certain files (use find + piping)
find /var/log -name "*.log" ! -name "*debug*" -exec gonzo -f {} +
```

### Real-Time File Following

Monitor logs as they grow, similar to `tail -f`:

#### Basic Following

```bash
# Follow a single file
gonzo -f /var/log/app.log --follow

# Follow multiple files
gonzo -f app.log -f error.log --follow

# Follow with glob patterns
gonzo -f "/var/log/*.log" --follow
```

**How Following Works:**

* Gonzo monitors files for changes using inotify (Linux) or similar mechanisms
* New log entries appear automatically in the interface
* Handles log rotation gracefully
* Efficiently processes only new content

#### Advanced Following Scenarios

{% tabs %}
{% tab title="Application Monitoring" %}
**Development Environment:**

```bash
# Follow application logs during development
gonzo -f logs/app.log --follow

# Include error logs
gonzo -f logs/app.log -f logs/error.log --follow

# With configuration
gonzo -f logs/*.log --follow --log-buffer=5000
```

**Production Monitoring:**

```bash
# Monitor production logs
gonzo -f /var/log/myapp/*.log --follow

# Include system logs
gonzo -f /var/log/myapp.log -f /var/log/syslog --follow
```

{% endtab %}

{% tab title="System Administration" %}
**Security Monitoring:**

```bash
# Monitor security logs
sudo gonzo -f /var/log/auth.log --follow

# Multiple security sources
sudo gonzo -f "/var/log/{auth,secure,audit}*.log" --follow
```

**Performance Monitoring:**

```bash
# Monitor performance-related logs
gonzo -f /var/log/nginx/access.log -f /var/log/app/perf.log --follow

# System resource logs
gonzo -f /var/log/syslog -f /var/log/kern.log --follow
```

{% endtab %}
{% endtabs %}

#### Following Best Practices

**Performance Optimization:**

```bash
# Large files - adjust buffer size
gonzo -f huge.log --follow --log-buffer=10000

# High-frequency logs - slower updates
gonzo -f busy.log --follow --update-interval=5s

# Memory-constrained systems
gonzo -f app.log --follow --memory-size=5000
```

**Monitoring Multiple Sources:**

```bash
# Start with most important logs
gonzo -f app.log --follow

# Add more sources gradually
gonzo -f app.log -f error.log --follow

# Full monitoring setup
gonzo -f "/var/log/app/*.log" --follow --log-buffer=5000 --update-interval=2s
```

### Stdin Processing (Piping)

Integrate Gonzo with existing tools and command pipelines:

#### Basic Piping

```bash
# Basic piping from other commands
cat application.log | gonzo

# Process compressed logs
zcat app.log.gz | gonzo
gunzip -c logs.gz | gonzo

# Stream from remote systems
ssh server "cat /var/log/app.log" | gonzo
```

#### Real-Time Streaming

**Traditional Unix Tools:**

```bash
# Stream with tail
tail -f /var/log/app.log | gonzo

# Multiple files with tail
tail -f /var/log/*.log | gonzo

# Advanced tailing with multitail
multitail -f /var/log/app.log /var/log/error.log | gonzo
```

**System Monitoring:**

```bash
# System logs
sudo tail -f /var/log/syslog | gonzo

# Journal logs (systemd)
journalctl -f | gonzo

# Specific service logs
journalctl -f -u nginx | gonzo
```

#### Container Integration

{% tabs %}
{% tab title="Docker" %}
**Single Container:**

```bash
# Current container logs
docker logs my-container | gonzo

# Follow container logs
docker logs -f my-container 2>&1 | gonzo

# Multiple containers
docker logs -f container1 container2 2>&1 | gonzo
```

**Docker Compose:**

```bash
# All services
docker-compose logs -f | gonzo

# Specific services
docker-compose logs -f web api database | gonzo

# With timestamps
docker-compose logs -f -t | gonzo
```

{% endtab %}

{% tab title="Kubernetes" %}
**Pod Logs:**

```bash
# Single pod
kubectl logs -f pod/my-app | gonzo

# Deployment logs
kubectl logs -f deployment/my-app | gonzo

# Multiple pods
kubectl logs -f -l app=backend | gonzo
```

**Advanced Kubernetes:**

```bash
# Previous container instance
kubectl logs -f pod/my-app --previous | gonzo

# Specific container in pod
kubectl logs -f pod/my-app -c sidecar | gonzo

# All containers in pod
kubectl logs -f pod/my-app --all-containers | gonzo
```

**With Stern (if installed):**

```bash
# All pods with label
stern backend | gonzo

# Pods in specific namespace
stern . -n production | gonzo

# With context and coloring
stern api --context=prod --color=always | gonzo
```

{% endtab %}
{% endtabs %}

#### Advanced Piping Scenarios

**Network Sources:**

```bash
# Remote syslog
nc -l 514 | gonzo

# SSH tunneling
ssh -L 8514:logserver:514 server "nc localhost 8514" | gonzo

# HTTP log streaming
curl -s http://logserver/stream | gonzo
```

**Complex Processing:**

<pre class="language-bash"><code class="lang-bash"># Filter before Gonzo
<strong>tail -f /var/log/app.log | grep -v DEBUG | gonzo
</strong>
# Transform data
tail -f /var/log/app.log | sed 's/old/new/g' | gonzo

# Multiple sources combined
( tail -f app.log &#x26; tail -f error.log ) | gonzo
</code></pre>

### Input Method Selection Guide

Choose the right input method based on your scenario:

#### Development & Debugging

```bash
# Local development - single application
gonzo -f logs/app.log --follow

# Debugging specific issues
gonzo -f error.log

# Multiple local services
gonzo -f "logs/*.log" --follow
```

#### Production Monitoring

```bash
# Container environments
kubectl logs -f deployment/app | gonzo

# Traditional servers
gonzo -f "/var/log/app/*.log" --follow

# OpenTelemetry-enabled applications
gonzo --otlp-enabled
```

#### System Administration

```bash
# System health monitoring
sudo gonzo -f "/var/log/{syslog,auth.log,kern.log}" --follow

# Security analysis
sudo tail -f /var/log/auth.log | gonzo

# Performance investigation
gonzo -f "/var/log/nginx/*.log"
```

#### Integration Scenarios

```bash
# CI/CD pipelines
build-logs | gonzo

# Monitoring alerts
alert-stream | gonzo

# Log aggregation
rsyslog-stream | gonzo
```

### Performance Considerations

#### Buffer Sizing

Optimize for your log volume and available memory:

```bash
# High-volume logs
gonzo -f busy.log --log-buffer=10000 --memory-size=20000

# Memory-constrained systems
gonzo -f app.log --log-buffer=1000 --memory-size=5000

# Balanced configuration
gonzo -f app.log --log-buffer=2000 --memory-size=15000
```

#### Update Intervals

Balance responsiveness with system resources:

```bash
# Real-time responsiveness (default)
gonzo -f app.log --follow --update-interval=1s

# Balanced performance
gonzo -f app.log --follow --update-interval=2s

# Resource conservation
gonzo -f app.log --follow --update-interval=5s
```

#### Input-Specific Optimizations

| Input Method       | Optimization                      | Configuration                  |
| ------------------ | --------------------------------- | ------------------------------ |
| **File Following** | Use larger buffers                | `--log-buffer=5000`            |
| **Stdin Piping**   | Ensure smooth pipeline            | \`command                      |
| **OTLP**           | Tune batch sizes                  | OpenTelemetry collector config |
| **Multiple Files** | Balance file count vs performance | Combine related files          |

### Troubleshooting Input Issues

#### File Access Problems

```bash
# Permission denied
sudo gonzo -f /var/log/secure.log

# File not found with globs
gonzo -f "/path/to/*.log"  # Use quotes!

# Check file permissions
ls -la logfile.log
```

#### Following Issues

```bash
# File rotation problems
# Gonzo handles this automatically, but check:
ls -la /var/log/app.log*

# High CPU usage
# Reduce update frequency:
gonzo -f app.log --follow --update-interval=5s
```

#### Piping Problems

```bash
# Broken pipe errors
# Ensure Gonzo can handle the data rate:
slow-producer | gonzo --log-buffer=10000

# Buffer full issues
# Increase buffer size or filter at source:
noisy-source | grep -v DEBUG | gonzo
```

### Advanced Input Patterns

#### Hybrid Approaches

Combine multiple input methods for comprehensive monitoring:

```bash
# OTLP + file backup
gonzo --otlp-enabled -f backup.log --follow

# Real-time + historical analysis
# Terminal 1: gonzo -f app.log --follow
# Terminal 2: gonzo -f historical-logs.log

# Primary + secondary sources
gonzo -f primary.log --follow & kubectl logs -f secondary | gonzo
```

#### Custom Input Scripts

Create wrapper scripts for complex scenarios:

```bash
#!/bin/bash
# monitor-all.sh
exec gonzo \
  -f "/var/log/app/*.log" \
  -f "/var/log/nginx/*.log" \
  --follow \
  --log-buffer=5000 \
  --update-interval=2s
```


# AI Setup & Configuration

Get AI-powered log analysis working in minutes. This guide covers everything from basic API key setup to advanced configuration options for all supported AI providers.

{% hint style="success" %}
**Quick Start:** Set `OPENAI_API_KEY` environment variable and run `gonzo -f your-logs.log --ai-model="gpt-4"`. That's it!
{% endhint %}

### Choose Your Setup Path

Select the approach that best fits your needs:

{% tabs %}
{% tab title="Local AI (Ollama)" %}
**Best for: Privacy, unlimited usage, no API costs**

**Requirements:**

* 8GB+ RAM (16GB+ recommended)
* Local compute resources
* Ollama installation

**Setup time:** 10-15 minutes
{% endtab %}

{% tab title="Local AI (LM Studio)" %}
**Best for: Development, testing, easy local setup**

**Requirements:**

* 8GB+ RAM
* LM Studio application
* Downloaded model

**Setup time:** 5-10 minutes
{% endtab %}

{% tab title="OpenAI API" %}
**Best for: Production use, reliability, best AI quality**

**Requirements:**

* OpenAI API account
* Valid API key with credits
* Internet connection

**Setup time:** 2-3 minutes
{% endtab %}

{% tab title="Custom API" %}
**Best for: Enterprise, existing AI infrastructure**

**Requirements:**

* OpenAI-compatible API endpoint
* Authentication credentials
* Network access to API

**Setup time:** 5-15 minutes
{% endtab %}
{% endtabs %}

### OpenAI Setup

#### Step 1: Get Your API Key

1. **Visit** [**OpenAI API Platform**](https://platform.openai.com/)
2. **Create account or sign in**
3. **Navigate to API Keys** (<https://platform.openai.com/api-keys>)
4. **Create new secret key**
5. **Copy the key** (starts with `sk-`)

{% hint style="warning" %}
**Important:** Save your API key securely. OpenAI only shows it once, and you'll need it for Gonzo configuration.
{% endhint %}

#### Step 2: Configure Environment

**Method 1: Environment Variable (Recommended)**

```bash
# Add to your ~/.bashrc, ~/.zshrc, or ~/.profile
export OPENAI_API_KEY="sk-your-actual-api-key-here"

# Reload your shell configuration
source ~/.bashrc  # or ~/.zshrc
```

**Method 2: Session Variable**

```bash
# Set for current session only
export OPENAI_API_KEY="sk-your-actual-api-key-here"

# Verify it's set
echo $OPENAI_API_KEY
```

**Method 3: Configuration File**

```bash
# Create Gonzo config file
mkdir -p ~/.config/gonzo
cat > ~/.config/gonzo/config.yml << EOF
# AI Configuration
ai-model: "gpt-4"

# Environment variables can also be set in config
# But API keys are more secure as environment variables
EOF
```

#### Step 3: Test Your Setup

```bash
# Test with automatic model selection
gonzo -f your-logs.log

# Test with specific model
gonzo -f your-logs.log --ai-model="gpt-4"

# Test with cheaper model for development
gonzo -f your-logs.log --ai-model="gpt-3.5-turbo"
```

#### Step 4: Verify AI Features Work

```bash
# 1. Start Gonzo with your logs
gonzo -f application.log --ai-model="gpt-4"

# 2. Navigate to a log entry and press 'i'
# You should see AI analysis of the log entry

# 3. Try the model switcher with 'm'
# You should see available OpenAI models

# 4. Test AI chat with 'c' in log details
# You should be able to have a conversation about the logs
```

### Local AI Setup (Ollama)

#### Step 1: Install Ollama

{% tabs %}
{% tab title="Linux" %}

```bash
# Install Ollama
curl -fsSL https://ollama.ai/install.sh | sh

# Verify installation
ollama --version
```

{% endtab %}

{% tab title="macOS" %}

```bash
# Option 1: Download from website
# Visit https://ollama.ai/download and download macOS installer

# Option 2: Homebrew
brew install ollama

# Verify installation
ollama --version
```

{% endtab %}

{% tab title="Windows" %}

```bash
# Download from https://ollama.ai/download
# Run the installer
# Open PowerShell or Command Prompt

# Verify installation
ollama --version
```

{% endtab %}
{% endtabs %}

#### Step 2: Start Ollama Service

```bash
# Start Ollama server (required for Gonzo to connect)
ollama serve

# This should show:
# Ollama is running on http://localhost:11434
```

{% hint style="info" %}
**Keep this running:** The `ollama serve` command needs to stay running for Gonzo to access AI features. Consider running it in a separate terminal or as a background service.
{% endhint %}

#### Step 3: Download AI Models

```bash
# Download recommended models for log analysis
ollama pull llama3        # Good general-purpose model (4.7GB)
ollama pull mistral       # Faster, smaller model (4.1GB)
ollama pull codellama     # Good for technical logs (3.8GB)

# Or download a larger, more capable model
ollama pull llama3:70b    # Very capable but requires 40GB+ RAM

# List available models
ollama list
```

**Model Recommendations by System:**

| RAM   | Recommended Model | Size  | Performance                    |
| ----- | ----------------- | ----- | ------------------------------ |
| 8GB   | mistral           | 4.1GB | Good for basic analysis        |
| 16GB  | llama3            | 4.7GB | Excellent for most use cases   |
| 32GB+ | llama3:70b        | 40GB  | Best quality, production-ready |

#### Step 4: Configure Gonzo for Ollama

```bash
# Set environment variables for Ollama
export OPENAI_API_KEY="ollama"                    # Special key for Ollama
export OPENAI_API_BASE="http://localhost:11434"   # Ollama endpoint

# Verify Ollama is accessible
curl http://localhost:11434/api/tags
```

#### Step 5: Test Ollama Integration

```bash
# Test with automatic model selection
gonzo -f your-logs.log

# Test with specific model
gonzo -f your-logs.log --ai-model="llama3"

# Test model switching
# Press 'm' in Gonzo to see available Ollama models
```

### Local LM Studio Setup

#### Step 1: Install LM Studio

1. **Download LM Studio** from <https://lmstudio.ai/>
2. **Install the application** for your operating system
3. **Launch LM Studio**

#### Step 2: Download Models

1. **Open LM Studio**
2. **Go to "Discover" tab**
3. **Search and download recommended models:**
   * `microsoft/DialoGPT-medium` (lightweight, good for testing)
   * `meta-llama/Llama-2-7b-chat-hf` (balanced performance)
   * `meta-llama/Llama-2-13b-chat-hf` (better quality, needs more RAM)

#### Step 3: Start Model Server

1. **Go to "Local Server" tab in LM Studio**
2. **Select your downloaded model**
3. **Click "Start Server"**
4. **Note the server URL** (usually `http://localhost:1234`)

#### Step 4: Configure Gonzo for LM Studio

```bash
# Set environment variables for LM Studio
export OPENAI_API_KEY="local-key"                     # Any non-empty value
export OPENAI_API_BASE="http://localhost:1234/v1"     # Note the /v1 suffix

# Test connectivity
curl http://localhost:1234/v1/models
```

#### Step 5: Test LM Studio Integration

```bash
# Test with LM Studio
gonzo -f your-logs.log

# The model will be auto-selected from whatever's running in LM Studio
# Use 'm' to see available models
```

### Custom API Setup

#### Enterprise AI Services

**Azure OpenAI Service:**

```bash
export OPENAI_API_KEY="your-azure-key"
export OPENAI_API_BASE="https://your-resource.openai.azure.com/"
export OPENAI_API_TYPE="azure"
export OPENAI_API_VERSION="2023-05-15"
```

**AWS Bedrock (via compatible proxy):**

```bash
export OPENAI_API_KEY="your-aws-access-key"
export OPENAI_API_BASE="https://your-bedrock-proxy.amazonaws.com/v1"
```

**Custom OpenAI-Compatible API:**

```bash
export OPENAI_API_KEY="your-custom-api-key"
export OPENAI_API_BASE="https://your-ai-service.com/v1"
```

#### Testing Custom APIs

```bash
# Test API connectivity
curl -H "Authorization: Bearer $OPENAI_API_KEY" \
     "$OPENAI_API_BASE/models"

# Test with Gonzo
gonzo -f test-logs.log --ai-model="your-model-name"
```

### Real-World Examples

See AI features in action:

* [AI and a TUI: Practical Logging Tools for SREs](https://www.controltheory.com/blog/ai-and-a-tui-practical-logging-tools-for-sres/) - Practical AI use cases for incident response

### Advanced Configuration

#### Configuration File Setup

Create a comprehensive configuration file for persistent settings:

```bash
# Create configuration directory
mkdir -p ~/.config/gonzo

# Create comprehensive config file
cat > ~/.config/gonzo/config.yml << EOF
# AI Configuration
ai-model: "gpt-4"                    # Default model
ai-auto-select: true                 # Auto-select best available model

# File and performance settings
files:
  - "/var/log/app/*.log"
follow: true
update-interval: 2s
log-buffer: 5000

# AI-specific performance settings
ai-context-size: 4000               # Maximum context for AI analysis
ai-response-timeout: 30s            # Timeout for AI responses
ai-max-retries: 3                   # Retry failed AI requests

# Development vs Production settings
profiles:
  development:
    ai-model: "gpt-3.5-turbo"       # Cheaper model for dev
    update-interval: 1s              # Faster updates
  production:
    ai-model: "gpt-4"               # Best model for production
    update-interval: 5s              # Conservative updates
EOF
```

#### Environment-Specific Configurations

**Development Environment:**

```bash
# ~/.config/gonzo/dev-config.yml
ai-model: "gpt-3.5-turbo"           # Cost-effective
update-interval: 1s                  # Responsive
log-buffer: 2000                     # Smaller buffer
ai-context-size: 2000               # Reduce token usage
```

**Production Environment:**

```bash
# ~/.config/gonzo/prod-config.yml
ai-model: "gpt-4"                   # Best quality
update-interval: 5s                  # Conservative
log-buffer: 10000                   # Larger buffer
ai-context-size: 8000               # More context
ai-response-timeout: 60s            # Longer timeout
```

**Usage:**

```bash
# Use specific configuration
gonzo --config ~/.config/gonzo/dev-config.yml -f logs/debug.log
gonzo --config ~/.config/gonzo/prod-config.yml -f /var/log/app.log
```

### Multi-Provider Setup

#### Switching Between Providers

**Script for Easy Provider Switching:**

```bash
#!/bin/bash
# ai-provider-switch.sh

switch_to_openai() {
    export OPENAI_API_KEY="sk-your-openai-key"
    export OPENAI_API_BASE=""
    echo "Switched to OpenAI"
}

switch_to_ollama() {
    export OPENAI_API_KEY="ollama"
    export OPENAI_API_BASE="http://localhost:11434"
    echo "Switched to Ollama"
}

switch_to_lmstudio() {
    export OPENAI_API_KEY="local-key"
    export OPENAI_API_BASE="http://localhost:1234/v1"
    echo "Switched to LM Studio"
}

# Usage: source ai-provider-switch.sh && switch_to_openai
```

#### Provider-Specific Aliases

```bash
# Add to ~/.bashrc or ~/.zshrc

# OpenAI for production incidents
alias gonzo-openai='OPENAI_API_KEY="sk-your-key" \
                    OPENAI_API_BASE="" \
                    gonzo --ai-model="gpt-4"'

# Ollama for development
alias gonzo-local='OPENAI_API_KEY="ollama" \
                   OPENAI_API_BASE="http://localhost:11434" \
                   gonzo --ai-model="llama3"'

# LM Studio for testing
alias gonzo-lms='OPENAI_API_KEY="local-key" \
                 OPENAI_API_BASE="http://localhost:1234/v1" \
                 gonzo'
```

### Troubleshooting Setup Issues

#### OpenAI Issues

**"Invalid API Key" Error:**

```bash
# Check API key is set correctly
echo $OPENAI_API_KEY

# Verify API key format (should start with 'sk-')
# Test API key directly
curl -H "Authorization: Bearer $OPENAI_API_KEY" \
     https://api.openai.com/v1/models
```

**"Rate limit exceeded" Error:**

```bash
# Check your OpenAI usage limits
# Visit https://platform.openai.com/account/usage

# Use cheaper model temporarily
gonzo -f logs.log --ai-model="gpt-3.5-turbo"

# Add delays between requests (automatic in Gonzo)
```

**"Insufficient credits" Error:**

```bash
# Add credits to your OpenAI account
# Visit https://platform.openai.com/account/billing

# Check current balance
curl -H "Authorization: Bearer $OPENAI_API_KEY" \
     https://api.openai.com/v1/dashboard/billing/subscription
```

#### Ollama Issues

**"Connection refused" Error:**

```bash
# Check if Ollama is running
ps aux | grep ollama

# Start Ollama if not running
ollama serve

# Check if port is accessible
curl http://localhost:11434/api/tags
```

**"Model not found" Error:**

```bash
# List available models
ollama list

# Download missing model
ollama pull llama3

# Verify model is available
ollama show llama3
```

**High Memory Usage:**

```bash
# Use smaller model
ollama pull mistral  # 4.1GB instead of 7GB+

# Monitor memory usage
htop

# Restart Ollama if memory issues persist
killall ollama
ollama serve
```

#### LM Studio Issues

**"No models available" Error:**

```bash
# Check LM Studio is running with server started
# Verify model is loaded in LM Studio
# Check server URL is correct (usually :1234)

# Test connectivity
curl http://localhost:1234/v1/models
```

**"Model loading failed" Error:**

```bash
# Check available RAM
free -h

# Try smaller model in LM Studio
# Restart LM Studio application
# Verify model file isn't corrupted
```

#### Network and Firewall Issues

**Corporate Firewall:**

```bash
# Test connectivity to AI providers
curl -I https://api.openai.com
curl -I http://localhost:11434  # For Ollama
curl -I http://localhost:1234   # For LM Studio

# Configure proxy if needed
export HTTP_PROXY=http://your-proxy:port
export HTTPS_PROXY=http://your-proxy:port
```

**SSL Certificate Issues:**

```bash
# Skip SSL verification (not recommended for production)
export PYTHONHTTPSVERIFY=0

# Or install proper certificates
# Contact your IT department for certificate installation
```

### What's Next?

Now that you have AI configured, explore these guides:

* **AI Providers Guide** - Detailed setup for specific providers
* **Using AI Features** - Master AI-powered workflows and analysis
* **Log Analysis** - Combine AI with algorithmic analysis

Or start using AI features immediately:

```bash
# Start analyzing with AI
gonzo -f your-logs.log --ai-model="gpt-4"

# Try these AI features:
# - Press 'i' on any log entry for analysis
# - Press 'c' in log details for interactive chat
# - Press 'm' to switch between AI models
```

***

**Your AI-powered log analysis is ready!** 🤖 You can now get intelligent insights, natural language explanations, and automated pattern recognition for any log analysis task.


# Old Configuration Cover Page

### Configuration Philosophy

Gonzo follows a layered configuration approach:

1. **Sensible defaults** - Works great out of the box with zero configuration
2. **Environment variables** - Quick overrides for common settings
3. **Command-line flags** - Session-specific adjustments
4. **Configuration files** - Persistent, sophisticated setups
5. **Priority system** - CLI flags override config files, which override environment variables

{% hint style="success" %}
**Start Simple:** Most users never need configuration files. Use command-line flags until you find yourself repeating the same options, then create a config file for convenience.
{% endhint %}

###

###

### Configuration Overview

Gonzo offers three main configuration approaches:

| Method                    | Complexity | Persistence   | Best For                             |
| ------------------------- | ---------- | ------------- | ------------------------------------ |
| **Command-Line Flags**    | Low        | Session only  | Quick analysis, one-time adjustments |
| **Environment Variables** | Low        | Shell session | Personal defaults, API keys          |
| **Configuration Files**   | Medium     | Permanent     | Team standards, complex setups       |

### Configuration Hierarchy

Understanding how Gonzo resolves configuration:

```
┌─────────────────────────────────────┐
│   1. Command-Line Flags             │ ← Highest priority
│      --log-buffer=5000              │
├─────────────────────────────────────┤
│   2. Environment Variables          │
│      GONZO_LOG_BUFFER=3000         │
├─────────────────────────────────────┤
│   3. Configuration File             │
│      log-buffer: 2000               │
├─────────────────────────────────────┤
│   4. Built-in Defaults              │ ← Lowest priority
│      log-buffer: 1000               │
└─────────────────────────────────────┘

Result: Uses 5000 (command-line flag wins)
```

### Quick Configuration Examples

#### Minimal Setup (No Configuration)

```bash
# Just works - uses sensible defaults
gonzo -f application.log
```

#### Basic Customization (CLI Flags)

```bash
# Common adjustments for specific sessions
gonzo -f /var/log/app.log \
      --follow \
      --log-buffer=5000 \
      --update-interval=2s \
      --ai-model="gpt-4"
```

#### Persistent Configuration (Config File)

```yaml
# ~/.config/gonzo/config.yml
files:
  - "/var/log/app/*.log"
follow: true
update-interval: 2s
log-buffer: 5000
memory-size: 15000
ai-model: "gpt-4"
```

```bash
# Uses config file automatically
gonzo
```

### Configuration Guide Structure

This section covers all aspects of Gonzo configuration:

#### Configuration File

**Master YAML-based configuration**

Learn how to create and manage configuration files for persistent settings:

* **File location and discovery** - Where Gonzo looks for config files
* **Complete YAML reference** - All available configuration options
* **Environment-specific configs** - Separate configs for dev, staging, production
* **Configuration profiles** - Switch between different setups easily
* **Validation and debugging** - Ensure your config is correct

**Time to master:** 20-30 minutes\
**Prerequisites:** Basic YAML knowledge helpful

***

#### Command Line Reference

**Complete CLI flag documentation**

Comprehensive reference for all command-line options:

* **Core flags** - File input, following, basic operations
* **Performance tuning** - Buffer sizes, update intervals, memory management
* **AI configuration** - Model selection, provider settings
* **Display options** - Interface customization, output control
* **Advanced flags** - Testing, debugging, profiling

**Time to master:** 15-20 minutes\
**Prerequisites:** Basic command-line familiarity

***

#### Advanced Configuration

**Performance tuning and complex setups**

Advanced configuration techniques for production deployments:

* **Performance optimization** - High-volume logs, resource constraints
* **Multi-environment setups** - Dev, staging, production configurations
* **Team configurations** - Shared standards, best practices
* **Integration patterns** - CI/CD, monitoring systems, alerting
* **Troubleshooting configs** - Debug configuration issues

**Time to master:** 30-45 minutes\
**Prerequisites:** Understanding of basic configuration

### Common Configuration Scenarios

#### Development Environment

**Goal:** Fast, responsive analysis with cost-effective AI

```bash
# Quick CLI approach
gonzo -f logs/*.log --follow --ai-model="gpt-3.5-turbo"

# Or create ~/.config/gonzo/dev.yml
files:
  - "logs/*.log"
follow: true
update-interval: 1s
log-buffer: 2000
ai-model: "gpt-3.5-turbo"
```

#### Production Monitoring

**Goal:** Reliable, comprehensive monitoring with quality AI analysis

```bash
# Production config: ~/.config/gonzo/prod.yml
files:
  - "/var/log/app/*.log"
  - "/var/log/nginx/*.log"
follow: true
update-interval: 5s           # Conservative updates
log-buffer: 10000            # Large buffer for history
memory-size: 50000           # Ample memory for analysis
ai-model: "gpt-4"            # Best quality for production
```

#### CI/CD Integration

**Goal:** Automated log analysis in build pipelines

```bash
# Use environment variables for CI
export GONZO_LOG_BUFFER=5000
export GONZO_UPDATE_INTERVAL=2s
export OPENAI_API_KEY="${CI_OPENAI_KEY}"

# Simple invocation
build-command 2>&1 | gonzo --ai-model="gpt-3.5-turbo"
```

#### High-Volume Log Processing

**Goal:** Handle thousands of log entries per second

```bash
# Optimized for performance
gonzo -f /var/log/high-volume.log \
      --follow \
      --log-buffer=20000 \
      --memory-size=100000 \
      --update-interval=10s \
      --ai-model="llama3"  # Local AI for no API limits
```

### Configuration Best Practices

#### 🎯 **Start Simple, Add Complexity**

1. **Begin with defaults** - Gonzo works well without configuration
2. **Add flags as needed** - Use CLI flags to experiment with settings
3. **Create config when repeating** - Move repeated flags to config files
4. **Separate by environment** - Different configs for dev vs production

#### 📁 **Organize Your Configurations**

```bash
~/.config/gonzo/
├── config.yml              # Default configuration
├── dev.yml                 # Development settings
├── prod.yml                # Production settings
├── incident.yml            # Incident response settings
└── profiles/
    ├── security.yml        # Security monitoring profile
    ├── performance.yml     # Performance analysis profile
    └── debugging.yml       # Debugging profile
```

**Usage:**

```bash
# Default config
gonzo

# Specific configuration
gonzo --config ~/.config/gonzo/prod.yml

# Quick profile switching
alias gonzo-dev='gonzo --config ~/.config/gonzo/dev.yml'
alias gonzo-prod='gonzo --config ~/.config/gonzo/prod.yml'
alias gonzo-security='gonzo --config ~/.config/gonzo/profiles/security.yml'
```

#### 🔐 **Secure Configuration Management**

**Do:**

* ✅ Store API keys in environment variables, not config files
* ✅ Use separate configs for different environments
* ✅ Version control config files (without secrets)
* ✅ Document why specific settings were chosen

**Don't:**

* ❌ Commit API keys to version control
* ❌ Share production configs without sanitizing
* ❌ Use production API keys in development
* ❌ Hard-code sensitive information

#### ⚡ **Performance Tuning Strategy**

```bash
# 1. Start with defaults
gonzo -f logs.log

# 2. Monitor resource usage
htop  # Check CPU/memory during operation

# 3. Identify bottlenecks
# - High CPU? Increase update-interval
# - High memory? Reduce log-buffer and memory-size
# - Slow AI? Use local models or faster cloud models

# 4. Tune incrementally
gonzo -f logs.log --update-interval=5s  # Test slower updates
gonzo -f logs.log --log-buffer=2000     # Test smaller buffer

# 5. Document working configuration
# Save successful settings to config file
```

### Configuration Validation

#### Testing Your Configuration

```bash
# Test configuration syntax
gonzo --config ~/.config/gonzo/config.yml --test-mode

# Dry-run to see what settings would be used
gonzo --config ~/.config/gonzo/config.yml --dry-run

# Verbose output to debug configuration
gonzo --config ~/.config/gonzo/config.yml --verbose
```

#### Common Configuration Issues

**Config file not found:**

```bash
# Check default locations Gonzo searches:
# 1. ./config.yml (current directory)
# 2. ~/.config/gonzo/config.yml
# 3. /etc/gonzo/config.yml

# Specify explicit path
gonzo --config /path/to/config.yml
```

**Settings not taking effect:**

```bash
# Check configuration priority
# CLI flags always override config file

# Example - this uses 5000, not 2000:
# config.yml has: log-buffer: 2000
gonzo --config config.yml --log-buffer=5000
```

**Performance issues:**

```bash
# Configuration too aggressive for system resources
# Solution: Reduce memory/buffer sizes

# From:
log-buffer: 50000
memory-size: 200000

# To:
log-buffer: 10000
memory-size: 30000
```

### Environment-Specific Patterns

#### Development Configuration

```yaml
# dev.yml - Optimized for fast iteration
files:
  - "logs/*.log"
  - "debug/*.log"

follow: true
update-interval: 1s          # Fast updates for development
log-buffer: 2000            # Smaller buffer
memory-size: 10000          # Less memory needed

ai-model: "gpt-3.5-turbo"   # Cost-effective
ai-auto-select: true
```

#### Production Configuration

```yaml
# prod.yml - Optimized for reliability and completeness
files:
  - "/var/log/app/*.log"
  - "/var/log/nginx/*.log"
  - "/var/log/database/*.log"

follow: true
update-interval: 5s          # Conservative updates
log-buffer: 10000           # Large history buffer
memory-size: 50000          # Ample analysis memory

ai-model: "gpt-4"           # Best quality
ai-response-timeout: 60s    # Longer timeout for reliability
```

#### Testing/CI Configuration

```yaml
# ci.yml - Optimized for automated analysis
files:
  - "build-logs/*.log"
  - "test-results/*.log"

follow: false                # Batch processing
update-interval: 2s
log-buffer: 5000

ai-model: "gpt-3.5-turbo"   # Fast, cost-effective
test-mode: true             # CI-friendly output
```

### Configuration Migration

#### Upgrading from CLI to Config File

```bash
# You've been running:
gonzo -f /var/log/app.log \
      --follow \
      --log-buffer=5000 \
      --update-interval=2s \
      --ai-model="gpt-4"

# Convert to config file:
cat > ~/.config/gonzo/config.yml << EOF
files:
  - "/var/log/app.log"
follow: true
log-buffer: 5000
update-interval: 2s
ai-model: "gpt-4"
EOF

# Now just run:
gonzo
```

#### Team Configuration Standards

```yaml
# team-standard.yml - Shared across team
# Version control this file (without secrets)

# Standard file patterns
file-patterns:
  - "*.log"
  - "logs/**/*.log"

# Performance standards
update-interval: 2s
log-buffer: 5000
memory-size: 15000

# AI standards (API keys from environment)
ai-model: "gpt-3.5-turbo"
ai-auto-select: true

# Display standards
show-host: true
show-service: true

# Comments explaining choices:
# - 2s update-interval: Balance between responsiveness and resource usage
# - gpt-3.5-turbo: Cost-effective for daily use, upgrade to gpt-4 for incidents
# - 5000 log-buffer: Enough history for correlation without excessive memory
```

### Getting Help with Configuration

**Configuration Resources:**

* **Configuration File Guide** - Complete YAML reference
* **CLI Reference** - All command-line options
* **Advanced Configuration** - Complex setups and tuning

**Community Support:**

* 💬 [GitHub Discussions](https://github.com/control-theory/gonzo/discussions) - Configuration questions
* 🐛 [GitHub Issues](https://github.com/control-theory/gonzo/issues) - Configuration bugs
* 📖 Example configurations in the repository

**Debugging Configuration:**

```bash
# Show current configuration
gonzo --show-config

# Verbose mode for debugging
gonzo --verbose --config myconfig.yml

# Test mode to validate without running
gonzo --test-mode --config myconfig.yml
```

### What's Next?

Ready to configure Gonzo for your needs? Start with the guide that matches your approach:

* **Configuration File** - Create persistent configurations with YAML
* **Command Line Reference** - Master all CLI flags and options
* **Advanced Configuration** - Performance tuning and complex setups

Or explore related topics:

* **Integration Examples** - See configuration in real-world scenarios
* **Advanced Features** - Features to configure and optimize
* **Troubleshooting** - Configuration-related issues

***

**Start with the defaults, configure when needed, optimize for your workflow.** ⚙️ Gonzo's flexible configuration system grows with your needs, from simple CLI flags to sophisticated production deployments.


