Need a simple example please

Ok so here is the issues:

  1. MonoLog is installed via composer require mongolog/monolog
  2. Slimphp is installed via composer require slim/slim “^3.0”

My index page is:

<?php

require 'vendor/autoload.php';

$app = new Slim\App();
$container = $app->getContainer();

$app->get('/hello/{name}', function ($request, $response, $args) {
    return $response->write("Hello, " . $args['name']);
    return $container;
});

$app->run();
?>

now I don’t understand how the following document integrates monolog
https://www.slimframework.com/docs/tutorial/first-app.html#use-monolog-in-your-application

So if someone could please show me how I simply add monolog logging to my index.php file.

Thank you.

Have you setup a container or configured Monolog anywhere? You might want to have a look at slimphp/Slim-Skeleton and see how it is wired together in that example, and here is the index.php from that example.

In the First Application Walkthrough you referenced, have a look in that index.php. The logger is configured on line #22, then you can see it used on line #39.

In your example, you would likely want something like this (I have not tested it):

<?php

require 'vendor/autoload.php';

$app = new Slim\App();
$container = $app->getContainer();

$container['logger'] = function($c) {
    $logger = new \Monolog\Logger('my_logger');
    $file_handler = new \Monolog\Handler\StreamHandler("../logs/app.log");
    $logger->pushHandler($file_handler);
    return $logger;
};

$app->get('/hello/{name}', function ($request, $response, $args) {
    $this->logger->addInfo("Hello route reached");
    return $response->write("Hello, " . $args['name']);
});

$app->run();

I tried GitHub - slimphp/Slim-Skeleton: Slim Framework 4 Skeleton Application however does not work with cpanel layout. In other words the slim-skeleton example is public_html is inside public yet it needs to be in public_html folder for cpanel to work.

It would be great if they had a version for running it in public_html an not a sub-directory, and yes I know I could just .htaccess this but rather not.

just rename public to public_html (or move the index.php file) and it should work fine, the folder name isn’t hardcoded into Slim anywhere. I run things from a directory called content and don’t need to change anything else.

1 Like