PHP

Minimal PSR-3 Logger

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
A 30-line PSR-3 compatible logger you can drop into any project that expects \Psr\Log\LoggerInterface. Writes to a file using the JSON structured format.
PHP
Raw
<?php
namespace App\Logging;

use Psr\Log\AbstractLogger;
use Stringable;

final class FileLogger extends AbstractLogger {
    public function __construct(private string $path) {}

    public function log($level, string|Stringable $message, array $context = []): void {
        // PSR-3 placeholder substitution: "{key}" → $context['key']
        $msg = (string)$message;
        foreach ($context as $k => $v) {
            if (!is_array($v) && (!is_object($v) || method_exists($v, '__toString'))) {
                $msg = str_replace('{' . $k . '}', (string)$v, $msg);
            }
        }
        $entry = json_encode([
            'ts'    => date('c'),
            'level' => (string)$level,
            'msg'   => $msg,
            'ctx'   => $context,
        ]) . PHP_EOL;
        file_put_contents($this->path, $entry, FILE_APPEND | LOCK_EX);
    }
}

$log = new FileLogger('/var/log/myapp.log');
$log->info('user {id} signed in', ['id' => 42]);
Tags

Save your own code snippets

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