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?

  • This looks like a duplicate question, see this answer for how to create a custom log file: http://magento.stackexchange.com/questions/75935/logging-to-a-custom-file-in-magento-2 –  Mar 22 '17 at 18:11

2 Answers2

1

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

amitshree
  • 7,006
  • 12
  • 63
  • 116
0

Please try below if you do not want to create a module:

$writer = new \Zend_Log_Writer_Stream(BP .'/var/log/customfile.log');
$logger = new \Zend_Log();
$logger->addWriter($writer);
$logger->info('hello log');