Search code examples
symfonyloggingerror-logging

How to do logging in my app using symfony's Depenency Injection module?


I've read the current docs on Symfony integration with Monolog, but all it says is to run:

composer require logger which throws an error "package not found". (https://symfony.com/doc/current/logging.html#installation)

I'm using these components:

"require": {
    "symfony/dependency-injection": "~3.0",
    "symfony/yaml": "~3.0",
    "symfony/config": "~3.0",
    "symfony/console": "~3.0",
    "symfony/validator": "~3.0",
    "symfony/event-dispatcher": "~3.0",
    "guzzlehttp/guzzle": "~6.0",
    "gedex/janrain-api": "~0.1"
},
"require-dev": {
    "phpunit/phpunit": "~5.7",
    "friendsofphp/php-cs-fixer": "~2.0",
    "squizlabs/php_codesniffer": "~3.0",
    "symfony/var-dumper": "~3.0"
},

I want to do logging using dependency injection and config module.

EDIT: it is not a web application. It is a library that provides abstraction and exposes internal API, and I want to make it possible to log what is going on in the methods.


Solution

  • Looking at your composer.json, you seem to be on Symfony 3.x still. The docs for your version are at https://symfony.com/doc/3.4/logging.html.

    The composer require logger is a shortcut which works with Flex. Flex is default on Symfony 4, but optional for Symfony 3. If you’ve upgraded from an earlier version, I assume that you currently don’t use Flex. In this case, you can install monolog and its Symfony integration by running:

    composer require "symfony/monolog-bundle": "^3.1.0"
    

    Then you must add the monolog bundle to your AppKernel:

        $bundles = [
            …
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            …
        ];
    

    Then you can inject the @logger service into your own services or call it in your controllers.