Lesson 4 of 6
Structured Logging with Monolog
Monolog is the most widely-used PHP logging library. It implements PSR-3 (LoggerInterface) and supports multiple handlers (file, syslog, Slack, Elasticsearch) and processors (add request ID, user ID, environment). Structured logging with context arrays makes logs machine-searchable in Kibana, Datadog, and CloudWatch.
Monolog - Structured Production Logging
<?php
declare(strict_types=1);
// composer require monolog/monolog
use MonologLogger;
use MonologHandler{StreamHandler, RotatingFileHandler, NullHandler};
use MonologFormatterJsonFormatter;
use MonologProcessor{IntrospectionProcessor, WebProcessor, MemoryUsageProcessor};
use MonologLevel;
// ── Logger factory ────────────────────────────────────────────
function createLogger(string $channel = "app"): Logger {
$logger = new Logger($channel);
$isTest = ($_ENV["APP_ENV"] ?? "production") === "testing";
$isProd = ($_ENV["APP_ENV"] ?? "production") === "production";
if ($isTest) {
$logger->pushHandler(new NullHandler()); // silence during tests
return $logger;
}
if ($isProd) {
// JSON format - machine-parseable for log aggregators (Datadog, ELK)
$handler = new RotatingFileHandler(
__DIR__ . "/../storage/logs/app.log",
maxFiles: 30, // Keep 30 days
level: Level::Warning, // Only Warning+ in production files
);
$handler->setFormatter(new JsonFormatter());
} else {
// Development - human-readable, all levels
$handler = new StreamHandler("php://stdout", Level::Debug);
}
// Add useful context to every log entry automatically
$logger->pushProcessor(new WebProcessor()); // URI, IP, method
$logger->pushProcessor(new MemoryUsageProcessor()); // memory usage
$logger->pushProcessor(function(array $record) {
$record["extra"]["request_id"] = $_SERVER["HTTP_X_REQUEST_ID"] ?? bin2hex(random_bytes(8));
$record["extra"]["user_id"] = $_SESSION["user_id"] ?? null;
return $record;
});
$logger->pushHandler($handler);
return $logger;
}
// ── Log levels (PSR-3) ────────────────────────────────────────
// DEBUG - detailed debug info (function entry/exit, variable values)
// INFO - interesting events (user login, post published)
// NOTICE - unusual but expected events
// WARNING - non-fatal issues (rate limit close, deprecated usage)
// ERROR - runtime errors that don't stop execution
// CRITICAL - critical failures (DB unreachable, payment gateway down)
// ALERT - action needed immediately (disk full, certif expiring)
// EMERGENCY - system is unusable
// ── Usage - always use context arrays, not string interpolation ──
$logger = createLogger("blog");
// ❌ Bad - string interpolation, not searchable
$logger->info("User alice@example.com logged in at 08:34");
// ✅ Good - structured context
$logger->info("User login", [
"user_id" => $user["id"],
"email" => $user["email"],
"ip" => $_SERVER["REMOTE_ADDR"],
"user_agent" => substr($_SERVER["HTTP_USER_AGENT"] ?? "", 0, 200),
]);
$logger->warning("Rate limit near", [
"key" => $rateLimitKey,
"remaining" => $remaining,
"limit" => 60,
]);
$logger->error("Post publish failed", [
"post_id" => $postId,
"exception" => get_class($e),
"message" => $e->getMessage(),
"trace" => array_slice(explode("
", $e->getTraceAsString()), 0, 10),
]);Quick Quiz
Tip
Tip
Practice Structured Logging with Monolog in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Structured Logging with Monolog
Practice Task
Note
Practice Task - (1) Write a working example of Structured Logging with Monolog from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Structured Logging with Monolog is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.
Finished this lesson?