PHPackages                             dschuppelius/php-error-toolkit - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. dschuppelius/php-error-toolkit

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

dschuppelius/php-error-toolkit
==============================

Reused codes for my api php sdks

v2.1.3.1(2mo ago)11.2k1MITPHPPHP &gt;=8.1 &lt;8.6CI passing

Since Jan 26Pushed 3mo ago2 watchersCompare

[ Source](https://github.com/DSchuppelius/php-error-toolkit)[ Packagist](https://packagist.org/packages/dschuppelius/php-error-toolkit)[ RSS](/packages/dschuppelius-php-error-toolkit/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (4)Versions (38)Used By (1)

PHP Error Toolkit
=================

[](#php-error-toolkit)

[![PHP Version](https://camo.githubusercontent.com/6d92b55b38bd0abf68aa878efb9188d71104c1214a7428c6f1f6b0879a5190eb/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e312d2d382e342d626c75652e737667)](https://www.php.net/)[![PSR-3 Compliant](https://camo.githubusercontent.com/b70824c02a946ca4d27ccce325c92a85468374a83ce5cbc467ca6333e4640ff7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5053522d2d332d436f6d706c69616e742d677265656e2e737667)](https://www.php-fig.org/psr/psr-3/)[![License: MIT](https://camo.githubusercontent.com/fdf2982b9f5d7489dcf44570e714e3a15fce6253e0cc6b5aa61a075aac2ff71b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d79656c6c6f772e737667)](https://opensource.org/licenses/MIT)

A PSR-3 compliant logging library built for PHP 8.1+ with a focus on console and file logging. Designed as a lightweight, reusable component for modern PHP applications.

Features
--------

[](#features)

- 🎯 **PSR-3 Compliant** - Full compatibility with PSR-3 logging standards
- 🖥️ **Console Logging** - Colored output with ANSI support and terminal detection
- 📄 **File Logging** - Automatic log rotation and fail-safe mechanisms
- 🏭 **Factory Pattern** - Clean instantiation with singleton behavior
- 🌐 **Global Registry** - Centralized logger management across your application
- ✨ **Magic Methods** - Convenient `logDebug()`, `logInfo()`, `logErrorAndThrow()` methods via trait
- ⏱️ **Timer Logging** - Measure execution time with `logInfoWithTimer()` and similar methods
- 🔄 **Conditional Logging** - `logInfoIf()`, `logErrorUnless()` for conditional log output
- 🔧 **OS Helper** - Cross-platform system detection and utilities
- 🎨 **Cross-Platform** - Windows, Linux and macOS terminal support
- 🧪 **Fully Tested** - Comprehensive test suite with PHPUnit

Installation
------------

[](#installation)

Install via [Composer](https://getcomposer.org/):

```
composer require dschuppelius/php-error-toolkit
```

Requirements
------------

[](#requirements)

- PHP 8.1 to 8.4
- PSR-3 Log Interface

Quick Start
-----------

[](#quick-start)

### Basic Usage with Console Logger

[](#basic-usage-with-console-logger)

```
use ERRORToolkit\Factories\ConsoleLoggerFactory;

// Create a console logger
$logger = ConsoleLoggerFactory::getLogger();

// Log messages with different levels
$logger->info('Application started');
$logger->warning('This is a warning message');
$logger->error('An error occurred');
```

### File Logging

[](#file-logging)

```
use ERRORToolkit\Factories\FileLoggerFactory;

// Create a file logger
$logger = FileLoggerFactory::getLogger('/path/to/logfile.log');

// Log with context
$logger->error('Database connection failed', [
    'host' => 'localhost',
    'port' => 3306,
    'error' => 'Connection timeout'
]);
```

### Using the ErrorLog Trait

[](#using-the-errorlog-trait)

Add logging capabilities to any class:

```
use ERRORToolkit\Traits\ErrorLog;
use ERRORToolkit\Factories\ConsoleLoggerFactory;

class MyService {
    use ErrorLog;

    public function __construct() {
        // Set up logging
        self::setLogger(ConsoleLoggerFactory::getLogger());
    }

    public function doSomething() {
        $this->logInfo('Starting operation');

        try {
            // Your code here
            $this->logDebug('Operation completed successfully');
        } catch (Exception $e) {
            $this->logError('Operation failed: ' . $e->getMessage());
        }
    }
}
```

Logger Types
------------

[](#logger-types)

### Console Logger

[](#console-logger)

- Colored output with level-specific colors
- Automatic terminal detection
- Debug console support (VS Code, etc.)
- Clean formatting with newline management

### File Logger

[](#file-logger)

- Automatic log rotation when size limit exceeded
- Fail-safe fallback to console/syslog
- Customizable file size limits
- Thread-safe file operations

### Null Logger

[](#null-logger)

- Silent logger for testing/production environments
- PSR-3 compliant no-op implementation

Global Logger Registry
----------------------

[](#global-logger-registry)

Manage loggers globally across your application:

```
use ERRORToolkit\LoggerRegistry;
use ERRORToolkit\Factories\FileLoggerFactory;

// Set a global logger
LoggerRegistry::setLogger(FileLoggerFactory::getLogger('app.log'));

// Use it anywhere in your application
if (LoggerRegistry::hasLogger()) {
    $logger = LoggerRegistry::getLogger();
    $logger->info('Using global logger');
}

// Reset when needed
LoggerRegistry::resetLogger();
```

Log Levels
----------

[](#log-levels)

Supports all PSR-3 log levels with integer-based filtering:

- `EMERGENCY` (0) - System is unusable
- `ALERT` (1) - Action must be taken immediately
- `CRITICAL` (2) - Critical conditions
- `ERROR` (3) - Error conditions
- `WARNING` (4) - Warning conditions
- `NOTICE` (5) - Normal but significant condition
- `INFO` (6) - Informational messages
- `DEBUG` (7) - Debug-level messages

ErrorLog Trait Features
-----------------------

[](#errorlog-trait-features)

The `ErrorLog` trait provides comprehensive logging capabilities with multiple advanced features:

### Magic Methods

[](#magic-methods)

All PSR-3 log levels are available as magic methods:

```
use ERRORToolkit\Traits\ErrorLog;

class MyClass {
    use ErrorLog;

    public function example() {
        // Instance methods - these methods are automatically available
        $this->logDebug('Debug message');
        $this->logInfo('Info message');
        $this->logNotice('Notice message');
        $this->logWarning('Warning message');
        $this->logError('Error message');
        $this->logCritical('Critical message');
        $this->logAlert('Alert message');
        $this->logEmergency('Emergency message');

        // All methods support context arrays
        $this->logError('Database error', ['table' => 'users', 'id' => 123]);
    }

    public static function staticExample() {
        // Static methods - all static magic methods are available
        self::logDebug('Static debug message');
        self::logInfo('Static info message');
        self::logNotice('Static notice message');
        self::logWarning('Static warning message');
        self::logError('Static error message');
        self::logCritical('Static critical message');
        self::logAlert('Static alert message');
        self::logEmergency('Static emergency message');

        // Static methods also support context
        self::logInfo('User action', ['user' => 'admin', 'action' => 'login']);
    }
}
```

### Conditional Logging

[](#conditional-logging)

Log messages only when conditions are met:

```
use ERRORToolkit\Traits\ErrorLog;

class DataProcessor {
    use ErrorLog;

    public function process(array $data, bool $verbose = false) {
        // Log only if condition is true
        $this->logDebugIf($verbose, 'Verbose mode enabled');

        // Log only if condition is false
        $this->logWarningUnless(count($data) > 0, 'Empty data received');

        // Works with all log levels
        $this->logInfoIf($verbose, 'Processing started', ['count' => count($data)]);
        $this->logErrorUnless($this->validate($data), 'Validation failed');
    }
}
```

### Log with Timer

[](#log-with-timer)

Measure execution time of operations:

```
use ERRORToolkit\Traits\ErrorLog;

class PerformanceService {
    use ErrorLog;

    public function heavyOperation() {
        // Execute callback and log duration
        $result = $this->logInfoWithTimer(function() {
            // Heavy processing...
            return $this->processData();
        }, 'Heavy operation');
        // Logs: "Heavy operation (completed in 123.45 ms)"

        return $result;
    }

    public function apiCall() {
        // Works with all log levels
        return $this->logDebugWithTimer(function() {
            return file_get_contents('https://api.example.com/data');
        }, 'API request');
    }
}
```

### Log and Return

[](#log-and-return)

Log a message and return a value in one call:

```
use ERRORToolkit\Traits\ErrorLog;

class Calculator {
    use ErrorLog;

    public function calculate(int $value): int {
        $result = $value * 2;

        // Log and return in one call
        return $this->logDebugAndReturn($result, 'Calculation complete', ['input' => $value]);
    }

    public function findUser(int $id): ?User {
        $user = $this->repository->find($id);

        return $user !== null
            ? $this->logInfoAndReturn($user, 'User found', ['id' => $id])
            : $this->logWarningAndReturn(null, 'User not found', ['id' => $id]);
    }
}
```

### Log Exceptions

[](#log-exceptions)

Log exceptions with full stack trace:

```
use ERRORToolkit\Traits\ErrorLog;
use Psr\Log\LogLevel;

class ExceptionHandler {
    use ErrorLog;

    public function handle(\Throwable $e): void {
        // Log exception with full context (file, line, trace)
        self::logException($e);

        // With custom log level
        self::logException($e, LogLevel::CRITICAL);

        // With additional context
        self::logException($e, LogLevel::ERROR, ['user_id' => 123]);
    }
}
```

### Log and Throw Exceptions

[](#log-and-throw-exceptions)

Combine logging and exception throwing in a single call with `log{Level}AndThrow()`:

```
use ERRORToolkit\Traits\ErrorLog;
use RuntimeException;
use InvalidArgumentException;

class ValidationService {
    use ErrorLog;

    public function validateUser(array $data): void {
        if (empty($data['email'])) {
            // Logs error and throws exception in one call
            $this->logErrorAndThrow(
                InvalidArgumentException::class,
                'Email is required'
            );
        }

        if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
            // With context array
            $this->logWarningAndThrow(
                InvalidArgumentException::class,
                'Invalid email format',
                ['email' => $data['email']]
            );
        }
    }

    public function processPayment(float $amount): void {
        try {
            // Payment processing...
        } catch (\Exception $e) {
            // With exception chaining
            $this->logCriticalAndThrow(
                RuntimeException::class,
                'Payment processing failed',
                ['amount' => $amount],
                $e  // Previous exception for chaining
            );
        }
    }

    public static function validateConfig(array $config): void {
        if (!isset($config['api_key'])) {
            // Static usage
            self::logErrorAndThrow(
                RuntimeException::class,
                'API key not configured'
            );
        }
    }
}
```

**Available log-and-throw methods:**

MethodLog Level`logErrorAndThrow()`ERROR`logCriticalAndThrow()`CRITICAL`logAlertAndThrow()`ALERT`logEmergencyAndThrow()`EMERGENCY**Method signature:**

```
log{Level}AndThrow(
    string $exceptionClass,    // Exception class to throw (e.g., RuntimeException::class)
    string $message,           // Error message (used for both log and exception)
    array $context = [],       // Optional: Context array for logging
    ?Throwable $previous = null // Optional: Previous exception for chaining
): never
```

### Logger Management

[](#logger-management)

The trait provides flexible logger management:

```
use ERRORToolkit\Traits\ErrorLog;
use ERRORToolkit\Factories\FileLoggerFactory;

class MyService {
    use ErrorLog;

    public function __construct() {
        // Set a specific logger for this class
        self::setLogger(FileLoggerFactory::getLogger('service.log'));

        // Or use global logger from registry (automatic fallback)
        self::setLogger(); // Uses LoggerRegistry::getLogger()
    }
}
```

### Automatic Project Detection

[](#automatic-project-detection)

The trait automatically detects project names from class namespaces:

```
namespace MyCompany\ProjectName\Services;

use ERRORToolkit\Traits\ErrorLog;

class UserService {
    use ErrorLog;

    public function process() {
        // Project name "MyCompany" is automatically detected
        // Log entry: [2025-12-29 10:30:00] info [MyCompany::UserService::process()]: Processing user
        $this->logInfo('Processing user');
    }
}
```

### Fallback Logging System

[](#fallback-logging-system)

When no logger is available, the trait provides intelligent fallbacks:

1. **Primary**: Uses configured PSR-3 logger
2. **Fallback 1**: PHP error\_log() if configured
3. **Fallback 2**: System syslog with project-specific facility
4. **Fallback 3**: File logging to system temp directory

```
class EmergencyService {
    use ErrorLog;

    public function criticalOperation() {
        // Even without explicit logger setup, this will work
        // Falls back through: error_log → syslog → temp file
        self::logEmergency('System failure detected');
    }
}
```

### Context Support

[](#context-support)

All logging methods support PSR-3 context arrays:

```
class ApiService {
    use ErrorLog;

    public function handleRequest($request) {
        $context = [
            'method' => $request->method,
            'url' => $request->url,
            'user_id' => $request->user?->id,
            'timestamp' => time()
        ];

        $this->logInfo('API request received', $context);

        try {
            // Process request
        } catch (Exception $e) {
            $this->logError('API request failed', [
                ...$context,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
        }
    }
}
```

Configuration
-------------

[](#configuration)

### Log Level Filtering

[](#log-level-filtering)

```
use ERRORToolkit\Logger\ConsoleLogger;
use Psr\Log\LogLevel;

// Only log warnings and above
$logger = new ConsoleLogger(LogLevel::WARNING);
$logger->info('This will be ignored');
$logger->warning('This will be logged');
```

### File Logger Options

[](#file-logger-options)

```
use ERRORToolkit\Logger\FileLogger;

$logger = new FileLogger(
    logFile: '/var/log/app.log',
    logLevel: LogLevel::INFO,
    failSafe: true,           // Fallback to console/syslog on file errors
    maxFileSize: 5000000,     // 5MB before rotation
    rotateLogs: true          // Create .old backup when rotating
);
```

Testing
-------

[](#testing)

Run the test suite:

```
composer test
```

Or run PHPUnit directly:

```
vendor/bin/phpunit
```

Cross-Platform Terminal Support
-------------------------------

[](#cross-platform-terminal-support)

The toolkit automatically detects:

- Windows VT100 support via `sapi_windows_vt100_support()`
- Unix/Linux TTY via `posix_isatty()`
- Debug consoles (VS Code, PHPStorm, etc.)
- PHPUnit color configuration

Helper Classes
--------------

[](#helper-classes)

### OsHelper

[](#oshelper)

Cross-platform operating system detection and utilities:

```
use ERRORToolkit\Helper\OsHelper;

// OS Detection
OsHelper::isWindows();    // true on Windows
OsHelper::isLinux();      // true on Linux
OsHelper::isMacOS();      // true on macOS
OsHelper::isUnix();       // true on Linux or macOS
OsHelper::getOsName();    // 'Windows', 'Linux', 'macOS'

// Path Utilities
OsHelper::getPathSeparator();     // '\' on Windows, '/' on Unix
OsHelper::getEnvPathSeparator();  // ';' on Windows, ':' on Unix
OsHelper::getHomeDirectory();     // User's home directory
OsHelper::getTempDirectory();     // System temp directory

// Executable Utilities
OsHelper::isExecutable('/path/to/file');  // Check if file is executable
OsHelper::findExecutable('git');          // Find executable in PATH

// User Information
OsHelper::getCurrentUsername();   // Current user name
OsHelper::getCurrentUserId();     // UID (Unix only)
OsHelper::isPrivilegedUser();     // Check for root/admin

// System Information
OsHelper::getCpuCoreCount();      // Number of CPU cores
OsHelper::getArchitecture();      // System architecture (x86_64, arm64, etc.)
OsHelper::getKernelVersion();     // Kernel version
OsHelper::getSystemInfo();        // Complete system info array

// Environment Variables
OsHelper::getEnv('HOME', '/default');  // Get env var with default
OsHelper::setEnv('MY_VAR', 'value');   // Set env var
```

### TerminalHelper

[](#terminalhelper)

Terminal detection and capabilities:

```
use ERRORToolkit\Helper\TerminalHelper;

TerminalHelper::isTerminal();      // Check if running in terminal
TerminalHelper::isDebugConsole();  // Check if running in debug console
TerminalHelper::getCursorColumn(); // Get current cursor position
```

### PhpUnitHelper

[](#phpunithelper)

PHPUnit-specific utilities:

```
use ERRORToolkit\Helper\PhpUnitHelper;

PhpUnitHelper::isRunningInPhpunit();  // Check if running in PHPUnit
PhpUnitHelper::supportsColors();      // Check PHPUnit color configuration
```

Architecture
------------

[](#architecture)

- **Factory Pattern** - All loggers created via factories with singleton behavior
- **Strategy Pattern** - Different logging strategies (Console, File, Null)
- **Registry Pattern** - Global logger management
- **Trait-based** - Easy integration via `ErrorLog` trait
- **Helper Classes** - Reusable utilities for OS detection, terminal handling, PHPUnit support
- **PSR-3 Compliant** - Standard logging interface

License
-------

[](#license)

MIT License. See [LICENSE](LICENSE) file for details.

Author
------

[](#author)

Daniel Jörg Schuppelius

- Website: [schuppelius.org](https://schuppelius.org)
- Email:

Contributing
------------

[](#contributing)

This is a personal toolkit for Daniel Schuppelius's projects. For bugs or feature requests, please open an issue.

###  Health Score

49

—

FairBetter than 95% of packages

Maintenance85

Actively maintained with recent releases

Popularity20

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity67

Established project with proven stability

 Bus Factor1

Top contributor holds 62.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~11 days

Total

37

Last Release

60d ago

Major Versions

v0.1.0 → v1.1.02025-01-30

v1.5.2 → v2.02026-01-10

PHP version history (4 changes)v0.1.0PHP ^8.2 || ^8.3

v1.3.5.1PHP &gt;=8.2 &lt;8.5

v1.4PHP &gt;=8.1 &lt;8.5

v2.1.3.1PHP &gt;=8.1 &lt;8.6

### Community

Maintainers

![](https://www.gravatar.com/avatar/9d648df75b8ca254b14377de6aa7c37daff5bc21e9e8742ef7687c7091c7bc94?d=identicon)[l0gtr0n](/maintainers/l0gtr0n)

---

Top Contributors

[![DSchuppelius](https://avatars.githubusercontent.com/u/19145058?v=4)](https://github.com/DSchuppelius "DSchuppelius (5 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (2 commits)")[![gklimm](https://avatars.githubusercontent.com/u/1778681?v=4)](https://github.com/gklimm "gklimm (1 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/dschuppelius-php-error-toolkit/health.svg)

```
[![Health](https://phpackages.com/badges/dschuppelius-php-error-toolkit/health.svg)](https://phpackages.com/packages/dschuppelius-php-error-toolkit)
```

###  Alternatives

[ecotone/ecotone

Supporting you in building DDD, CQRS, Event Sourcing applications with ease.

558549.8k17](/packages/ecotone-ecotone)[civicrm/civicrm-core

Open source constituent relationship management for non-profits, NGOs and advocacy organizations.

728272.9k20](/packages/civicrm-civicrm-core)[j0k3r/php-readability

Automatic article extraction from HTML

186808.8k6](/packages/j0k3r-php-readability)[symfony/ai-platform

PHP library for interacting with AI platform provider.

51927.7k136](/packages/symfony-ai-platform)[symfony/ai-agent

PHP library for building agentic applications.

30536.7k44](/packages/symfony-ai-agent)[spomky-labs/pwa-bundle

Progressive Web App Manifest Generator Bundle for Symfony.

6144.4k1](/packages/spomky-labs-pwa-bundle)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
