exbico/monolog-exception-processor

Monolog processor of exceptions and exception with context

2.0.0 2023-06-09 12:31 UTC

This package is auto-updated.

Last update: 2024-05-09 14:16:46 UTC


README

Latest Stable Version Total Downloads License

INSTALLATION

The preferred way to install this extension is through composer.

Either run

composer require exbico/monolog-exception-processor

or add

"exbico/monolog-exception-processor": "*"

to the require section of your application's composer.json file.

Basic Usage

<?php

use Exbico\Formatter\ExceptionProcessor;
use Monolog\Logger;

$logger = new Logger();
$logger->pushProcessor(new ExceptionProcessor);

USAGE

<?php
try{
    throw new Exception('test');
}catch(Throwable $exception) {
    $logger->alert('message', [..., 'exception' => $exception, ...]);
}

Resulted record for any Throwable

[
  "message" => "message",
  "context" => [...],
  ...
  "extra" => [
    ...
    "exception" => [
      "message" => "test",
      "class"   => "Exception",
      "trace"   => "#0 {main}",
    ],
    ...
  ],
]

Resulted record, if Throwable has previous

[
  "message" => "message",
  "context" => [...],
  ...
  "extra"   => [
    ...
    "exception" => [
      "message"  => "test",
      "class"    => "Exception",
      "trace"    =>"#0 {main}",
      "previous" => [
        "message" => "previous message",
        "class"   => "Class of previous",
        "trace"   => "#0 {main}",
      ],
    ],
    ...
  ],
]

You can implement ExceptionWithContext or extend ContextException

<?php

use Exbico\Formatter\ExceptionWithContext;
use Exbico\Formatter\ExceptionWithContextInterface;

class FooException extends ExceptionWithContext
{

}

class BarException implements ExceptionWithContextInterface
{
    ...

    /**
     * @return array<string, mixed>
     */
    public function getContext(): array
    {
        ...
    }
}

try {
    throw new FooException(message: 'test', context: ['id' => 12, 'text' => '...'], previous: $previousException);
} catch (FooException $exception) {
    $logger->alert('message', ['id' => 34, 'exception' => $exception, 'date' => '...']);
}

Then record will look:

[
  "message" => "message",
  "context" => [
    "id"   => 34,
    "date" => "...",
    "text" => "...",
  ],
  ...
  "extra" => [
    ...
    "exception" => [
      "message"  => "test",
      "class"    => "Exception",
      "trace"    =>"#0 {main}",
      "previous" => [
        "message" => "previous message",
        "class"   => "Class of previous",
        "trace"   => "#0 {main}",
        "context" => [
          ...
        ],
      ],
      "context" => [
        "id"   => 34,
        "date" => "...",
      ],
    ],
    ...
  ],
]

WARNING if you have equal keys in both contexts, then value of exception context has higher priority