Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 67 ยท Security, Errors and Deployment

Logging, Exceptions and Error Handling in Laravel

Learn Laravel logging channels and levels, context data, how to report and render exceptions in bootstrap/app.php, and maintenance mode, with runnable stand-ins.

Things go wrong in production: a payment API times out, a user submits something you never imagined, a deploy leaves a table out of date. You cannot watch every request, so your application has to do two jobs when it fails. It must record what happened so that you can fix it later, and it must answer the visitor with something sensible instead of a stack trace.

Laravel splits those jobs cleanly. Logging writes messages to one or more destinations. Exception handling decides, for every exception that escapes your code, how to report it (usually to the log) and how to render it (an HTTP response). In this lesson you will learn both, plus maintenance mode. The real framework code is shown in read-only blocks, because Laravel cannot run on this site. The runnable examples are plain-PHP stand-ins with the same shape, and the text always says which is which. For the language-level view of exceptions see PHP exceptions and PSR-3 logging.

Logging basics

Laravel logging is built on Monolog, the standard PHP logging library. You use it through the Log facade. Every message has a level, taken from the eight levels of the syslog standard, from least to most severe: debug, info, notice, warning, error, critical, alert, emergency.

PHP
use Illuminate\Support\Facades\Log;

Log::info('Order placed');
Log::warning('Stock is running low');
Log::error('Payment gateway timed out');

// the helper does the same for quick use
logger('Something happened');

The level tells readers how urgent a message is, and it also lets you filter: a channel configured with the level error ignores debug and info messages. In production you normally keep the minimum at info or warning, because debug output is noisy and can include data you do not want stored.

Context: structured data

A message is for people, but context is for searching. Pass an array as the second argument and Laravel stores it alongside the message:

PHP
Log::error('Payment failed', [
    'order_id' => $order->id,
    'gateway'  => 'stripe',
    'amount'   => $order->total,
]);

Compare "Payment failed for order 1042 using card 4242..." glued into a string with a fixed message plus context. The fixed message is easy to count and alert on, and the context keys can be searched in a log service. Never put secrets (passwords, full card numbers, tokens) in context: logs are copied, shipped and read by many people.

You can attach context to every message of a request, which is perfect for a request id or the signed-in user:

PHP
// in a middleware
Log::withContext(['request_id' => (string) Str::uuid()]);

Channels and the log configuration

A channel is a named destination plus its settings, defined in config/logging.php. The default channel comes from the LOG_CHANNEL environment variable, and LOG_LEVEL sets the minimum level.

Channel driver What it does
single One file, storage/logs/laravel.log
daily A new file per day, old files deleted after N days
stack Sends each message to several other channels
stderr Writes to standard error (good for containers)
syslog, errorlog System log or PHP's error log
slack Posts to a Slack webhook
null Throws messages away

The stack channel is the one you will customize most. This stack writes everything to a daily file and sends only serious problems to Slack:

PHP
// config/logging.php (excerpt)
'channels' => [
    'stack' => [
        'driver' => 'stack',
        'channels' => ['daily', 'slack'],
        'ignore_exceptions' => false,
    ],
    'daily' => [
        'driver' => 'daily',
        'path' => storage_path('logs/laravel.log'),
        'level' => env('LOG_LEVEL', 'debug'),
        'days' => 14,
    ],
    'slack' => [
        'driver' => 'slack',
        'url' => env('LOG_SLACK_WEBHOOK_URL'),
        'level' => 'critical',
    ],
],

You can also write to one channel on demand with Log::channel('slack')->critical('Disk almost full'), or to a temporary stack with Log::stack(['daily', 'slack'])->alert('...'). A good production recipe: log to stderr or a daily file, ship it to a log service, and alert on error and above.

The stand-in below does what the stack driver does: each channel has its own minimum level and its own destination, and a message goes to every channel that accepts it. It uses a fixed clock, so the output is deterministic.

PHP A logger with levels, channels and context

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

How Laravel handles exceptions

When code throws an exception and nothing catches it, the exception travels up to the framework, which hands it to the exception handler. That handler does two separate things:

  1. Report: log the exception (or send it to a service such as Sentry or Flare).
  2. Render: turn it into a response: a styled error page, a redirect, or JSON for API requests.
flowchart LR
    T["Code throws an exception"] --> H["Exception handler"]
    H --> D{"Is the type in dontReport?"}
    D -- "no" --> R["Report: write to the log"]
    D -- "yes" --> S["Skip reporting"]
    R --> W["Render: build the response"]
    S --> W
    W --> X["HTTP response<br/>(404 page, 422 JSON, 500 page)"]

Reporting and rendering are separate steps, so an exception can be rendered nicely without ever being logged.

Laravel already knows what to do with the common cases. A ModelNotFoundException becomes a 404. A ValidationException becomes a redirect back with errors, or a 422 JSON response. An AuthenticationException becomes a redirect to the login page, or a 401. Anything unknown becomes a 500 page. With APP_DEBUG=true you get the detailed error page with the stack trace; with APP_DEBUG=false visitors see a plain message. Never set APP_DEBUG=true in production, because the debug page can expose environment values and code.

Customizing the handler in bootstrap/app.php

In Laravel 11 and newer (including Laravel 13), there is no Handler class by default. You customize handling in bootstrap/app.php, in the withExceptions callback:

PHP
use App\Exceptions\PaymentFailedException;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Http\Request;

