How to use the Symfony monolog component to log messages?

by elise_daugherty , in category: PHP Frameworks , 2 years ago

How to use the Symfony monolog component to log messages?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by giovanny.lueilwitz , 2 years ago

@elise_daugherty 

To use the Symfony Monolog component to log messages, you need to follow these steps:

  1. Install the Monolog component using Composer by running the following command:
1
composer require symfony/monolog-bundle


  1. Configure the Monolog component by adding the following lines to the config/packages/monolog.yaml file:
1
2
3
4
5
6
monolog:
    handlers:
        main:
            type: stream
            path: "%kernel.logs_dir%/%kernel.environment%.log"
            level: debug


This configuration sets up a stream handler that writes log messages to a file in the logs directory.

  1. In your PHP code, use the LoggerInterface interface to log messages. For example, to log a message with the debug level, you can use the following code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
use PsrLogLoggerInterface;

class MyClass {
    private $logger;

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

    public function myMethod() {
        // ...
        $this->logger->debug('This is a debug message.');
        // ...
    }
}


This code injects the LoggerInterface into the MyClass constructor, and then uses it to log a debug message.


Note that there are other types of Monolog handlers you can use, such as email, slack, and syslog. You can find more information about Monolog in the Symfony documentation: https://symfony.com/doc/current/logging.html