Magento 2 – Cron Job Not Logging Product Value in Log File [SOLVED]

croncrontabcustommagento2product

I'm creating new Cron Job.

app\code\Custom\Module\Cron\MyTask.php

namespace Custom\Module\Cron;

class MyTask {

    protected $_logger;

    public function __construct(\Psr\Log\LoggerInterface $logger) {
        $this->_logger = $logger;
    }

    public function execute() {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
        $productCollection->addAttributeToFilter('price', array('gt' => 500));
        $productCollection->load();

        foreach ($productCollection as $products) {
            $this->_logger->debug($products->getName());
            $this->_logger->info($products->getName());
        }
        return $this;
    }
}

When I'm executing through command it's not logging Product Name in var/log/debug.log or var/log/system.log

Some time it will log, sometime don't

Best Answer

It works fine now.

http://devdocs.magento.com/guides/v2.0/config-guide/cli/config-cli-subcommands-cron.html

it's saying

You must run cron twice: the first time to discover tasks to run and the second time to run the tasks themselves.

So i'm running commands in below order

php bin/magento cache:flush
php bin/magento setup:cron:run
php bin/magento cron:run --group="my_cronjob" // Group Id
php bin/magento cron:run --group="my_cronjob" // Group Id

It's logging value now in var/log/system.log