Magento Log Files
Log File Locations
# Main log directory
var/log/
# Log files:
var/log/system.log # General system events
var/log/exception.log # Uncaught exceptions
var/log/debug.log # Debug messages (developer mode)
var/log/payment.log # Payment gateway logs
var/log/cron.log # Cron job logs
var/log/setup.log # Installation/update logs
var/log/mail.log # Email sending logs
var/log/cron_schedule.log # Cron scheduling logs
Log Configuration
// app/etc/env.php
return [
'log' => [
'file' => [
'level' => \Monolog\Logger::DEBUG,
'path' => 'var/log/',
],
'syslog' => [
'ident' => 'magento',
'facility' => LOG_USER,
],
],
];
Log Levels
use Psr\Log\LoggerInterface;
class ProductProcessor
{
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function process($product)
{
$this->logger->debug('Processing product', ['sku' => $product->getSku()]);
try {
// Process product
$this->logger->info('Product processed successfully', ['id' => $product->getId()]);
} catch (\Exception $e) {
$this->logger->error('Product processing failed', [
'sku' => $product->getSku(),
'error' => $e->getMessage(),
]);
}
}
}
Key Points
- system.log records general operations
- exception.log captures uncaught exceptions
- debug.log provides detailed debug info (dev mode)
- Log levels: DEBUG, INFO, NOTICE, WARNING, ERROR, CRITICAL
System and Exception Logs
System Log Usage
use Magento\Framework\Logger\Monolog;
class SystemLogger
{
private $logger;
public function __construct(Monolog $logger)
{
$this->logger = $logger;
}
public function logOrder($orderId, $status)
{
$this->logger->info('Order status updated', [
'order_id' => $orderId,
'status' => $status,
'timestamp' => date('Y-m-d H:i:s'),
]);
}
public function logInventory($sku, $qty)
{
$this->logger->warning('Low inventory', [
'sku' => $sku,
'quantity' => $qty,
]);
}
}
Exception Logging
// Custom exception handler
set_exception_handler(function($exception) {
$logger = Bootstrap::getObjectManager()->get(
\Psr\Log\LoggerInterface::class
);
$logger->critical('Uncaught exception', [
'message' => $exception->getMessage(),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'trace' => $exception->getTraceAsString(),
]);
});
// Log specific exception types
try {
$this->processOrder($order);
} catch (\Magento\Framework\Exception\LocalizedException $e) {
$this->logger->warning('Localized error: ' . $e->getMessage());
throw $e;
} catch (\Exception $e) {
$this->logger->critical('Unexpected error', [
'exception' => $e,
]);
throw $e;
}
Key Points
- Use appropriate log levels for different events
- Include contextual data in log entries
- Don't log sensitive data (passwords, tokens)
- Monitor exception.log for recurring issues
Custom Logging
Custom Logger Channel
// app/code/Vendor/Module/Logger/Handler.php
namespace Vendor\Module\Logger;
use Magento\Framework\Logger\Handler\Base;
class Handler extends Base
{
protected $fileName = '/var/log/vendor_module.log';
protected $loggerType = \Monolog\Logger::INFO;
}
// app/code/Vendor/Module/Logger/Handler.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Framework\Logger\Monolog">
<arguments>
<argument name="handlers" xsi:type="array">
<item name="debug" xsi:type="object">Vendor\Module\Logger\Handler</item>
</argument>
</arguments>
</type>
</config>
Database Logging
namespace Vendor\Module\Logger;
class DatabaseLogger
{
private $resource;
public function __construct(\Magento\Framework\App\ResourceConnection $resource)
{
$this->resource = $resource;
}
public function log($level, $message, array $context = [])
{
$connection = $this->resource->getConnection();
$tableName = $this->resource->getTableName('vendor_module_log');
$connection->insert($tableName, [
'level' => $level,
'message' => $message,
'context' => json_encode($context),
'created_at' => date('Y-m-d H:i:s'),
]);
}
}
Key Points
- Create custom handlers for module-specific logs
- Separate logs by module or functionality
- Consider database logging for queryable data
- Implement log rotation to manage disk space
Log Rotation
Logrotate Configuration
# /etc/logrotate.d/magento
/var/www/magento/var/log/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0644 www-data www-data
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] && kill -USR1 $(cat /var/run/nginx.pid)
endscript
}
Magento Log Cleanup
# Clean old log files
bin/magento log:clean
# Clean specific log types
bin/magento log:clean --log-types=system,exception
# Cron job for automatic cleanup
# bin/magento cron:run (runs log cleanup daily)
Custom Log Cleanup
use Magento\Framework\Log\Cleaner;
class LogCleaner
{
private $cleaner;
public function cleanOldLogs($daysToKeep = 30)
{
$ cutoff = time() - ($daysToKeep * 86400);
$logFiles = glob('var/log/*.log');
foreach ($logFiles as $file) {
if (filemtime($file) < $cutoff) {
unlink($file);
}
}
}
}
Key Points
- Configure logrotate for automatic rotation
- Set appropriate retention periods
- Compress old log files to save space
- Clean logs regularly to prevent disk filling
Practice Problems
0 / 1 solved
Custom Logger Module
Create a custom logging module that writes to a separate log file for order processing.
Solution
<?php
namespace Vendor\OrderLog\Logger;
use Magento\Framework\Logger\Handler\Base;
class OrderHandler extends Base
{
protected $fileName = '/var/log/order_processing.log';
protected $loggerType = \Monolog\Logger::INFO;
}
// di.xml
<config>
<type name="Magento\Framework\Logger\Monolog">
<arguments>
<argument name="handlers" xsi:type="array">
<item name="order" xsi:type="object">Vendor\OrderLog\Logger\OrderHandler</item>
</argument>
</arguments>
</type>
</config>
// Usage in OrderProcessor
public function process($order)
{
$this->logger->info('Processing order', [
'order_id' => $order->getIncrementId(),
'total' => $order->getGrandTotal(),
]);
} Quiz
1. Where does Magento store exception logs?
2. What log level is most verbose?
3. What command cleans Magento logs?
4. Why use log rotation?
Flashcards
Question
exception.log purpose?
Click to reveal answer
Answer
Records uncaught exceptions and errors
Question
Most verbose log level?
Click to reveal answer
Answer
DEBUG - shows detailed debug info
Question
Clean logs command?
Click to reveal answer
Answer
bin/magento log:clean
Question
Log rotation benefit?
Click to reveal answer
Answer
Prevents disk space issues with old logs
Revision Notes
Key Takeaways
- 1. Magento logs are in var/log/ directory
- 2. exception.log captures uncaught exceptions
- 3. Use appropriate log levels (DEBUG, INFO, ERROR)
- 4. Configure log rotation to manage disk space
Interview Tips
- • Explain different log files and their purposes
- • Discuss logging best practices
- • Know how to configure log levels
Cheat Sheet
Magento Logs
- system.log: general events
- exception.log: uncaught exceptions
- debug.log: debug info (dev mode)
- Levels: DEBUG, INFO, WARNING, ERROR
- Clean: bin/magento log:clean