0

Background

I want to save symfony / monolog Logs into my database. I followed this guide which is acutally giving a good solution.

Problem

My solution is working in general, but I get errors (Serialization of 'Closure' is not allowed) while trying to save the CONTEXT variable. I have no idea, what is the problem or how to fix it.

Any idea? Many Thanks!

class WebsiteLogger {
    [...]

    /**
     * @ORM\Column(type="string", type="array", nullable=true)
     */
    private $context;

    /**
     * @ORM\Column(type="string", type="array", nullable=true)
     */
    private $extra;

    [...]
}
class DatabaseHandler extends AbstractProcessingHandler {
    private $emi;

    public function __construct(EntityManagerInterface $emi) {
        $this->emi        = $emi;
        parent::__construct();
    }

    protected function write(array $record): void {

        try {

            // store into database
            $logItem = new WebsiteLogger();
            $logItem->setChannel($record['channel']);
            $logItem->setLevel($record['level']);
            $logItem->setLevelName($record['level_name']);
            $logItem->setMessage($record['message']);
            $logItem->setLoggedAt($record['datetime']);
            $logItem->setExtra($record['extra']);
            $logItem->setContext(["initialization" => "not replaced yet"]);

            $this->emi->persist($logItem);
            $this->emi->flush();

        } catch ( Exception $exception ) {
            return;
        }


        try {
            $logItem->setContext($record['context']);

            $this->emi->persist($logItem); // this is causing the issue
            $this->emi->flush();

        } catch (Exception $exception) {
            dump("save CONTEXT - exception");
            dump($exception);
        }


    }
}
Tim K.
  • 335
  • 4
  • 23
  • What's in your **$record['context']**? If there is Closure, you must remove it before saving to database. Closure can't be serialized. – Pavol Velky Dec 31 '20 at 15:23
  • Well, the content can be very different, pending on the error/exception. That the Closure causes the issue is clear from the description (see above). Any proposal how to cover it? – Tim K. Jan 03 '21 at 08:12

2 Answers2

1

My Solution

There is a nice class in symfony called FlattenException. This is helping to serialize the exception and make it storable into the database.

Have fun!

    // ...

    protected function write(array $record): void {

        try {

            // store into database
            $logItem = new WebsiteLogger();
            $logItem->setChannel($record['channel']);
            $logItem->setLevel($record['level']);
            $logItem->setLevelName($record['level_name']);
            $logItem->setMessage($record['message']);
            $logItem->setLoggedAt($record['datetime']);
            $logItem->setExtra($record['extra']);

            // set a default value that shall be replaced but will be kept in case an exception will be thrown.
            $logItem->setContext(["initialization" => "not replaced (= exception thrown while trying to save the context)"]);

            $this->emi->persist($logItem);
            $this->emi->flush();

        } catch ( Exception $exception ) {
            return;
        }


        try {
           
            $exception = $record['context']['exception'] ?? null;

            if ($exception && $exception instanceof Throwable ) {
                $flattenException = FlattenException::createFromThrowable($exception);

                $context = $flattenException;
            } else {
                $context = $record['context'];
            }

            $logItem->setContext($context);

            $this->emi->persist($logItem);
            $this->emi->flush();

        } catch (Exception $exception) {
            // do nothing
        }


    }
Tim K.
  • 335
  • 4
  • 23
0

You can unset all closures in an array:

$context = $record['context'];
foreach ($context as $key => $value) {
    if ($value instanceof \Closure) {
        unset($context[$key]);
    }
}

But it not support multi dimensional array. You must determine where the closure come from and prevent it to be in context.

Tim K.
  • 335
  • 4
  • 23
Pavol Velky
  • 770
  • 3
  • 9
  • unfortunatelly this answer is not helping on complex and multi-layer objects. It only solves one dimensional arrays – Tim K. Jan 20 '21 at 08:52