PHP code example of dschuppelius / php-error-toolkit
1. Go to this page and download the library: Download dschuppelius/php-error-toolkit 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/ */
dschuppelius / php-error-toolkit example snippets
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');
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'
]);
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());
}
}
}
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();
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');
// Optional: Nachricht zusätzlich als Hex-Bytes ausgeben
$this->logInfoHex('Payload: äöü');
// 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']);
// Auch statisch mit zusätzlicher Hex-Ausgabe
self::logDebugHex('RAW');
}
}
$this->logInfoHex('ABC');
// Output contains three lines:
// [timestamp] info [caller]: ABC
// [timestamp] info [caller] [str]: A B C
// [timestamp] info [caller] [hex]: 41 42 43
use ERRORToolkit\Contracts\Abstracts\LoggerAbstract;
$logger->info('ABC', [LoggerAbstract::CONTEXT_KEY_MESSAGE_HEX => true]);
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');
}
}
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');
}
}
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]);
}
}
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]);
}
}
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 {
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'
);
}
}
}
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
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()
}
}
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');
}
}
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');
}
}
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');
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
);
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
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
use ERRORToolkit\Helper\PhpUnitHelper;
PhpUnitHelper::isRunningInPhpunit(); // Check if running in PHPUnit
PhpUnitHelper::supportsColors(); // Check PHPUnit color configuration
bash
composer
// [str]: ä B
// [hex]: C3 A4 42
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.