PHP

JSON Structured Logger

admin by @admin ADMIN
5h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Append a single JSON object per line to a log file. Easy to grep and to ship into Datadog / Loki / CloudWatch later without re-parsing.
PHP
Raw
<?php
function logJson(string $path, string $level, string $message, array $context = []): void {
    $entry = json_encode([
        'ts'      => date('c'),
        'level'   => strtoupper($level),
        'msg'     => $message,
        'context' => $context,
        'pid'     => getmypid(),
    ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    file_put_contents($path, $entry . PHP_EOL, FILE_APPEND | LOCK_EX);
}

logJson('/var/log/myapp.log', 'info',  'user signed in', ['user_id' => 42, 'ip' => '10.0.0.1']);
logJson('/var/log/myapp.log', 'error', 'payment failed', ['order_id' => 9001, 'reason' => 'card_declined']);
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.