FALVARIX
FALVARIX
devops --real --no-hype

Local AI for DevOps: a 100% private log analysis copilot

Local AI for DevOps: a 100% private log analysis copilot

Local AI for DevOps: a 100% private log analysis copilot

It’s 3:12 in the morning and your pager won’t stop buzzing. You’ve got 40,000 lines of logs, a 200-line stack trace, and the urge to paste the whole thing into a cloud AI chat. You’ve done it before, and it worked. But those logs contained internal IPs, customer names, tokens in headers, and maybe a couple of email addresses. You just handed all of that to a third party.

Local AI for DevOps solves that dilemma. You can have the same kind of assistant, one that summarizes incidents, clusters errors and proposes hypotheses, running on your own infrastructure, with no outbound connection and zero marginal cost per query. In this guide we’ll build a log analysis copilot with Ollama, Grafana Loki and a hundred-line script.

Why you shouldn’t send your logs to an external API

A log is rarely harmless. Over time it accumulates personal data covered by GDPR, session identifiers, internal paths, vulnerable software versions and, all too often, credentials printed by mistake in debug mode.

Sending that information to an external provider raises three real problems:

  • Regulatory compliance: transferring personal data to a third party requires a legal basis, a data processing agreement and, sometimes, an international transfer assessment.
  • Attack surface: every SaaS integration is another place where your data can leak.
  • Vendor lock-in and cost: logs are bulky and the price per token climbs fast during an incident, right when you need the tool most.

A local model eliminates all three. Data never leaves the perimeter, there’s no contract to review, and the cost is whatever your hardware already costs you.

Architecture of the log copilot

The design is deliberately simple, because a copilot you can’t maintain gets abandoned within a month:

  1. Loki (or your current log store) stores and queries the records.
  2. An orchestration script pulls a window of logs with LogQL.
  3. A sanitization layer masks secrets and personal data before they reach the model.
  4. Ollama serves the language model locally and returns the analysis.

The key is step 3. Even though the model is local, applying least privilege to the data is good practice, because the responses can end up in tickets, chats or wikis.

Step 1: deploy Ollama with Docker

Ollama makes running open models easy and exposes a simple HTTP API. This docker-compose.yml keeps it listening on localhost only:

services:
  ollama:
    image: ollama/ollama:latest
    container_name: ollama
    ports:
      - "127.0.0.1:11434:11434"
    volumes:
      - ollama_data:/root/.ollama
    restart: unless-stopped
    # Descomenta si tienes GPU NVIDIA con nvidia-container-toolkit
    # deploy:
    #   resources:
    #     reservations:
    #       devices:
    #         - driver: nvidia
    #           count: all
    #           capabilities: [gpu]

volumes:
  ollama_data:

Start the service and pull a model:

docker compose up -d
docker exec -it ollama ollama pull llama3.1:8b

Step 2: pick the model for your hardware

You don’t need a GPU cluster. For log analysis, understanding technical text matters more than creativity, and mid-sized models do well.

HardwareRecommended modelTypical use
CPU with 16 GB RAMQuantized llama3.1:8b or qwen2.5:7bSummaries of small windows
GPU with 12-16 GB VRAMqwen2.5:14bIncident analysis and correlation
GPU with 24 GB or moreQuantized 30B+ modelsDeeper reasoning over long traces

One practical tip: start with the smallest model that gives an acceptable answer. Once you’ve measured latency and quality on your own logs, decide whether scaling up is worth it. The ideal model is the one your team actually uses during an incident, not the one that wins benchmarks.

Step 3: pull logs and sanitize before you ask

If you use Loki, the query_range API returns whatever window you need. Before handing it to the model, mask anything sensitive with regular expressions. This is the heart of the copilot:

import re
import time
import requests

LOKI = "http://loki.interno:3100"
OLLAMA = "http://127.0.0.1:11434"
MODELO = "llama3.1:8b"

