PHP code example of eryndrix / exception-logger

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

    

eryndrix / exception-logger example snippets


use Eryndrix\Logging\Exceptions\PaginationException;
use Eryndrix\Logging\Exceptions\UserNotFoundException;
use Eryndrix\Logging\Exceptions\UnexpectedException;

throw new PaginationException(perPage: 500);    // WARNING
throw new UserNotFoundException();              // WARNING
throw new UnexpectedException(message: 'Oops'); // CRITICAL

use Eryndrix\Logging\Attributes\{Level, Log};

#[Log(level: Level::WARNING)]
final class PaginationException extends \DomainException {}

#[Log(level: Level::WARNING)]
final class UserNotFoundException extends \LogicException {}

#[Log(level: Level::CRITICAL)]
final class UnexpectedException extends \RuntimeException {}

use Eryndrix\Logging\Contracts\ExceptionLoggerInterface;

class MyService
{
    public function __construct(
        private ExceptionLoggerInterface $logger
    ) {}
    
    public function handle(): void
    {
        try {
            // ...
        } catch (\Throwable $e) {
            $this->logger->log(exception: $e);
        }
    }
}

use Eryndrix\Logging\Contracts\LoggerInterface;

class MyService
{
    public function __construct(
        private LoggerInterface $logger
    ) {}
    
    public function handle(): void
    {
        $exception = new \RuntimeException(
            message: 'error'
        );
        
        $this->logger->error(
            message: 'Something went wrong',
            e: $exception
        );

        $this->logger->warning(
            message: 'Potential issue',
            e: $exception
        );

        $this->logger->debug(
            message: 'Debug info',
            e: $exception
        );
    }
}

'default_level' => env('DEFAULT_LOG_LEVEL', 'error')

'exception_levels' => [
    \DomainException::class => 'warning',
    \InvalidArgumentException::class => 'warning',
    \App\Exceptions\PaginationException::class => 'warning',
]

'context' => [
    'emergency' => [
        'exception' => true,
        'code' => true,
        'file' => true,
        'line' => true,
        'trace' => true,
    ],
    'error' => [
        'exception' => true,
        'code' => true,
        'file' => true,
        'line' => true,
        'trace' => false,
    ],
    'warning' => [
        'exception' => true,
        'code' => true,
        'file' => false,
        'line' => false,
        'trace' => false,
    ],
    // ... other levels
]
bash
php artisan vendor:publish --tag="exception-logger-config"