How to setup a monolog logger

Hello I’m a newbie. The documentation on setting up a custom error handler doesn’t make clear how to setup the logger. Can you please me how to setup the logger variable here?

	<?php
	use Psr\Http\Message\ServerRequestInterface;
	use Psr\Log\LoggerInterface;
	use Slim\Factory\AppFactory;
	use Slim\Psr7\Response;

	require __DIR__ . '/../vendor/autoload.php';

	$app = AppFactory::create();

	// Add Routing Middleware
	$app->addRoutingMiddleware();

	// Define Custom Error Handler
	$customErrorHandler = function (
		ServerRequestInterface $request,
		Throwable $exception,
		bool $displayErrorDetails,
		bool $logErrors,
		bool $logErrorDetails,
		?LoggerInterface $logger = null
	) use ($app) {
		$logger->error($exception->getMessage());

		$payload = ['error' => $exception->getMessage()];

		$response = $app->getResponseFactory()->createResponse();
		$response->getBody()->write(
			json_encode($payload, JSON_UNESCAPED_UNICODE)
		);

		return $response;
	};

	// Add Error Middleware
	$errorMiddleware = $app->addErrorMiddleware(true, true, true, $logger);
	$errorMiddleware->setDefaultErrorHandler($customErrorHandler);

	// ...

	$app->run();

For monolog and other dependencies I would recommend installing an IoC container first. Then you can create a container definition (factory) for monolog. In this blog post you can find some information how to integrate monolog into a Slim 4 project: Slim 4 - Logging

4 Likes

Your blog. Great job.

1 Like

Dude your blog is amazing a lot of stuff to learn there

1 Like