Logging

Logging that helps in production: structure, request IDs, and what to avoid.

On this page

Why Logging Matters

Logs are your main visibility tool in production. They help diagnose incidents, track performance issues, and detect abuse patterns. Good logs are structured, consistent, and safe.

Basic Logging

PHP can log via error_log. In production you typically route logs to files or stdout (containers) and aggregate them.

<?php
error_log("User login failed: email=" . $email);

Use a Request ID

A request ID helps correlate logs across layers. Generate it once per request and include it in every log line.

<?php
$requestId = bin2hex(random_bytes(8));
header("X-Request-Id: " . $requestId);

function logInfo(string $msg, string $requestId): void {
  error_log("rid=" . $requestId . " " . $msg);
}

logInfo("route=/items method=GET", $requestId);

Structured Logging (JSON Style)

Even without a library, you can log JSON for better parsing in log systems.

<?php
$line = json_encode([
  "level" => "info",
  "rid" => $requestId,
  "event" => "items_list",
  "page" => (int)($_GET["page"] ?? 1),
]);

error_log($line);

Do Not Log Secrets

Never log passwords, tokens, full session cookies, or API keys. If you must log user input, truncate and sanitize.

Production Tip

Log meaningful events (auth failures, 4xx spikes, slow queries). Add latency logging and error rate monitoring. Prefer a real logger library later, but start with consistent log lines now.