Skip to content

exbico/monolog-exception-processor

Repository files navigation

MONOLOG EXCEPTION PROCESSOR

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

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages