PHP code example of mafin / simple-logger

1. Go to this page and download the library: Download mafin/simple-logger library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mafin / simple-logger example snippets


use Mafin\SimpleLogger\Logger;
use Psr\Log\LogLevel;

// Create a logger that writes to a file
$logger = new Logger('app.log', LogLevel::DEBUG);

// Log messages at different levels
$logger->info('This is an info message.');
$logger->error('This is an error message.');
$logger->debug('Debug information');

$logger->info('User {username} logged in from {ip}', [
    'username' => 'john_doe',
    'ip' => '192.168.1.1',
]);
// Output: [2025-11-05 12:34:56] [info] User john_doe logged in from 192.168.1.1

use Mafin\SimpleLogger\Infrastructure\FileLogWriter;
use Mafin\SimpleLogger\Infrastructure\DefaultLogFormatter;
use Mafin\SimpleLogger\Logger;
use Psr\Log\LogLevel;

// Custom writer
$writer = new FileLogWriter('logs/app.log');

// Custom formatter (optional)
$formatter = new DefaultLogFormatter();

// Inject dependencies
$logger = new Logger($writer, LogLevel::INFO, $formatter);

use Mafin\SimpleLogger\Contract\LogWriterInterface;

class DatabaseLogWriter implements LogWriterInterface
{
    public function __construct(private PDO $pdo) {}

    public function write(string $message): void
    {
        $stmt = $this->pdo->prepare('INSERT INTO logs (message) VALUES (?)');
        $stmt->execute([$message]);
    }
}

$logger = new Logger(new DatabaseLogWriter($pdo), LogLevel::INFO);

use Mafin\SimpleLogger\Contract\LogFormatterInterface;

class JsonFormatter implements LogFormatterInterface
{
    public function format(string $level, string|\Stringable $message, array $context = []): string
    {
        return json_encode([
            'timestamp' => time(),
            'level' => $level,
            'message' => (string) $message,
            'context' => $context,
        ]) . PHP_EOL;
    }
}

$logger = new Logger('app.log', LogLevel::DEBUG, new JsonFormatter());

src/
├── Contract/              # Interfaces (abstraction layer)
│   ├── LogWriterInterface.php
│   └── LogFormatterInterface.php
├── Infrastructure/        # Concrete implementations
│   ├── FileLogWriter.php
│   └── DefaultLogFormatter.php
└── Logger.php            # Main logger orchestration