Strong Like Bull
Strong Like Bull

Reputation: 11317

How to log simple debug messages to a file in Symfony?

I want to be able to write debug messages to a log file. What is the proper way of doing this? There is absolutely no documentation that i can find out there. I know the Monolog bundle is mentioned but it is not writing anything. Please suggest.

Upvotes: 6

Views: 14491

Answers (2)

VladTit
VladTit

Reputation: 11

add 2 use classes

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

then in function simple use this

$log = new Logger('shipment');
$log->pushHandler(new StreamHandler('var/log/fileName.log', Logger::WARNING));

// add records to the log
$log->addWarning('qty is 0', ['data' => 3]);

Upvotes: 1

Vitalii Zurian
Vitalii Zurian

Reputation: 17986

Assuming that you are using MonologBundle that is included by default

Step 1

Define your handler service and pass directory/file there

your.log.handler:
    class: %monolog.handler.stream.class%
    arguments: [ %kernel.logs_dir%/%kernel.environment%.yourFileName.log ]

Class parameter %monolog.handler.stream.class% is defined in MonologBundle and it is Monolog\Handler\StreamHandler class

Step 2

Define your logger service and inject your handler there

your.logger:
    class: %monolog.logger.class%
    arguments: [ nameOfLoggingChannel ]
    calls: [ [pushHandler, [@your.log.handler]] ]

Parameter %monolog.logger.class% is also defined in MonologBundle and represents the Symfony\Bridge\Monolog\Logger class

Step 3

Inject it to your controller in and use as normal logger

$logger = $this->get('your.logger');
$logger->warn('We are using custom logger');

Check your app/logs/dev.yourFileName.log

Upvotes: 14

Related Questions