Logging Exceptions
Structured exception logging includes the message, file, line, trace, and any contextual data. Use a PSR-3 compatible logger like Monolog.
Structured exception logging includes the message, file, line, trace, and any contextual data. Use a PSR-3 compatible logger like Monolog.
<?php
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$logger = new Logger("app");
$logger->pushHandler(new StreamHandler("logs/app.log", Logger::ERROR));
try {
$result = riskyOperation($input);
} catch (Exception $e) {
$logger->error("Operation failed", [
"exception" => $e->getMessage(),
"file" => $e->getFile(),
"line" => $e->getLine(),
"trace" => $e->getTraceAsString(),
"input" => $input, // contextual data
]);
// Return graceful error to user
return response()->json(["error" => "Operation failed"], 500);
}
Log the full exception context (message, trace, input data) but show only a generic message to end users.