eliashaeussler/transient-logger

PSR-3 compliant logger to store logs in memory, especially useful for testing

1.0.0 2023-11-23 09:41 UTC

This package is auto-updated.

Last update: 2024-11-05 05:19:05 UTC


README

Transient PSR-3 logger

Coverage Maintainability CGL Tests Supported PHP Versions

This library provides a small PSR-3 compliant logger to stores log records in memory. Each log is converted to a log record and attached to the current logger instance. Logs will be available as long as the logger object is available in memory. This is especially useful for testing applications and libraries.

🔥 Installation

Packagist Packagist Downloads

composer require --dev eliashaeussler/transient-logger

⚡ Usage

Create logger

The library provides a TransientLogger class which implements PSR's LoggerInterface. You can use it just like any other PSR-3 compliant logger:

use EliasHaeussler\TransientLogger;

$logger = new TransientLogger\TransientLogger();

Log messages

For each logged message, a new Log\LogRecord is created and attached to the logger instance. The appropriate log levels are represented by a Log\LogLevel enum which is a wrapper around PSR's LogLevel constants.

// Log using generic log() method
$logger->log(
    TransientLogger\Log\LogLevel::Alert,
    'Houston, we have a problem!',
    ['error' => 'rocket down'],
);

// Log using specific methods
$logger->alert('Houston, we have a problem!', ['error' => 'rocket down']);

Access log records

You can access all log records in several ways:

// Get all log records
$logs = $logger->getAll();

// Get by specific log level
$errors = $logger->getByLogLevel(TransientLogger\Log\LogLevel::Error);

// Iterate over log records
foreach ($logger as $logRecord) {
    $level = $logRecord->level; // instanceof \EliasHaeussler\TransientLogger\Log\LogLevel
    $message = $logRecord->message; // string or instanceof Stringable
    $context = $logRecord->context; // array<string, mixed>
}

Flush log

If required, you can always flush the log attached to a logger:

$logger->flushLog();

🧑‍💻 Contributing

Please have a look at CONTRIBUTING.md.

⭐ License

This project is licensed under GNU General Public License 3.0 (or later).