# 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


Laravel은 문제가 발생했을 때 애플리케이션 내부에서 일어나는 일을 파악할 수 있도록 구조화된 로깅을 기본 제공합니다. 로그 메시지를 표준 오류, 일별 로그 파일 또는 둘 다에 일반 텍스트나 JSON 형식으로 기록할 수 있습니다. Laravel은 모든 로그 항목에 해당 항목을 생성한 요청, 명령어, 잡을 자동으로 표시하므로 로그가 많은 운영 환경에서도 하나의 작업 흐름을 추적할 수 있습니다.


로그 메시지는 [`tracing`](https://docs.rs/tracing) 크레이트의 매크로로 작성합니다. Laravel이 `tracing`을 기반으로 하므로 의존성 트리에서 `tracing`을 사용하는 모든 크레이트(패키지와 SQLx 포함)가 같은 채널에 같은 형식으로 기록합니다.

<a name="configuration"></a>

## Configuration


새 애플리케이션의 `.env` 파일은 `info` 이상의 메시지를 표준 오류에 기록하도록 설정합니다. `daily` 채널을 활성화하기 전까지 Laravel은 로그 파일을 작성하지 않습니다.

```ini
LOG_CHANNEL=stderr
LOG_LEVEL=info
```


Laravel은 로깅을 설정할 때 다음 환경 변수를 읽습니다.

| 변수 | 설정 내용 | 기본값 |
| --- | --- | --- |
| `LOG_LEVEL`, 또는 `RUST_LOG` | 기록할 메시지의 [level](#log-levels) | `info` |
| `LOG_FORMAT` | [format](#formats), `text` 또는 `json` | `text` |
| `LOG_CHANNEL` | `stderr,daily` 등 기록할 [channels](#channels) | `stderr` |
| `LOG_DAILY_LEVEL`, `LOG_STDERR_LEVEL`, `LOG_STDOUT_LEVEL` | [channel's own level](#channel-levels-and-formats) | `LOG_LEVEL` |
| `LOG_DAILY_DAYS` | `daily` 채널의 파일 보관 일수. `0`이면 모두 보관 | `14` |

<a name="log-levels"></a>

### Log levels


로그 레벨은 Laravel이 기록할 메시지를 결정하며 `trace`, `debug`, `info`, `warn`, `error`가 있습니다. 설정한 레벨 이상의 메시지를 기록하므로 `info`에서는 `info`, `warn`, `error` 메시지가 기록됩니다. 로깅을 완전히 끄려면 레벨을 `off`로 설정합니다.


`tracing`의 필터 문법으로 모듈마다 다른 레벨을 설정할 수도 있습니다. 예를 들어 이 필터는 애플리케이션의 `debug` 로그를 활성화하면서 SQLx는 `warn`으로 유지합니다.

```ini
LOG_LEVEL=info,app=debug,sqlx=warn
```


`RUST_LOG`도 같은 필터 문법을 사용합니다. 두 변수가 모두 설정되면 `RUST_LOG`가 우선하므로 셸에서 내보낸 `RUST_LOG`가 `.env`의 `LOG_LEVEL`을 덮어씁니다.

<a name="formats"></a>

### Formats


`text` 형식은 메시지당 읽기 쉬운 한 줄을 기록하므로 로컬 개발 중 터미널에서 읽기 편합니다. `json` 형식은 한 줄에 JSON 객체 하나를 기록하므로 운영 환경에서 로그 수집기가 필드를 수집하고 색인화할 때 적합합니다.

```ini
LOG_FORMAT=json
```


각 JSON 로그 항목은 한 줄에 기록됩니다. 먼저 UTC 기준 `time`, `level`(`trace`, `debug`, `info`, `warning`, `error`), `message`, 기록한 모듈인 `target`이 나옵니다. 이어서 해당 항목을 작성한 요청, 명령어, 예약 작업, 틱, 잡, 워크플로가 `request`나 `job` 같은 개별 객체로 표시되므로 로그 수집기는 `request.path`, `job.queue`, `workflow.step` 같은 경로를 조회할 수 있습니다. 항목 자체의 필드는 `fields` 아래에, 추가한 [context values](#adding-context)는 `context` 아래에 있습니다. 다음 예제는 읽기 쉽도록 여러 줄로 표시했습니다.

```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
    }
}
```


명령어, 예약 작업, 틱, 잡, 워크플로는 `"job": {"name": "podcasts.process", "queue": "podcasts", …}`나 `"workflow": {"name": "orders.fulfil", "run": "…", "step": "charge", "attempt": 1}`처럼 `name`으로 이름을 나타냅니다. [Laravel Cloud](https://laravel.com/cloud)에서는 `laravel-cloud-socket` 채널이 같은 줄을 Cloud의 Logs 페이지로 보내며 요청 객체에는 Cloud의 요청 ID도 `cloud_request_id`로 포함됩니다. [OpenTelemetry tracing](/rust/docs/tracing)을 활성화하면 JSON 줄에 `trace_id`와 `span_id`도 포함됩니다.

<a name="channels"></a>

### Channels


채널은 Laravel이 로그를 기록할 위치를 결정합니다.

| 채널 | 대상 |
| --- | --- |
| `stderr` | 프로세스 관리자와 컨테이너가 로그를 수집하는 표준 오류. 기본값입니다. |
| `stdout` | 표준 출력. |
| `daily` | `laravel.2026-10-04.log`처럼 `storage/logs`에 있는 일별 순환 파일. |


여러 채널에 동시에 기록하려면 `LOG_CHANNEL`에서 채널 이름을 쉼표로 구분합니다.

<a name="channel-levels-and-formats"></a>

### Channel levels and formats


기본적으로 `LOG_LEVEL`과 `LOG_FORMAT`은 모든 채널에 적용됩니다. 특정 채널의 최소 레벨을 다르게 설정하려면 `LOG_DAILY_LEVEL`, `LOG_STDERR_LEVEL`, `LOG_STDOUT_LEVEL`을 설정합니다.


경고와 오류의 로컬 사본을 보관하려면 `.env` 파일의 `LOG_CHANNEL`에 `daily`를 추가합니다. 다음 설정은 표준 오류에 `info` 이상의 메시지를 기록하고 디스크에는 경고와 오류만 저장합니다.

```ini
LOG_CHANNEL=stderr,daily
LOG_LEVEL=info
LOG_DAILY_LEVEL=warn
```


채널마다 형식을 지정하려면 `src/config/logging.rs` [config file](/rust/docs/configuration#config-files)에서 채널을 설정합니다. 예를 들어 다음 설정은 `stderr`를 텍스트로 유지하고 일별 파일을 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)
    }
}
```


`src/config/mod.rs`에 `mod logging;`으로 모듈을 선언합니다. 코드로 설정한 채널은 `LOG_CHANNEL`을 대체하며 `LOG_<CHANNEL>_LEVEL` 변수를 무시하므로 위 예처럼 `.level(...)`로 각 채널의 레벨을 지정하세요.

<a name="writing-log-messages"></a>

## Writing log messages


애플리케이션 어디서나 `tracing`의 매크로로 로그 메시지를 작성할 수 있습니다. 로그 레벨마다 하나의 매크로가 있습니다.

```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");
```


각 메시지에는 활성 요청, 명령어, 잡의 [context](#request-context)가 자동으로 포함되므로 요청 ID나 경로를 수동으로 기록할 필요가 없습니다.

<a name="structured-fields"></a>

### Structured fields


로그 메시지가 게시물이나 사용자 같은 특정 레코드를 가리킬 때는 ID를 메시지 문자열에 삽입하지 말고 구조화된 필드로 전달합니다. 예를 들어 다음 핸들러는 사용자가 발행하는 게시물을 각각 기록합니다.

```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())
}
```


`text` 형식에서는 필드가 메시지 뒤에 표시됩니다. `json` 형식에서는 각 필드가 항목의 `fields` 객체 키가 되므로 로그 수집기에서 게시물 `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
```


구조화된 필드는 숫자, 문자열, 불리언을 직접 받습니다. 다른 타입을 `Display`나 `Debug` 구현으로 기록하려면 필드에 `%`(`Display`) 또는 `?`(`Debug`) 접두사를 붙입니다. 접두사가 없으면 `Timestamp` 같은 타입은 컴파일되지 않습니다.

```rust
tracing::warn!(%user.email, ?user.email_verified_at, "The welcome email bounced");
```

<a name="request-context"></a>

## Request context


애플리케이션이 여러 요청을 동시에 처리하므로 서로 다른 요청의 로그 줄이 섞입니다. 하나의 요청을 추적할 수 있도록 Laravel은 요청의 `id`, `method`, `path`, `route`가 담긴 `request` 스팬 안에서 각 요청을 실행합니다. 해당 요청 중 기록되는 모든 로그 줄은 애플리케이션이나 패키지에서 발생했는지와 관계없이 이 필드를 상속합니다.

```text
INFO request{id=4bf92f3577b34da6a3ce929d0e0e4736 method=GET path=/users/1 route=/users/{user}}: app::users: Looking up the user
```


요청이 끝나면 Laravel은 [status and duration](#framework-log-lines)을 기록한 요약 줄도 작성합니다. [streamed response](/rust/docs/responses#streamed-responses), 다운로드, [event stream](/rust/docs/responses#event-streams)은 마지막 청크를 보낸 뒤 해당 줄을 기록하므로 소요 시간에 응답 전체가 포함됩니다. 응답 완료 전에 클라이언트 연결이 끊어지면 상태를 `499`로 기록합니다.

<a name="request-ids"></a>

### Request IDs


모든 응답은 `X-Request-Id` 헤더에 요청 ID를 포함하므로 사용자가 오류를 보고하면 이 ID로 로그를 검색할 수 있습니다. 로드 밸런서 등에서 이미 `X-Request-Id` 헤더를 포함한 요청이 오면 Laravel은 해당 값을 유지합니다. 핸들러에서 요청 ID를 읽으려면 `RequestId` 인수를 받습니다.

```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


HTTP 요청 외부에서 실행하는 작업에도 스팬이 부여됩니다. 모든 콘솔 명령어은 명령어 이름을 기록하는 `command` 스팬 안에서 실행됩니다.

```text
INFO command{command=reports:generate}: app::reports: Generating the monthly report
```


`serve`, `schedule:work`, `queue:work` 같은 [Long-running commands](/rust/docs/console#long-running-commands)는 전체 수명을 단일 `command` 스팬으로 감싸지 않습니다. 대신 각 요청, [scheduled task](/rust/docs/scheduling), [queued job](/rust/docs/queues)가 개별 스팬에서 실행됩니다. `scheduled_task` 스팬은 작업 설명을 기록하고 `job` 스팬은 잡의 ID, 이름, 연결, 큐, 시도 횟수를 기록합니다.

<a name="adding-context"></a>

### Adding context


멀티테넌트 애플리케이션의 현재 테넌트처럼 요청 중 작성되는 모든 로그 항목에 공유 정보를 포함해야 할 때가 있습니다. [`laravel::context::add`](/rust/docs/context#adding-to-the-context)로 추가한 컨텍스트 값은 보고된 오류를 포함해 해당 요청의 이후 모든 로그 항목에 자동으로 붙습니다. `text` 형식에서는 메시지 필드 뒤에, `json` 형식에서는 항목의 `context` 객체 아래에 표시됩니다.

```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"
```


컨텍스트 값을 로그에 기록하지 않고 저장하려면 [`add_hidden`](/rust/docs/context#hidden-values)을 사용합니다.

<a name="errors-and-panics"></a>

## Errors and panics


[error handler](/rust/docs/errors)는 모든 `5xx` 서버 실패를 `error` 레벨로 기록합니다. 항목의 메시지는 오류 자체의 메시지이며, 필드는 오류 타입, 소스 위치, 요청 컨텍스트와 원인이 있으면 그 원인 체인을 기록합니다. 핸들러에서 패닉이 발생하면 로그 항목에 패닉이 발생한 파일과 줄이 포함됩니다.

```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
```


`json` 형식에서는 오류의 타입, 위치, 원인이 `fields` 대신 항목의 `error` 객체 아래에 있습니다.

```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"}}
```


오류 핸들러는 `5xx` 실패만 기록합니다. `404`나 유효성 검증 실패 같은 클라이언트 오류는 예상 가능한 결과이므로 `error` 로그 항목을 생성하지 않습니다. 특정 서버 오류도 로그에서 제외하려면 [ignore its type](/rust/docs/errors#ignoring-errors-by-type)을 설정합니다.

<a name="framework-log-lines"></a>

## Framework log lines


Laravel은 내부 동작을 `laravel::` 대상으로 기록합니다. 대부분 `debug` 레벨이므로 기본 `info` 레벨에서는 나타나지 않습니다. 이를 확인하려면 `LOG_LEVEL`에서 대상 레벨을 높입니다. 예를 들어 다음 필터는 모든 데이터베이스 쿼리와 캐시 작업을 기록합니다.

```ini
LOG_LEVEL=info,laravel::cache=debug,sqlx::query=debug
```

| 대상 | 레벨 | 기록 내용 |
| --- | --- | --- |
| `laravel::request` | 로컬에서는 `info`, 그 외에는 `debug` | 완료된 각 요청의 `status`와 `duration_ms` |
| `laravel::console` | `debug` | 완료된 각 [console command](/rust/docs/console)의 `exit_code`와 `duration_ms` |
| `laravel::queue` | `debug` | 처리된 각 [job](/rust/docs/queues)의 `outcome`과 `duration_ms` |
| `laravel::workflow` | `warn` | 재시도할 실패한 [workflow](/rust/docs/workflows) 단계 시도와 `run`, `step`, `error` |
| `laravel::http::client` | `debug` | 완료된 각 [outgoing request](/rust/docs/http-client)의 `status` 또는 `error` 및 `duration_ms` |
| `laravel::cache` | `debug` | [cache](/rust/docs/cache#logging)가 읽고 쓰거나 삭제한 각 키 |
| `laravel::redis` | `debug` | 인수를 제외한 각 [Redis](/rust/docs/redis) 명령어 |
| `laravel::mail` | `debug` | [mailer](/rust/docs/mail#tracing-and-logging)가 보낸 각 이메일 |
| `laravel::view` | `debug` | 렌더링한 각 [view](/rust/docs/views)의 `duration_ms` |
| `sqlx::query` | `debug` | 각 [database](/rust/docs/database) 문(1초보다 오래 걸리면 `warn`으로 기록) |


요청 로그는 `APP_ENV`가 `local`일 때만 `info`로 기록되므로 개발 중 터미널에서 요청을 볼 수 있습니다. 운영 환경에서는 호스팅 플랫폼의 접근 로그가 보통 이미 각 요청을 기록하므로, Laravel은 중복 기록을 피하기 위해 `debug`로 남깁니다. 애플리케이션 앞에서 접근 로그를 보관하는 계층이 없다면 다음과 같이 다시 활성화할 수 있습니다.

```ini
LOG_LEVEL=info,laravel::request=debug
```

<a name="sending-logs-elsewhere"></a>

## Sending logs elsewhere


채널은 표준 출력이나 로컬 파일에 기록하지만, 팀에 알림을 주는 외부 추적 서비스로 오류를 전달하고 싶을 수도 있습니다. `tracing`과 통합되는 서비스는 `src/app.rs`의 `with_logging`으로 등록한 `tracing` 레이어를 통해 로그를 받을 수 있습니다. 사용자 지정 레이어는 기본적으로 모든 레벨의 이벤트를 받으므로 `tracing_subscriber`의 `with_filter`로 필터를 붙이세요.


[service provider](/rust/docs/packages#service-providers)는 `register` 메서드의 `app.logging()`으로 레이어를 등록할 수도 있습니다. 패키지에서 레이어를 등록하는 자세한 방법은 패키지 개발 가이드의 [logging](/rust/docs/packages#logging) 절을 참고하세요. 로그 메시지 대신 분산 트레이스를 내보내려면 [tracing guide](/rust/docs/tracing)를 참고하세요.

<a name="sentry"></a>

### Sentry


[Sentry](https://sentry.io)로 오류를 보내려면 `Cargo.toml`에 `sentry` 크레이트(`tracing` 기능 포함)와 `tracing-subscriber`를 추가합니다. 그런 다음 오류를 처리할 Sentry의 `tracing` 레이어를 등록하고 `src/app.rs`의 부팅 훅에서 Sentry를 초기화합니다.

```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) })
```


Sentry는 `main`이 아닌 부팅 훅에서 초기화하세요. Laravel이 부팅 직전에 `.env`를 프로세스 환경으로 불러오므로 `sentry::init`이 그곳에 정의된 `SENTRY_DSN`을 읽습니다. `ClientInitGuard`를 컨테이너에 보관하면 애플리케이션 종료 시 Sentry가 대기 중인 이벤트를 모두 전송하므로 실행 시간이 짧은 콘솔 명령어의 오류도 유실되지 않습니다.


오류 핸들러가 모든 서버 실패를 `error` 레벨로 기록하므로 직접 기록한 오류와 함께 Sentry에 도착합니다. Sentry의 tracing 레이어는 [added to the request context](#adding-context)한 값을 자동으로 포함하지 않습니다. 해당 컨텍스트 값을 포함하거나 tracing 레이어가 없는 서비스로 실패를 전달하려면 오류 [reporter](/rust/docs/errors#reporting-errors)를 등록하고 `context::all()`로 값을 읽습니다.