Menu

Christian Stryczynski

Freelance software developer. Haskelling at night. Hopefully unconventional. Fan of Dvorak

Log exceptions and errors with PHP Slim 3 using Monolog

$container['logger'] = function (\Slim\Container $c) {
    $settings = $c->get('settings')['logger'];
    $logger = new Monolog\Logger($settings['name']);
    $logger->pushProcessor(new Monolog\Processor\UidProcessor());
    $logger->pushHandler(new Monolog\Handler\StreamHandler($settings['path'], $settings['level']));
    return $logger;
};

$container['errorHandler'] = function (\Slim\Container $container) {
    return function (\Slim\Http\Request $request, \Slim\Http\Response $response, \Exception $exception) use ($container) {
        /** @var \Monolog\Logger $monoLog */
        $monoLog = $container->logger;
        $monoLog->addError($exception->getMessage());
        $monoLog->addError($exception->getTraceAsString());
        $monoLog->addError($exception->getFile());
        $monoLog->addError($exception->getCode());
        $monoLog->addError($exception->getLine());

        $response->getBody()->rewind();
        return $response->withStatus(500)
                        ->withHeader('Content-Type', 'text/html')
                        ->write("An error has occurred. Error details will be present within the application log. Please contact your website administrator.");
    };
};

$container['phpErrorHandler'] = function ($container) {
    return $container['errorHandler'];
};

And then in your settings.php you'll need:

 [
        'rootPath' => __DIR__ . "/..",
        'displayErrorDetails' => true, // set to false in production
        'addContentLengthHeader' => false, // Allow the web server to send the content-length header

        // Renderer settings
        'renderer' => [
            'template_path' => __DIR__ . '/../templates/',
        ],

        // Monolog settings
        'logger' => [
            'name' => 'slim-app',
            'path' => __DIR__ . '/../logs/app.log',
            'level' => \Monolog\Logger::DEBUG,
        ],
    ],
];

Written by Christian Stryczynski on Monday July 17, 2017

Permalink -

« Postgrest is pretty awesome though it does have some limitations - Docker command line functions that will change your life »