How to create basic Error logging in Mezzio v3

Sorry if this is a too simple thing to ask for here. but i am stuck here and flooded with all the information available , where I am only trying to write a basic error logging mechanism that logs all my PHP errors and exception to a log file as of now i am using Zend server and Z-ray is enabled which is the only way for displaying the errors on the Z-ray bar.

Also throw me some light on Errorlistener and Delegators . Can it be used to log error, tried to implement it but no luck.

LoggingErrorListener.php

namespace App\ErrorListner;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerInterface;
use Throwable;

class LoggingErrorListener 
{

    private const LOG_STRING = '{status} [{method}] {uri}: {error}';
    private $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function __invoke(
        Throwable $error,
        ServerRequestInterface $request,
        ResponseInterface $response
    ) {

            $this->logger->error(sprintf(
                self::LOG_FORMAT,
                $response->getStatusCode(),
                $request->getMethod(),
                (string) $request->getUri(),
                $error->getMessage()
            ));
        }
}

LoggingErrorListenerelegator.php

namespace App\ErrorListner;

use Laminas\Stratigility\Middleware\ErrorHandler;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;

class LoggingErrorListenerDelegator
{
    public function __invoke(ContainerInterface $container,string $serviceName,callable $callback): ErrorHandler
    {
        $errorHandler = $callback();
        $errorHandler->attachListener(
        new LoggingErrorListener($container->get(LoggerInterface::class))
        );
        return $errorHandler;
    }
}

ConfigProvider.php i have added this

'delegators' => [
			ErrorHandler::class => [
				ErrorListner\LoggingErrorListenerDelegator::class,
			],
		],

And how to test if the delegator is working. because right now i think it is not getting detected.

Not sure if this is the only missing piece, but you might be missing the following in pipeline.php:

<?php

// use statements here ...

return function (Application $app, MiddlewareFactory $factory, ContainerInterface $container): void {
    /** @var ErrorHandler $errorHandler */
    $errorHandler = $container->get(ErrorHandler::class);
    $errorHandler->attachListener(function (Throwable $throwable, ServerRequestInterface $request, ResponseInterface $response): void {
        _log()->err($throwable->getMessage() . "\n" . $throwable->getTraceAsString());
    });

    // The error handler should be the first (most outer) middleware to catch
    // all Exceptions.
    $app->pipe($errorHandler);

    // all other stuff here ....
};

To test it, you should be able to throw any exception in one of your middleware.

1 Like

the better way I found to build my own log, was build a module that handle it with laminas-log,
in my case I build a middleware to log all incoming request, and a Model to write logs when need to.
if you need, ask for my code.