->withExceptions(function (Exceptions $exceptions): void {

    // Report: extra work whenever this type is thrown
    $exceptions->report(function (PaymentFailedException $e) {
        // for example, notify the finance channel
    });

    // Render: how this type becomes a response
    $exceptions->render(function (PaymentFailedException $e, Request $request) {
        if ($request->expectsJson()) {
            return response()->json(['message' => 'Payment failed.'], 402);
        }

        return response()->view('errors.payment', status: 402);
    });

    // Do not log these at all
    $exceptions->dontReport([
        App\Exceptions\NoisyButHarmlessException::class,
    ]);

    // Lower the log level for some exceptions
    $exceptions->level(PDOException::class, Psr\Log\LogLevel::CRITICAL);
})

If a render callback returns nothing (null), Laravel falls back to its default rendering. A report callback that returns false stops Laravel from running the default logging for that exception. Laravel also deduplicates: one exception is reported only once, even if several places try.

Self-handling exceptions

For your own exception classes you can skip the central file and put the logic on the exception itself:

PHP
namespace App\Exceptions;

use Exception;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class PaymentFailedException extends Exception
{
    public function __construct(public readonly string $orderNumber, string $reason)
    {
        parent::__construct("Payment failed for {$orderNumber}: {$reason}");
    }

    public function report(): bool
    {
        // return false to fall back to default reporting
        return false;
    }

    public function render(Request $request): Response
    {
        return response("Payment failed for order {$this->orderNumber}", 402);
    }

    public function context(): array
    {
        return ['order' => $this->orderNumber];   // added to the log entry
    }
}

This keeps "what does this failure look like?" next to the class that represents it, which is easy to find later. Use the central withExceptions block for cross-cutting rules (log levels, third-party exceptions you do not own).

Throwing HTTP errors yourself

For a plain HTTP error, abort() is the shortcut. It throws an HttpException with a status code:

PHP
abort(404);
abort(403, 'You cannot edit this post.');
abort_if(! $post->isPublished(), 404);
abort_unless($user->isAdmin(), 403);

To customize the page, create a Blade view named after the status code, such as resources/views/errors/404.blade.php or errors/500.blade.php. Laravel picks it up automatically. The rescue() helper is another handy tool: rescue(fn () => riskyThing()) runs the closure, reports any exception, and returns null instead of crashing the request.

The stand-in below keeps the same two-step design: a handler with dontReport, a report step that logs, and render callbacks chosen by the exception type. Notice that report and render are independent.

PHP An exception handler with report and render

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The real framework works the same way, but the registries (report, render, dontReport, level) all live behind $exceptions in bootstrap/app.php, and the final fallback page is the Blade error view or the debug page (Ignition-style), not a plain string.

API responses and JSON errors

For requests that send Accept: application/json (or whose route is under api/*), Laravel renders exceptions as JSON, for example {"message": "Server Error"} with the right status code, and only includes the trace when debug mode is on. You can force JSON for more paths:

PHP
$exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {
    return $request->is('api/*') || $request->expectsJson();
});

Consistent error shapes for APIs are covered in API design.

Maintenance mode

Before a risky deploy or migration, you can turn the site into a "back soon" page:

Terminal
php artisan down
php artisan down --retry=60 --refresh=15
php artisan down --secret="my-bypass-token"
php artisan down --render="errors::503"
php artisan up

While the app is down, every request gets a 503 Service Unavailable response. --retry sets the Retry-After header, --refresh makes the page reload itself, and --secret lets you visit /my-bypass-token once to receive a cookie that bypasses maintenance mode, so you can test the live site before reopening. Queued jobs are not processed while the app is in maintenance mode unless you start the worker in a way that ignores it, so plan for that.

Maintenance mode is a blunt tool because the site is fully offline. For deploys with no downtime at all, see Deploying Laravel.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why pass context as a second argument to Log::error() instead of building a long message string?

    A constant message groups similar events together, and the context keys can be filtered in a log service. It also keeps secrets from being glued into free text by accident.
  2. 2. What does the "stack" log channel do?

    A stack lists other channels (for example daily and slack) and forwards each message to all of them, each applying its own minimum level.
  3. 3. In Laravel 13, where do you normally register custom report and render logic for exceptions?

    Modern Laravel skeletons have no Handler class. You configure reporting and rendering through the Exceptions object passed to withExceptions, or put report() and render() methods on your own exception classes.
  4. 4. What is the difference between reporting and rendering an exception?

    Reporting is about recording the failure for developers. Rendering is about what the visitor sees. They are independent, so an exception can be in dontReport and still be rendered.
  5. 5. Why must APP_DEBUG be false in production?

    The detailed error page includes stack traces and can show environment details. That is useful locally but a serious information leak on a public site.

Summary

  • Laravel logs through Monolog: choose a channel with LOG_CHANNEL, a minimum level with LOG_LEVEL, and use stack to fan out to several channels.
  • Use fixed messages with a context array, never secrets, and Log::withContext() for request-wide data.
  • The exception handler reports (logs) and renders (responds) each exception; configure both in withExceptions in bootstrap/app.php or on your own exception classes.
  • abort() throws HTTP errors, and resources/views/errors/{status}.blade.php customizes error pages.
  • php artisan down serves 503 during maintenance; --secret lets you bypass it to test.
  • Keep APP_DEBUG=false in production.

Next: Deploying Laravel