5 min read

Loki in Practice - Sending Logs via the HTTP API from the Python and PHP Mini Apps

1. Recap: Metrics Are Ready, the Second Pillar Is Missing

The two mini applications in this series — the Python one (article 2) and the PHP one (article 3) — already expose metrics consumed by Prometheus. Metrics answer “how many orders failed in the last 5 minutes”, but they don’t answer “why did order 4821 specifically fail”. That’s the question logs answer, and this article covers how to send them to Loki straight from the mini apps.

2. Why Loki’s Indexing Is Different

Traditional log tools, like Elasticsearch, index the full content of every line — every text term becomes searchable, which enables rich searches but requires expensive index structures on disk and CPU, growing in proportion to log volume.

Loki makes a deliberately different choice, directly inspired by Prometheus’ model: it indexes only a small set of labels — like app="python-app", env="production" — and treats the log line content as opaque text, compressed and stored in chunks, with no index of its own. When a query asks for a text filter (|= "error", for example), Loki scans the relevant chunks (already filtered by labels) at query time, instead of looking up a prebuilt index.

The practical result of this trade-off:

  • Much cheaper storage — without a full-text inverted index, disk cost grows much more slowly with log volume.
  • Searches by label are very fast — “every log from service X, in environment Y” is a cheap operation, because the labels are actually indexed.
  • Free-text searches get slower as volume grows — because they involve scanning, not an index lookup. In practice, this pushes you to always filter by labels first (which drastically reduces the volume to scan) before applying a text filter.
  • Label cardinality matters as much as in Prometheus — using a high-cardinality label (like a user_id unique per request) breaks the same efficiency premise in both systems, and it’s a common mistake for people coming from tools that index everything.

3. Loki’s HTTP Push API

Unlike Prometheus (which pulls), Loki receives logs by push: the application actively sends each batch of lines to an HTTP endpoint, POST /loki/api/v1/push. The request body is JSON in the following format:

{
  "streams": [
    {
      "stream": {
        "app": "python-app",
        "level": "info"
      },
      "values": [
        ["1735689600000000000", "request received at /"]
      ]
    }
  ]
}

Important points about this format:

  • stream carries the labels — what Loki actually indexes. Few, and low-cardinality, as seen above.
  • values is a list of [timestamp, line], where the timestamp is a string in nanoseconds since epoch (not seconds, nor milliseconds — an easy detail to get wrong).
  • You can send multiple lines from the same stream at once, which is more efficient than one HTTP request per log line.

4. Sending Logs from the Python Mini App

Using only the standard library (urllib, without installing an external HTTP client), a log function that sends straight to Loki:

# logger.py
import json
import time
import urllib.request

LOKI_URL = "http://loki:3100/loki/api/v1/push"


def log_to_loki(message, level="info", app="python-app"):
    timestamp_ns = str(time.time_ns())
    payload = {
        "streams": [
            {
                "stream": {"app": app, "level": level},
                "values": [[timestamp_ns, message]],
            }
        ]
    }
    req = urllib.request.Request(
        LOKI_URL,
        data=json.dumps(payload).encode("utf-8"),
        headers={"Content-Type": "application/json"},
        method="POST",
    )
    try:
        urllib.request.urlopen(req, timeout=2)
    except Exception as exc:
        # never let a logging failure bring the application down
        print(f"failed to send log to Loki: {exc}")

Wiring it into article 2’s app.py, calling log_to_loki on every business request:

# inside do_GET, in the branch that isn't /metrics
log_to_loki(f"request received at {self.path}")

5. Sending Logs from the PHP Mini App

The same endpoint, called from plain PHP with file_get_contents and a stream context (no cURL or external libraries needed):

<?php
// logger.php

function logToLoki($message, $level = 'info', $app = 'php-app') {
    // microtime(true) returns seconds with a decimal fraction; convert to
    // nanoseconds since epoch, the format Loki expects
    $timestampNs = sprintf('%.0f', microtime(true) * 1e9);

    $payload = json_encode([
        'streams' => [[
            'stream' => ['app' => $app, 'level' => $level],
            'values' => [[$timestampNs, $message]],
        ]],
    ]);

    $context = stream_context_create([
        'http' => [
            'method' => 'POST',
            'header' => "Content-Type: application/json\r\n",
            'content' => $payload,
            'timeout' => 2,
            'ignore_errors' => true,
        ],
    ]);

    @file_get_contents('http://loki:3100/loki/api/v1/push', false, $context);
}

Wiring it into article 3’s app.php, right after processing an order:

require __DIR__ . '/logger.php';
logToLoki("order processed, total orders: {$state['requests_total']}");

6. Querying the Logs in Grafana with LogQL

With the Loki datasource already configured in Grafana since article 1, go to Explore, select the Loki datasource and run a basic LogQL query:

{app="python-app"}

This returns every log line with the label app="python-app" — the equivalent of a grep pre-filtered by the indexed labels. To refine it with a text filter:

{app="python-app"} |= "error"

{app="php-app", level="info"} != "healthcheck"

|= keeps lines that contain the text; != keeps lines that don’t contain it. These text filters run over content already narrowed down by labels — hence the importance of always starting the query with the right labels, as discussed in section 2.

7. Conclusion and Next Steps

We saw why Loki indexes only labels and treats line content as unindexed text — a deliberate trade of search richness for cost —, how to send logs directly through the HTTP API without external libraries in Python and PHP, and how to query those logs with LogQL in Grafana. With metrics and logs from both mini apps already flowing into the stack, the third pillar is missing: the next article introduces OpenTelemetry and instruments the same applications to generate traces.


References:

  1. Grafana Loki — HTTP API (push)
  2. Grafana Loki — LogQL
  3. Grafana Loki — Best Practices