1

How i can create my own custom log file with time stamp each time when i log the error

3 Answers 3

3

create Your own Handler

    <?php
    namespace Alshaya\Vistorinfo\Model;

    use Magento\Framework\Filesystem\DriverInterface;
    use Monolog\Formatter\LineFormatter;
    use Monolog\Handler\StreamHandler;
    use Monolog\Logger;

    class Handler extends \Magento\Framework\Logger\Handler\Base
    {
        /**
         * Logging level
         * @var int
         */
        protected $loggerType = Logger::INFO;

        /**
         * File name
         * @var string
         */
        public $fileName = '';
        /**
         * File name
         * @var string
         */
        public $cutomfileName = 'NO_PATH';
        /**
         * @var TimezoneInterface
         */
        protected $_localeDate;

        public function __construct(
            DriverInterface $filesystem,
            \Magento\Framework\Filesystem $corefilesystem,
            \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
            $filePath = null
        ) {
            $this->_localeDate = $localeDate;
            $corefilesystem= $corefilesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR); 
            $logpath = $corefilesystem->getAbsolutePath('log/');


            // Custom log file name for each day because log will be full for optimization 
            $filename = 'vistorInfo_'.Date('Y_m_d').'.log';

            $filepath = $logpath . $filename;
            $this->cutomfileName=$filepath;
            parent::__construct(
                $filesystem,
                $filepath
            );
   //custom message format 
           $this->setFormatter(new LineFormatter('%message%'.PHP_EOL,null,true));

        }
    }

call this handler in any class

public function __construct(
        LoggerInterface $logger,
        \Alshaya\Vistorinfo\Model\Handler $handler,
        \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress $ip,
        \Magento\Framework\UrlInterface $url
    )
    {
        $this->logger = $logger;
        $this->url = $url;
        $this->handler = $handler;
        $this->ip = $ip;
        // Custom log file name for each day because log will be full for optimization 
        $this->logger->setHandlers ( [$this->handler] );
    }

and call

$this->logger->info( "hello world" ); 
1

first create your own handler

<?php
namespace YourNamespace\YourModule\Model;

use Magento\Framework\Filesystem\DriverInterface;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;

class Handler extends \Magento\Framework\Logger\Handler\Base
{
    /**
     * Logging level
     * @var int
     */
    protected $loggerType = Logger::INFO;

    /**
     * File name
     * @var string
     */
    public $fileName = '';
    /**
     * File name
     * @var string
     */
    public $cutomfileName = 'NO_PATH';
    /**
     * @var TimezoneInterface
     */
    protected $_localeDate;

    public function __construct(
        DriverInterface $filesystem,
        \Magento\Framework\Filesystem $corefilesystem,
        \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
        $filePath = null
    ) {
        $this->_localeDate = $localeDate;
        $corefilesystem= $corefilesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR); 
        $logpath = $corefilesystem->getAbsolutePath('log/');

        $filename = 'delivery_martix/import_'. $this->getTimeStamp() .'.log';
        $filepath = $logpath . $filename;
        $this->cutomfileName=$filepath;
        parent::__construct(
            $filesystem,
            $filepath
        );
    }

    public function getCustomFile()
    {
        return  $this->cutomfileName;
    }
    public function getTimeStamp()
    {
        return $this->_localeDate->formatDateTime($this->_localeDate->date(),
        null,
        null,
        null,
        null,
        'Y_M_d_H_mm_ss'
        );
    }
}

and in your main file

<?php

namespace YourNamespace\YourModule\Controller\Adminhtml\Import;

class Save
{   
    protected $_logger;
    protected $_handler;

    public function __construct(
        \Psr\Log\LoggerInterface $logger,
        \YourNamespace\YourModule\Model\Handler $handler,

    ) {
        parent::__construct($context);
        $this->_logger = $logger;
        $this->_handler = $handler;

    }



     public function execute()
    {

            $this->messageManager->addError(
                                __('Few Items are not inserted, Please check log.'. $this->_handler->getCustomFile())
                            );
            $this->_logger->critical('Duplicate Entry Not Allowed, this  Combination already exists',$data);
    }



}
1

you can also log in below way specially you need log with log file AS like order increment id

public function __construct(
        \Magento\Framework\App\Action\Context $context, // based on class thi will change
        \Magento\Framework\Filesystem $filesystem
    ){
       $this->_logDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR);
        parent::__construct($context);
    }


   public function execute()
{
    $logpath = $this->_logDirectory->getAbsolutePath('log/orders/');    
    if(!$this->_logDirectory->isExist($this->_logDirectory->getRelativePath('log/orders/'))){
         //if the folder not exit it will create one dummy file 
        $jsonpath =  $this->_logDirectory->getRelativePath('log/orders/');
        $filePath = $jsonpath.'test'.'.log';
        $this->_logDirectory->writeFile($filePath, 'test file created');
    }                   

    $filename = 'import_.'$order->getIncrementId()'.log';
    $filepath = $logpath . $filename;

    $writer = new \Zend\Log\Writer\Stream($filepath);
    $logger = new \Zend\Log\Logger();
    $logger->addWriter($writer);
    $msg='rrr';
    $logger->info($msg);
    $logger->info(print_r($order->getData(),1)); 

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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