2

I have an instance of a logger in my PHP script that I use. I instantiate it like this:

$logger = $om->get("Psr\Log\LoggerInterface");

I can log text like this:

$logger->debug("caruk");

but it is always logged in the file var/log/debug.log . I want to log error messages in my own custom file customfile.log . How can I do this?

0

In case you want to define your own logger using monolog you can follow https://magento.stackexchange.com/a/75954/9169.

If you want to change default debug log file you can rewrite Magento\Framework\Logger\Handler\Debug in your custom module and change filename there.

Module's di.xml code

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Framework\Logger\Handler\Debug" type="Amit\Helloworld\Model\CustomLogger" />
</config>

CustomLogger.php code

<?php

namespace Amit\Helloworld\Model;
use Monolog\Logger;

class CustomLogger extends \Magento\Framework\Logger\Handler\Debug
{
    /**
     * @var string
     */
    protected $fileName = '/var/log/customfile.log';

    /**
     * @var int
     */
    protected $loggerType = Logger::DEBUG;
}

Now your debug logs will be logged in customfile.log .

Example:

<?php

namespace Amit\Helloworld\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
{
    // other code
    protected $logger;

    public function __construct(
        // other code
        \Psr\Log\LoggerInterface $logger
    ) {
        // other code
        $this->logger = $logger;
        parent::__construct($context);
    }

    public function execute()
    {
        $this->logger->debug('test');
        // other code
    }

}

Similarly you can overwrite other default log files exception.log and system.log using preference. Other log files are defined in \Magento\Framework\Logger\Handler\Exception, \Magento\Framework\Logger\Handler\System

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.