When you build a custom module, an integration or a cron job in Magento 2, writing everything to var/log/system.log or var/log/debug.log quickly becomes a mess. Your messages get buried under hundreds of lines from core modules and third-party extensions, and finding the one error you care about takes forever. The clean solution is to write logs to a custom file in Magento 2, for example var/log/magentip_sync.log.
In this tutorial, we will learn how to create a dedicated log file in Magento 2.4.x using virtual types in di.xml (no extra PHP classes needed), how to inject the custom logger into your class, and how to fix the most common problems when the log file is not created.
Previously, I published a tutorial on how to create a custom Helloworld module in Magento 2. If you have never created a module before, read that guide first, because we will add the logger to a small module.
Contents
How logging works in Magento 2
Magento 2 follows the PSR-3 logging standard. Whenever you inject Psr\Log\LoggerInterface into a class, Magento gives you an instance of Magento\Framework\Logger\Monolog, which is built on the Monolog library (Monolog 3 in Magento 2.4.8). A Monolog logger is a “channel” with a list of handlers, and each handler decides where the message goes.
By default, the main logger has handlers that write to:
var/log/system.log– info level and abovevar/log/debug.log– debug messages (only when debug logging is enabled)var/log/exception.log– exceptions
To log to a custom file, we simply create a new handler that points to another file name, and a new logger that uses only that handler. Both can be virtual types, so we don’t need to write any PHP class for them.
Step 1: Create a small module
In this example, the vendor is Magentip and the module is CustomLog. Create the folder app/code/Magentip/CustomLog with these two files.
app/code/Magentip/CustomLog/registration.php:
<?php
use Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(
ComponentRegistrar::MODULE,
'Magentip_CustomLog',
__DIR__
);
app/code/Magentip/CustomLog/etc/module.xml:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Magentip_CustomLog"/>
</config>
If you already have your own module, skip this step and add the configuration below to that module instead.
Step 2: Declare the custom log file in di.xml
This is the most important step. Create app/code/Magentip/CustomLog/etc/di.xml:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<!-- 1. Handler: writes to var/log/magentip_sync.log -->
<virtualType name="Magentip\CustomLog\Logger\Handler"
type="Magento\Framework\Logger\Handler\Base">
<arguments>
<argument name="fileName" xsi:type="string">/var/log/magentip_sync.log</argument>
</arguments>
</virtualType>
<!-- 2. Logger channel that only uses our handler -->
<virtualType name="Magentip\CustomLog\Logger\Logger"
type="Magento\Framework\Logger\Monolog">
<arguments>
<argument name="name" xsi:type="string">magentipSync</argument>
<argument name="handlers" xsi:type="array">
<item name="system" xsi:type="object">Magentip\CustomLog\Logger\Handler</item>
</argument>
</arguments>
</virtualType>
<!-- 3. Inject the custom logger into your class -->
<type name="Magentip\CustomLog\Model\OrderSync">
<arguments>
<argument name="logger" xsi:type="object">Magentip\CustomLog\Logger\Logger</argument>
</arguments>
</type>
</config>
A few notes about this configuration:
fileNameis relative to the Magento root folder, so/var/log/magentip_sync.logends up in<magento_root>/var/log/magentip_sync.log. Magento creates the folder if it does not exist.Magento\Framework\Logger\Handler\Baselogs everything from theDEBUGlevel up, sodebug(),info(),warning()anderror()messages all go to the file.nameis the channel name. It appears in each log line (magentipSync.INFO), which makes it easy togrep.- The
<type>node tells Magento to pass our virtual logger to the$loggerconstructor argument ofOrderSync. Other classes keep using the default logger.
Step 3: Use the logger in your class
Now create the class that writes the logs, app/code/Magentip/CustomLog/Model/OrderSync.php. Notice that we still type-hint the standard Psr\Log\LoggerInterface. The constructor argument must be named $logger because that is the name we used in di.xml.
<?php
declare(strict_types=1);
namespace Magentip\CustomLog\Model;
use Psr\Log\LoggerInterface;
class OrderSync
{
public function __construct(
private readonly LoggerInterface $logger
) {
}
public function execute(int $orderId): void
{
$this->logger->info('Order sync started', ['order_id' => $orderId]);
try {
// ... call your external API here ...
$this->logger->debug('API response', ['status' => 200]);
} catch (\Exception $e) {
$this->logger->error('Sync failed', [
'order_id' => $orderId,
'exception' => $e->getMessage()
]);
}
}
}
The second parameter (the context array) is optional, but I recommend using it instead of concatenating values into the message. Monolog prints it as JSON at the end of the line, so you can search the log by order ID later.
You can inject the same virtual logger into as many classes as you want (observers, plugins, cron jobs, controllers): just add another <type> node in di.xml for each class.
Step 4: Enable the module, compile and check the log file
Run the following commands from the Magento root folder:
php bin/magento module:enable Magentip_CustomLog php bin/magento setup:upgrade php bin/magento setup:di:compile php bin/magento cache:flush
You must run setup:di:compile in production mode every time you change di.xml, otherwise Magento keeps using the old generated configuration. In developer mode the cache flush is usually enough. If you are not sure which mode your store runs in, see how to enable or disable Magento 2 developer mode.
Now trigger your code (run the cron, place an order, call the controller…) and check the log:
ls -l var/log/ tail -f var/log/magentip_sync.log
You should see lines like this:
[2026-12-04T02:15:22+00:00] magentipSync.INFO: Order sync started {"order_id":100} []
[2026-12-04T02:15:23+00:00] magentipSync.DEBUG: API response {"status":200} []
Alternative: a custom handler class
If you prefer real PHP classes (for example to reuse the handler in several modules or to change the minimum log level), extend the core handler instead of using a virtual type:
<?php
declare(strict_types=1);
namespace Magentip\CustomLog\Logger;
use Magento\Framework\Logger\Handler\Base;
use Monolog\Logger;
class Handler extends Base
{
/** @var string */
protected $fileName = '/var/log/magentip_sync.log';
/** @var int */
protected $loggerType = Logger::INFO; // skip DEBUG messages
}
Then remove the first virtualType from di.xml and keep the logger virtual type pointing to Magentip\CustomLog\Logger\Handler, which is now a real class.
Quick one-off logging while debugging
Sometimes you just need to dump a value once while debugging and you don’t want to touch di.xml. You can create a Monolog logger on the fly:
$logger = new \Monolog\Logger('tmp');
$logger->pushHandler(new \Monolog\Handler\StreamHandler(BP . '/var/log/tmp_debug.log'));
$logger->info('Quote data', ['quote_id' => $quote->getId()]);
Only use this for temporary debugging and remove it before you deploy. Old snippets on the internet that use \Zend\Log\Writer\Stream or \Zend_Log don’t work in Magento 2.4, because the Zend Framework libraries were replaced by Laminas.
Common errors
The custom log file is not created
- Nothing has been logged yet. Monolog creates the file on the first write, so make sure your code actually runs.
- You didn’t run
setup:di:compileafter editingdi.xmlin production mode, so the old configuration ingenerated/is still used. - The web server user can’t write to
var/log. Fix the ownership, for examplechown -R www-data:www-data var/(replacewww-datawith your web server user).
Messages still go to system.log
This means Magento injected the default logger. Check that the class name in the <type name="..."> node matches your class exactly (including the namespace), and that the constructor parameter is called $logger, the same as <argument name="logger">. If you add a plugin to the class, the type name must still be the original class, not the interceptor.
Permission denied or “failed to open stream”
If you see The stream or file ".../var/log/magentip_sync.log" could not be opened, the file was probably created by root when you ran a CLI command, and now the web server can’t write to it. Delete the file or fix its owner. This kind of permission problem is also a frequent cause of the Magento 2 500 internal server error.
Log files grow too large
Custom logs are not rotated automatically. Set up logrotate for var/log/*.log on your server, and avoid logging full API payloads with info() in production.
For more background on how logging is designed in Magento, read Adobe’s official documentation on custom logging. You can also find all the commands used in this tutorial in my Magento 2 command list cheat sheet.
Wrapping up
That’s it! Now you know how to write logs to a custom file in Magento 2: declare a handler and a logger with virtual types in di.xml, inject the logger into your class, compile, and watch var/log. Having one log file per integration makes debugging much faster and keeps system.log readable.
If you have any questions or the log file still doesn’t show up on your store, leave a comment below with your Magento version and I will help you.





