To set up file-based logging in Symfony, you'll need to follow these steps:
composer require symfony/monolog-bundle
config.yml
file and add the following configuration to enable file-based logging with Monolog:monolog:
handlers:
file:
type: stream
path: "%kernel.logs_dir%/%kernel.environment%.log"
level: debug
This configuration sets up a file handler that logs messages in the app/logs/
directory with the environment name (e.g., dev.log
for the dev environment).
services.yml
file like so:services:
_defaults:
autowire: true
Psr\Log\LoggerInterface: '@monolog.logger'
This configuration sets up the LoggerInterface
to use the Monolog logger service.
LoggerInterface
service into your classes and using it to log messages as needed. For example:// In a controller or service
use Psr\Log\LoggerInterface;
class MyController
{
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function index()
{
$this->logger->info('This is an info message');
$this->logger->error('An error occurred');
// Additional logging statements...
}
}
With these steps, you have successfully set up file-based logging in Symfony using Monolog. You can now start logging messages to files in your application for debugging and monitoring purposes.