# Logging
- [Introduction](#introduction)
- [Configuration](#configuration)
- [Log levels](#log-levels)
- [Formats](#formats)
- [Channels](#channels)
- [Channel levels and formats](#channel-levels-and-formats)
- [Writing log messages](#writing-log-messages)
- [Structured fields](#structured-fields)
- [Request context](#request-context)
- [Request IDs](#request-ids)
- [Commands, jobs, and scheduled tasks](#command-context)
- [Adding context](#adding-context)
- [Errors and panics](#errors-and-panics)
- [Framework log lines](#framework-log-lines)
- [Sending logs elsewhere](#sending-logs-elsewhere)
- [Sentry](#sentry)
<a name="introduction"></a>
## Introduction
To help you understand what's happening inside your application when something goes wrong, Laravel provides structured logging out of the box. You may write log messages to standard error, daily log files, or both, formatted as plain text or JSON. Laravel automatically tags every log entry with the request, command, or job that produced it so you can trace a single operation through busy production logs.
You write log messages using the [`tracing`](https://docs.rs/tracing) crate's macros. Because Laravel builds on `tracing`, every crate in your dependency tree that uses `tracing` (including packages and SQLx) writes to the same channels in the same format.
<a name="configuration"></a>
## Configuration
A new application's `.env` file configures Laravel to write `info` messages and above to standard error. Laravel doesn't write log files unless you enable the `daily` channel.
```ini
LOG_CHANNEL=stderr
LOG_LEVEL=info
```
Laravel reads these environment variables when configuring logging:
| Variable | What it sets | Default |
| --- | --- | --- |
| `LOG_LEVEL`, or `RUST_LOG` | The [level](#log-levels) of messages to write | `info` |
| `LOG_FORMAT` | The [format](#formats): `text` or `json` | `text` |
| `LOG_CHANNEL` | The [channels](#channels) to write to, such as `stderr,daily` | `stderr` |
| `LOG_DAILY_LEVEL`, `LOG_STDERR_LEVEL`, `LOG_STDOUT_LEVEL` | A [channel's own level](#channel-levels-and-formats) | `LOG_LEVEL` |
| `LOG_DAILY_DAYS` | How many days of files the `daily` channel keeps, or `0` to keep all of them | `14` |
<a name="log-levels"></a>
### Log levels
The log level controls which messages Laravel records: `trace`, `debug`, `info`, `warn`, or `error`. Laravel writes messages at the configured level and above, so `info` records `info`, `warn`, and `error` messages. To disable logging entirely, set the level to `off`.
You may also set different levels per module using `tracing`'s filter syntax. For example, this filter enables `debug` logs for your application while keeping SQLx at `warn`:
```ini
LOG_LEVEL=info,app=debug,sqlx=warn
```
`RUST_LOG` accepts the same filter syntax. If both variables are set, `RUST_LOG` takes precedence, so a `RUST_LOG` exported in your shell overrides the `LOG_LEVEL` in `.env`.
<a name="formats"></a>
### Formats
The `text` format writes one human-readable line per message, making it easy to read in your terminal during local development. The `json` format writes one JSON object per line, which works well in production when a log aggregator collects and indexes your fields:
```ini
LOG_FORMAT=json
```
Each JSON log entry is written on a single line. It starts with the entry's `time` in UTC, its `level` (`trace`, `debug`, `info`, `warning`, or `error`), its `message`, and its `target`, the module that logged it. The request, command, scheduled task, tick, job, or workflow that wrote the entry follows as an object of its own, such as `request` or `job`, so log aggregators can query paths like `request.path`, `job.queue`, or `workflow.step`. The entry's own fields are under `fields`, and the [context values](#adding-context) you add are under `context`. This example is formatted across multiple lines for readability:
```json
{
"time": "2026-11-25T15:02:58.476885Z",
"level": "info",
"message": "Order shipped",
"target": "app::orders",
"request": {
"id": "4bf92f…",
"method": "POST",
"path": "/orders/42/ship",
"route": "/orders/{order}/ship"
},
"fields": {
"order.id": 42
}
}
```
A command, scheduled task, tick, job, or workflow names itself with `name`, such as `"job": {"name": "podcasts.process", "queue": "podcasts", …}` or `"workflow": {"name": "orders.fulfil", "run": "…", "step": "charge", "attempt": 1}`. On [Laravel Cloud](https://laravel.com/cloud), the `laravel-cloud-socket` channel sends these same lines to Cloud's Logs page, and a request's object also carries Cloud's request ID as `cloud_request_id`. When [OpenTelemetry tracing](tracing.md) is enabled, JSON lines also include `trace_id` and `span_id`.
<a name="channels"></a>
### Channels
Channels control where Laravel writes your logs:
| Channel | Destination |
| --- | --- |
| `stderr` | Standard error, where process managers and containers collect logs. The default. |
| `stdout` | Standard output. |
| `daily` | A daily rotating file in `storage/logs`, such as `laravel.2026-10-04.log`. |
To write to more than one channel at once, separate the channel names with commas in `LOG_CHANNEL`.
<a name="channel-levels-and-formats"></a>
### Channel levels and formats
By default, `LOG_LEVEL` and `LOG_FORMAT` apply to every channel. To give a specific channel a different minimum level, set `LOG_DAILY_LEVEL`, `LOG_STDERR_LEVEL`, or `LOG_STDOUT_LEVEL`.
If you want to keep a local copy of warnings and errors, add `daily` to `LOG_CHANNEL` in your `.env` file. This configuration keeps `info` messages and above on standard error but saves only warnings and errors to disk:
```ini
LOG_CHANNEL=stderr,daily
LOG_LEVEL=info
LOG_DAILY_LEVEL=warn
```
To give a channel its own format, configure your channels in a `src/config/logging.rs` [config file](configuration.md#config-files). For example, this configuration keeps `stderr` as text while writing daily files as JSON:
```rust
// src/config/logging.rs
use laravel::config::logging::{LogChannel, LogFormat, Logging};
use laravel::config::{self, Env};
#[config::section]
fn logging(env: &Env) -> Logging {
Logging {
channels: vec![
LogChannel::stderr(),
LogChannel::daily().level("warn").format(LogFormat::Json),
],
..Logging::from_env(env)
}
}
```
Declare the module in `src/config/mod.rs` with `mod logging;`. Channels configured in code replace `LOG_CHANNEL` and ignore the `LOG_<CHANNEL>_LEVEL` variables, so specify each channel's level with `.level(...)` as shown above.
<a name="writing-log-messages"></a>
## Writing log messages
You may write log messages from anywhere in your application using `tracing`'s macros. There is one macro for each log level:
```rust
tracing::trace!("Checking the post's tags");
tracing::debug!("Looking up the user");
tracing::info!("Post published");
tracing::warn!("The mail provider is slow");
tracing::error!("The welcome email couldn't be sent");
```
Each message automatically includes the [context](#request-context) of the active request, command, or job, so you don't need to log the request ID or path manually.
<a name="structured-fields"></a>
### Structured fields
When a log message refers to a specific record such as a post or user, pass its IDs as structured fields rather than interpolating them into the message string. For example, this handler logs each post a user publishes:
```rust
use laravel::model::update;
use laravel::prelude::*;
use crate::models::{Post, User};
pub async fn publish(
Authenticated(user): Authenticated<User>,
mut post: Post,
) -> laravel::Result<Redirect> {
update!(post { published_at: laravel::now() }).await?;
tracing::info!(post.id = post.id, user.id = user.id, "Post published");
Ok(Redirect::back())
}
```
In `text` format, the fields appear after the message. In `json` format, each field becomes a key of the entry's `fields` object so your log aggregator can search for every event related to post `42`:
```text
INFO request{id=4bf92f… method=POST path=/posts/42/publish route=/posts/{post}/publish}: app::http::handlers::posts: Post published post.id=42 user.id=7
```
Structured fields accept numbers, strings, and booleans directly. To log another type using its `Display` or `Debug` implementation, prefix the field with `%` (for `Display`) or `?` (for `Debug`). Without a prefix, types such as `Timestamp` won't compile:
```rust
tracing::warn!(%user.email, ?user.email_verified_at, "The welcome email bounced");
```
<a name="request-context"></a>
## Request context
Because your application handles many requests concurrently, log lines from different requests are interleaved. To help you trace a single request, Laravel runs every request inside a `request` span containing the request's `id`, `method`, `path`, and `route`. Every log line written during that request inherits those fields, whether it comes from your application or a package:
```text
INFO request{id=4bf92f3577b34da6a3ce929d0e0e4736 method=GET path=/users/1 route=/users/{user}}: app::users: Looking up the user
```
When the request finishes, Laravel also writes a summary line recording its [status and duration](#framework-log-lines). For a [streamed response](responses.md#streamed-responses), download, or [event stream](responses.md#event-streams), Laravel writes that line after the last chunk is sent so the duration covers the entire response. If the client disconnects before the response finishes, Laravel logs the status as `499`.
<a name="request-ids"></a>
### Request IDs
Every response includes its request ID in the `X-Request-Id` header, so when a user reports an error, you can search your logs for that ID. If a request already arrives with an `X-Request-Id` header (for example, from a load balancer), Laravel preserves it. To read the request ID inside a handler, take a `RequestId` argument:
```rust
use laravel::http::RequestId;
pub async fn show(id: RequestId) -> String {
format!("Your request was {id}")
}
```
<a name="command-context"></a>
### Commands, jobs, and scheduled tasks
Work running outside an HTTP request also receives a span. Every console command runs inside a `command` span that records the command's name:
```text
INFO command{command=reports:generate}: app::reports: Generating the monthly report
```
[Long-running commands](console.md#long-running-commands) such as `serve`, `schedule:work`, and `queue:work` don't wrap their entire lifetime in a single `command` span. Instead, each individual request, [scheduled task](scheduling.md), or [queued job](queues.md) they execute runs in its own span: a `scheduled_task` span records the task's description, and a `job` span records the job's ID, name, connection, queue, and attempt.
<a name="adding-context"></a>
### Adding context
Sometimes every log entry written during a request should include shared information, such as the current tenant in a multi-tenant application. Any context value you add with [`laravel::context::add`](context.md#adding-to-the-context) is automatically attached to every subsequent log entry in that request, including reported errors. In `text` format, context fields appear after the message's fields; in `json` format, they appear under the entry's `context` object:
```text
INFO request{id=4bf92f… method=POST path=/posts/42/publish route=/posts/{post}/publish}: app::http::handlers::posts: Post published post.id=42 user.id=7 tenant="acme"
```
To store a context value without writing it to your logs, use [`add_hidden`](context.md#hidden-values) instead.
<a name="errors-and-panics"></a>
## Errors and panics
The [error handler](errors.md) logs every `5xx` server failure at the `error` level. The entry's message is the error's own message, and its fields record the error's type, source location, and request context, along with its chain of causes when it has any. When a handler panics, the log entry includes the file and line where the panic occurred:
```text
ERROR request{id=… method=GET path=/reports}: laravel::errors: No such file or directory (os error 2) type="core::io::error::Error" location=src/http/handlers/reports.rs:42:31
ERROR request{id=… method=GET path=/reports}: laravel::errors: panic at src/http/handlers/reports.rs:42:9: the disk is full type="laravel::errors::panic::Panic" location=src/http/handlers/reports.rs:42:9
```
In `json` format, the error's type, location, and causes are under the entry's `error` object instead of its `fields`:
```json
{"time": "2026-11-25T15:02:58.476885Z", "level": "error", "message": "the report couldn't be read", "target": "laravel::errors", "error": {"type": "core::io::error::Error", "location": "src/http/handlers/reports.rs:42:31", "causes": ["No such file or directory (os error 2)"]}, "request": {"id": "4bf92f…", "method": "GET", "path": "/reports", "route": "/reports"}}
```
The error handler only logs `5xx` failures. Client errors such as `404` or failed validation are expected outcomes and don't produce `error` log entries. To exclude a specific server error from your logs as well, [ignore its type](errors.md#ignoring-errors-by-type).
<a name="framework-log-lines"></a>
## Framework log lines
Laravel logs its internal activity under `laravel::` targets. Most of these entries are emitted at the `debug` level, so they stay quiet under the default `info` level. To inspect them, raise a target's level in `LOG_LEVEL`. For example, this filter logs every database query and cache operation:
```ini
LOG_LEVEL=info,laravel::cache=debug,sqlx::query=debug
```
| Target | Level | What it logs |
| --- | --- | --- |
| `laravel::request` | `info` locally, `debug` otherwise | Each completed request, including `status` and `duration_ms` |
| `laravel::console` | `debug` | Each completed [console command](console.md), including `exit_code` and `duration_ms` |
| `laravel::queue` | `debug` | Each processed [job](queues.md), including `outcome` and `duration_ms` |
| `laravel::workflow` | `warn` | Each failed [workflow](workflows.md) step attempt that will be retried, including `run`, `step`, and `error` |
| `laravel::http::client` | `debug` | Each completed [outgoing request](http-client.md), including `status` or `error` and `duration_ms` |
| `laravel::cache` | `debug` | Each key the [cache](cache.md#logging) reads, writes, or removes |
| `laravel::redis` | `debug` | Each [Redis](redis.md) command, without its arguments |
| `laravel::mail` | `debug` | Each email sent by a [mailer](mail.md#tracing-and-logging) |
| `laravel::view` | `debug` | Each rendered [view](views.md), including `duration_ms` |
| `sqlx::query` | `debug` | Each [database](database.md) statement (statements slower than one second log at `warn`) |
Request lines log at `info` only while `APP_ENV` is `local`, so you can watch requests in your terminal as you develop. In production, your hosting platform's access logs typically already record each request, so Laravel logs these lines at `debug` to avoid writing every request twice. If nothing in front of your application keeps access logs, you may turn the lines back on:
```ini
LOG_LEVEL=info,laravel::request=debug
```
<a name="sending-logs-elsewhere"></a>
## Sending logs elsewhere
While channels write to standard output or local files, you may also want to forward errors to an external tracker that alerts your team. Any service that integrates with `tracing` can receive your logs through a `tracing` layer registered with `with_logging` in `src/app.rs`. Custom layers receive events at every level by default, so attach a filter with `with_filter` from `tracing_subscriber`.
A [service provider](packages.md#service-providers) may also register a layer via `app.logging()` in its `register` method. To learn more about registering layers from a package, check out the package development guide's section on [logging](packages.md#logging). If you'd like to export distributed traces instead of log messages, check out the [tracing guide](tracing.md).
<a name="sentry"></a>
### Sentry
To send errors to [Sentry](https://sentry.io), add the `sentry` crate (with its `tracing` feature) and `tracing-subscriber` to your `Cargo.toml`. Then register Sentry's `tracing` layer for errors and initialize Sentry in a boot hook in `src/app.rs`:
```rust
// src/app.rs
use laravel::prelude::*;
use tracing_subscriber::Layer;
use tracing_subscriber::filter::LevelFilter;
Application::configure()
.with_logging(|logging, _| {
logging.layer(
sentry::integrations::tracing::layer().with_filter(LevelFilter::ERROR),
);
})
.with_services(|app| {
app.singleton(|_| async { Ok(sentry::init(sentry::ClientOptions::new())) });
})
.booted(|app| async move { app.resolve::<sentry::ClientInitGuard>().await.map(drop) })
```
Initialize Sentry in the boot hook rather than in `main`. Laravel loads `.env` into the process environment right before booting, so `sentry::init` picks up the `SENTRY_DSN` defined there. Storing the `ClientInitGuard` in the container ensures Sentry flushes any pending events when your application exits, which keeps errors from short-lived console commands from being dropped.
Because the error handler logs every server failure at the `error` level, failures arrive in Sentry alongside errors you log yourself. Note that Sentry's tracing layer doesn't automatically include values you [added to the request context](#adding-context). To include those context values (or forward failures to a service without a tracing layer), register an error [reporter](errors.md#reporting-errors) and read them with `context::all()`.