delet or archive in magento 2

We recently had a requirement to archive or delete API logs when we were developing Magento 2 to JDA integration. We were logging each and every API call to the custom log table in Magento 2 and within 2 weeks we had over 100k records. Without having an archiving strategy this table would have been massive with millions of records within 3 months for sure. Our dev team created a cron job to delete records which were older than certain number of days which can be easily configured from admin.

We couldn’t find anything similar on Google so we thought it would be good to create another short and sweet post for our Magento 2 users.

Here is the main class which can help you delete or archive records from your custom table which are older than x number of days

/** * Cron job to run jda logs archive * * @category Scommerce * @package Scommerce_JdaConnector * @author Scommerce Core Team * */ namespace ScommerceJdaConnectorCron; class LogsArchive
{ /** * @var ScommerceJdaConnectorHelperData */ protected $_helper; /** * @var MagentoFrameworkAppResourceConnection */ protected $_resourceConnecton; /** * @param ScommerceJdaConnectorHelperData $helper * @param MagentoFrameworkAppResourceConnection $resourceConnection */ public function __construct( ScommerceJdaConnectorHelperData $helper, MagentoFrameworkAppResourceConnection $resourceConnection ) { $this->_helper = $helper; $this->_resourceConnecton = $resourceConnection; } public function execute() { if ($this->_helper->getLogsArchiveEnabled()){ $connection = $this->_resourceConnecton->getConnection(); $jdaLogTable = $this->_resourceConnecton->getTableName('jda_connector_log'); $connection->delete( $jdaLogTable, "created_at < date_sub(CURDATE(), INTERVAL ".$this->_helper->getLogsArchiveNumberOfDays()." Day)" ); } return; }
} 

That’s it, Hope this article helped you in some way. Please leave us your comment and let us know what do you think? Thanks.

Similar Posts