# Structured logging

What is structured logging?

Structured logging is writing each log record as named fields, such as a level, a message and an order id, instead of one line of free text. A program can then filter and count records by any field without parsing sentences, and a person can still read the record.

## How it works

The same event, written both ways:

```text
[2026-12-05 10:14:03] production.WARNING: Payment declined for order 1042, user 77, reason card_declined
```

```json
{"time": "2026-12-05T10:14:03Z", "level": "warning", "message": "Payment declined", "context": {"order_id": 1042, "user_id": 77, "reason": "card_declined"}}
```

The first can only be searched as text. In the second, `order_id` is a field: you can ask for every record about order 1042, or count declines by reason.

In PHP the fields travel in the context array. PSR-3 gives every log method a context argument, and a message may hold placeholders in braces that are filled in from it:

```php
<?php

Log::warning('Payment declined for order {order_id}', [
    'order_id' => $order->id,
    'reason' => $result->code,
]);
```

Laravel adds `Log::withContext()` (one channel) and `Log::shareContext()` (every channel) for fields that belong on every record of a request, such as a request id. The OpenTelemetry log data model describes the same split in general terms: a record has a timestamp, a severity, a body and a set of attributes, and the body itself may be structured data rather than a string.

## Why it matters

Free text answers the questions someone thought of while writing the message. Fields answer the ones that come up during an incident: which customers, which endpoint, since when. They also let a log system group records by message while keeping the varying values apart, and set the [log level](/glossary/log-level) beside them as a field of its own.

## What can go wrong

- Values are written into the message instead of passed as context, so no filter can pick them out and every record has a different message.
- The same field has different names in different places (`user_id`, `userId`, `user`), and a filter on one misses the rest.
- Whole models or request payloads go into the context and carry passwords, tokens or personal data into the log.
- A field changes type between releases, a number in one and a string in the next, and queries on it stop matching.

## Check it

Ranetrace's [log monitoring](/features/log-monitoring) stores each record's context and extra fields and shows them as JSON beside the message. It groups records by level, channel and message, with ids, email addresses and similar values replaced by placeholders, and for each group lists the most common values of each context field across recent occurrences and the fields that never change.

Read this definition in a browser: https://ranetrace.com/glossary/structured-logging
