Programmatically: How to use Magento's custom logging system for custom logging and debugging
Step 1: Create a custom log writer
In your Magento module, create a new file Logger.php in the etc directory:
// app/code/local/MyCompany/MyModule/etc/Logger.php
namespace MyCompany\MyModule\Logger;
class Logger
{
private $logger;
public function __construct(\Magento\Framework\App\LoggerInterface $logger)
{
$this->logger = $logger;
}
public function log($message, $level = \Monolog\Logger::INFO)
{
$this->logger->log($level, $message);
}
}
Step 2: Use the custom logger in your module
Now, let's use this logger in one of your module's controllers or models. For example, let's create a IndexController in the MyCompany/MyModule module:
// app/code/local/MyCompany/MyModule/Controller/IndexController.php
namespace MyCompany\MyModule\Controller;
class IndexController extends \Magento\Framework\App\Action\Action
{
private $logger;
public function __construct(
\MyCompany\MyModule\Logger\Logger $logger,
\Magento\Framework\App\Action\Context $context
) {
parent::__construct($context);
$this->logger = $logger;
}
public function execute()
{
$this->logger->log('Custom log message from IndexController');
// ... rest of your code ...
}
}
Step 3: Configure the logger
To configure the logger, you need to add a logging configuration to your Magento configuration file (app/etc/env.php):
return [
// ... other settings ...
'log' => [
'enabled' => true,
'type' => 'stream',
'handlers' => [
'default' => [
'logger' => \Monolog\Logger::DEBUG,
'path' => 'var/log/magento.log',
' permissions' => 0644,
],
],
],
];
Step 4: Run the application and check the logs
Run your Magento application and trigger the IndexController action. You should see a log message in the magento.log file:
[2023-02-20 14:30:00] DEBUG (7): Custom log message from IndexController