PATRONES = [
    (re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+"), "<EMAIL>"),
    (re.compile(r"\b\d{1,3}(?:\.\d{1,3}){3}\b"), "<IP>"),
    (re.compile(r"(?i)(authorization|token|password|secret)[=:]\s*\S+"), r"\1=<REDACTED>"),
    (re.compile(r"\beyJ[\w-]+\.[\w-]+\.[\w-]+\b"), "<JWT>"),
]

def sanear(linea: str) -> str:
    for patron, reemplazo in PATRONES:
        linea = patron.sub(reemplazo, linea)
    return linea

def obtener_logs(consulta: str, minutos: int = 15, limite: int = 400):
    fin = int(time.time() * 1e9)
    inicio = fin - minutos * 60 * int(1e9)
    r = requests.get(
        f"{LOKI}/loki/api/v1/query_range",
        params={"query": consulta, "start": inicio, "end": fin,
                "limit": limite, "direction": "backward"},
        timeout=30,
    )
    r.raise_for_status()
    lineas = []
    for stream in r.json()["data"]["result"]:
        lineas += [sanear(v[1]) for v in stream["values"]]
    return lineas

def analizar(lineas):
    prompt = (
        "Eres un SRE senior. Analiza estos logs saneados.\n"
        "Responde en español con: 1) resumen en dos frases, "
        "2) errores agrupados por causa probable, "
        "3) hipótesis ordenadas por probabilidad, "
        "4) comandos de verificación seguros (solo lectura).\n"
        "Si no hay evidencia suficiente, dilo; no inventes.\n\n"
        + "\n".join(lineas)
    )
    r = requests.post(
        f"{OLLAMA}/api/generate",
        json={"model": MODELO, "prompt": prompt, "stream": False,
              "options": {"temperature": 0.1, "num_ctx": 8192}},
        timeout=300,
    )
    r.raise_for_status()
    return r.json()["response"]

if __name__ == "__main__":
    logs = obtener_logs('{app="api-pagos"} |= "error"')
    print(analizar(logs))

Two details make the difference. The first is low temperature: when diagnosing you want deterministic answers, not creative flourishes. The second is num_ctx: Ollama uses a small context by default, and if your log window exceeds it, the model silently truncates the beginning, which is usually where the root cause lives. Always set it explicitly.

Prompt engineering for logs

A good diagnostic prompt is a stable template, not an improvised question. These guidelines work consistently:

  • Define the role and the output format. Asking for fixed sections makes answers comparable across incidents.
  • Forbid making things up. Instructing the model to “say so if there’s no evidence” noticeably reduces hallucinations.
  • Limit actions to read-only. The copilot suggests, the human executes.
  • Provide system context. A line like “API on Kubernetes, PostgreSQL database, deployed 20 minutes ago” greatly improves the hypothesis.

Cut the noise before it reaches the model

Small models get lost in thousands of repeated lines. Deduplicate similar messages and send a counter instead of every repetition. A line like connection refused (x1.238) carries more signal than 1,238 identical copies and saves you context for what matters.

Security: a local copilot still needs defenses

Running AI inside your network doesn’t exempt you from basic security hygiene:

  • Don’t expose port 11434. Ollama has no built-in authentication. If other teams need access, put it behind a proxy with TLS and access control; our guide to Traefik as a reverse proxy with automatic SSL covers exactly that pattern.
  • Don’t rely on regex alone. Sanitization reduces risk, but ideally secrets never end up in logs in the first place. If you’re still handling them in plain files, see how to do it with secret management using OpenBao.
  • Treat logs as untrusted input. An attacker can inject text like “ignore the previous instructions” into a log field. That’s an indirect prompt injection. Which is why the copilot shouldn’t have write-enabled tools or execute the commands it suggests.
  • Audit usage. Log who queries what and when. Combined with audited access, like the setup we describe in Teleport for SSH with auditing, you get full traceability of the incident.

Use cases where the copilot already pays off

Once the pipeline is in place, the value shows up fast in very specific tasks:

  • Night-time triage: a summary of the latest error windows automatically attached to the alert.
  • Postmortems: rebuilding the timeline from logs across multiple services.
  • Security analysis: interpreting patterns of access attempts. Combined with advanced Fail2ban configuration, it can explain why an IP was blocked and what it tried beforehand.
  • Onboarding: anyone new can ask what an unclear error message means without interrupting a colleague.

Honest limitations

A local copilot doesn’t replace observability, it complements it. Models in the 7B to 14B parameter range make more mistakes than the big commercial ones, especially with multi-service traces or exotic log formats. They also don’t compute metrics accurately: that’s what PromQL and LogQL are for.

The right strategy is to let the model do what it does well, which is summarizing, clustering and proposing hypotheses, and have your deterministic tools validate the numbers. If the copilot says there was a spike in 502 errors, check the metric before acting on it.

If your team needs more precision, you can combine models: a small one for continuous triage and a bigger one, on demand, for serious incidents. Since everything runs on your infrastructure, that decision is driven by performance, not by the bill.

Next steps toward production

Once the prototype convinces you, these are the natural next steps to mature it:

  1. Wire the summary into the alert. An Alertmanager webhook can trigger the script and attach the analysis to the Slack or Mattermost message.
  2. Package the service. Turn the script into a small API, with a lightweight Docker image and version control in Git.
  3. Evaluate on real cases. Save ten past incidents with their known root cause, and every time you change the model or the prompt, check whether the copilot still gets them right.
  4. Measure. Track latency, context length and perceived usefulness. Without metrics, you won’t know whether the copilot saves time or just adds noise.

Conclusion

Local AI for DevOps is no longer an experiment. With Ollama, a log store like Grafana Loki and a sanitization script, you can have a copilot that summarizes incidents and proposes hypotheses without a single byte leaving your network. You get faster diagnosis, simpler regulatory compliance and total control over cost.

Start small: an 8B model, a single application and a well-tuned prompt template. Measure how much time you save on your next incident and grow from there. Your logs tell the story of your infrastructure, and that story doesn’t need to be shared with anyone else.

Keep reading