Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

Example below has two different ways of handling logs. Native @logger service logs all messages to dev.log file of "main" channel and our custom MonologService service logs all messages to country.log file of "country" channel.


Custom monolog service


namespace Football\FrontendBundle\Service;

use Symfony\Component\HttpKernel\Log\LoggerInterface;

class MonologService
{
private $logger;

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

public function add($level, $message)
{
$this->logger->$level($message);
}
}

Monolog service definition


services:
football_frontend.logger.monolog:
class: Football\FrontendBundle\Service\MonologService
arguments: [@logger]
tags:
- { name: monolog.logger, channel: country }

Config.yml


monolog:
channels: ["country"]
handlers:
country:
type: stream
path: %kernel.logs_dir%/%kernel.environment%_country.log
channels: ["country"] # Only handle country channel logs
main:
type: stream
path: "%kernel.logs_dir%/%kernel.environment%.log"
level: debug
channels: ["!country"] # Handle all channel logs but country

Controller.yml


services:
football_frontend.controller.country:
class: Football\FrontendBundle\Controller\CountryController
arguments:
- @football_frontend.logger.monolog
- @logger

Controller


/**
* @Route("/country", service="football_frontend.controller.country")
*/
class CountryController extends Controller
{
private $monologService;
private $logger;

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

public function listAction()
{
$this->monologService->add('warning', 'message'); // This would use "country" channel
$this->logger->warning('message'); // This would use "main" channel
}
}