PHP code example of helsingborg-stad / psr-logger

1. Go to this page and download the library: Download helsingborg-stad/psr-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/ */

    

helsingborg-stad / psr-logger example snippets


use PsrLogger\LoggerFactory;
use PsrLogger\Loggers\PhpErrorLogger;
use Psr\Log\LogLevel;

$factory = new LoggerFactory(
    namespace: 'MyPlugin',
    loggers: [['logger' => new PhpErrorLogger(), 'logLevel' => LogLevel::ERROR]]
);

$logger = $factory->createLogger();
$logger->error('Something went wrong');
// → [ERROR]:[MyPlugin]: Something went wrong
$logger->debug('Verbose detail');  // suppressed — below ERROR threshold
$logger->info('Just FYI');         // suppressed — below ERROR threshold

$app       = $factory->createLogger();
$moduleA   = $app->createLogger(['namespace' => 'ModuleA']);
$component = $moduleA->createLogger(['namespace' => 'Component']);

$app->error('app');
// → [ERROR]:[MyPlugin]: app

$moduleA->error('moduleA');
// → [ERROR]:[MyPlugin/ModuleA]: moduleA

$component->error('component');
// → [ERROR]:[MyPlugin/ModuleA/Component]: component

$logger->error('User {user.name} failed to log in', ['user' => ['name' => 'Alice']]);
// → [ERROR]:[MyPlugin]: User Alice failed to log in

$logger->debug('Payload: {data}', ['data' => ['id' => 1, 'status' => 'fail']]);
// → [DEBUG]:[MyPlugin]: Payload: {
//       "id": 1,
//       "status": "fail"
//   }

$logger->debug('Response: {res}', ['res' => $someObject]);
// → [DEBUG]:[MyPlugin]: Response: {
//       "prop": "value"
//   }

use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Stringable;

class FileLogger extends NullLogger implements LoggerInterface
{
    public function __construct(private string $path) {}

    public function log($level, string|Stringable $message, array $context = []): void
    {
        file_put_contents($this->path, $message . PHP_EOL, FILE_APPEND);
    }
}

$factory = new LoggerFactory(
    namespace: 'MyPlugin',
    loggers: [['logger' => new FileLogger('/tmp/app.log'), 'logLevel' => LogLevel::DEBUG]]
);