Logging is a critical part of Magento 2 development. It helps developers track issues, debug functionality, and monitor custom processes. While Magento provides system and exception logs by default, sometimes you need your own custom log file for module‑specific or business‑specific events.
Why Custom Logs?
- Keep your module’s logs separate from Magento’s core logs
- Quickly identify issues related to your custom functionality
- Track specific events (e.g., product sync, API calls, payment gateway responses)
- Provide an audit trail for business processes
Magento Version Specific Code
For Magento 2.4.2 and Before:
$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/custom.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info('Custom message');
$logger->info(print_r($object->getData(), true));
For Magento 2.4.2 and After:
$writer = new \Laminas\Log\Writer\Stream(BP . '/var/log/custom.log');
$logger = new \Laminas\Log\Logger();
$logger->addWriter($writer);
$logger->info('text message');
$logger->info(print_r($object->getData(), true));
For Magento 2.4.3:
$writer = new \Zend_Log_Writer_Stream(BP . '/var/log/custom.log');
$logger = new \Zend_Log();
$logger->addWriter($writer);
$logger->info('text message');
$logger->info(print_r($object->getData(), true));
Best Practices
- Use meaningful log filenames (e.g.,
custom.log,sync.log,payment.log) - Apply log levels properly:
info,debug,error - Rotate or clear logs regularly to avoid large files
- Never log sensitive data like passwords or tokens
Step-by-Step Tutorial
- Create Logger: Instantiate the correct logger class based on your Magento version.
- Define Log File: Point to
/var/log/custom.logor another meaningful filename. - Write Messages: Use
info(),debug(), orerror()depending on the context. - Test: Trigger your code and check the log file in
var/logto confirm entries.
When to Use Custom Logs
- Tracking API integrations (ERP, payment gateways, etc.)
- Debugging custom module functionality
- Monitoring cron jobs or scheduled tasks
- Capturing business‑specific events for auditing
Troubleshooting
- If your log file doesn’t appear, check file permissions for the
var/logdirectory. - Ensure your code is actually executed (e.g., place a test
$logger->info('Hello World');). - Clear cache after adding new code to make sure Magento picks up changes.
Conclusion
Depending on your Magento version, the logging classes differ slightly. By using the correct snippet above, you can generate custom logs safely and effectively. This ensures better visibility into your module’s behavior and makes debugging much easier. Custom logs are a simple but powerful tool to keep your Magento store stable and transparent.
0 comments:
Post a Comment