This page looks best with JavaScript enabled

Monolog in symfony3.4

 ·  🎃 kr0m

When a web application fails, it is essential to be able to log certain variables to be able to debug the code. In this article, I will explain how to do it with symfony3.4 and monolog, a logging library widely used among PHP programmers.

If we don’t have symfony and composer installed, we proceed to do so:

curl -LsS https://symfony.com/installer -o /usr/local/bin/symfony
chmod a+x /usr/local/bin/symfony
curl -sS https://getcomposer.org/installer -o composer-setup.php
php composer-setup.php –install-dir=/usr/local/bin –filename=composer

We will follow the basic luckyNumber example from the symfony website.

We create the project:

symfony new luckyNumber 3.4

We create the controller that will generate the lucky number and log it in the log file:

cd luckyNumber
vi src/AppBundle/Controller/LuckyController.php

<?php
// src/AppBundle/Controller/LuckyController.php
namespace AppBundle\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

class LuckyController extends Controller
{
    /**
     * @Route("/lucky/number")
     */
    public function numberAction()
    {
    
        $logger = new Logger('debugLogger');
        $logDir = $this->container->get('kernel')->getLogDir();
        $logger->pushHandler(new StreamHandler($logDir.'/debugLog.log', Logger::NOTICE));
        $logger->notice('debugLogger is now ready');

        $number = random_int(0, 100);
        $logger->notice(sprintf('luckyNumber: %s', $number));

        return new Response(
            '<html><body>Lucky number: '.$number.'</body></html>'
        );
    }
}

We start the web server integrated in symfony:

php bin/console server:run

We check that the controller works correctly by generating the lucky number:
http://localhost:8000/lucky/number

We can see how we log the lucky number in our log file:

tail -f var/logs/debugLog.log

[2019-08-02 17:26:48] debugLogger.NOTICE: debugLogger is now ready [] []
[2019-08-02 17:26:48] debugLogger.NOTICE: luckyNumber: 66 [] []
If you liked the article, you can treat me to a RedBull here