[Solved] Custom ErrorLogger in CakePHP 4.6

I am trying to set up a custom ErrorLogger in CakePHP 4.6 like so:

src/Error/MyErrorLogger.php

<?php

declare(strict_types=1);

namespace App\Error;

use Cake\Error\ErrorLogger as CakeErrorLogger;
use Cake\Log\Log;
use Psr\Http\Message\ServerRequestInterface;
use Throwable;

class MyErrorLogger extends CakeErrorLogger
{
    /**
     * Log an exception to Cake's Log subsystem
     *
     * @param \Throwable $exception The exception to log a message for.
     * @param \Psr\Http\Message\ServerRequestInterface|null $request The current request if available.
     * @param bool $includeTrace Whether a stack trace should be logged.
     * @return void
     */
    public function logException(
        Throwable $exception,
        ?ServerRequestInterface $request = null,
        bool $includeTrace = false
    ): void {
        $message = $this->getMessage($exception, false, $includeTrace);

        if ($request !== null) {
            $message .= $this->getRequestContext($request);
        }
        Log::error('My Logger: ' . $message);
    }
}

App.php

 'Error' => [
        'errorLevel' => E_ALL & ~E_USER_DEPRECATED,
        'exceptionRenderer' => 'Cake\Error\ExceptionRenderer',
        'skipLog' => [],
        'log' => true,
        'trace' => true,
        'logger' => MyErrorLogger::class,
    ],

According to the docs, this should replace the default logger in Cake\Error\ErrorLogger.php with my own. However, all logs come from the default logger.

Any help is deeply appreciated!

It should, both for Exceptions and Errors.
Did you upgrade to the new Error and ExceptionTrap as described in the 4.4 migration guide?

Thank you for the quick reply. Yes, I am using the new Traps as described in the docs.

I just saw that Cake’s own ErrorHandlerMiddleware is added to the middleware queue without any parameters. ->add(new ErrorHandlerMiddleware())

When I remove it, MyErrorLogger is correctly applied. Does the middleware overwrite the settings from bootstrap.php?

Well thats your problem then.
You need to pass the error config to the ErrorHandlerMiddleware as you can see in the 4.x app template example.

1 Like

Unless one uses the Tools ErrorHandlerMiddleware, as that one internally consumes the config by default:

1 Like

This seems to be a reasonable approach and has been suggested years ago.

I see two areas for making this easier to find:

  1. In this example from the docs, the ErrorHandlerMiddleware is added without passing the configuration. I think the parameter should be included here.
  2. The Error & Exception Handling section of the docs could benefit from a clearly visible hint that the error config needs to be passed to the middleware to take effect.

Do you want make a PR?

Sure! Do you mean just for updating the docs or also changing the default param for ErrorHandlerMiddleware?

Both. Especially if the current code is wrong