Does one of your Magento 2 caches seem to clear itself all the time? A Call Stack can help you find the cause. With custom extensions, it can show exactly which code triggered a cache cleanup.
For temporary analysis, you can create a plugin for TypeList::cleanType() and Cache Manager::flush() . Register it in etc/di.xml:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\Framework\App\Cache\TypeList"> <plugin name="cache_trace_type_list" type="Vendor\Module\Plugin\CacheTrace"/> </type> <type name="Magento\Framework\App\Cache\Manager"> <plugin name="cache_trace_manager" type="Vendor\Module\Plugin\CacheTrace"/> </type> </config> |
The plugin logs the affected cache type and call stack:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
<?php declare(strict_types=1); namespace Vendor\Module\Plugin; use Magento\Framework\App\Cache\Manager; use Magento\Framework\App\Cache\TypeList; use Magento\Framework\Filesystem\DirectoryList; class CacheTrace { public function __construct( private readonly DirectoryList $directoryList ) { } public function beforeCleanType( TypeList $subject, string $typeCode ): array { $this->writeTrace('CLEAN', [$typeCode]); return [$typeCode]; } public function beforeFlush( Manager $subject, array $types ): array { $this->writeTrace('FLUSH', $types); return [$types]; } private function writeTrace(string $action, array $types): void { $trace = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 25 ); $lines = []; foreach ($trace as $entry) { $call = ($entry['class'] ?? '') . ($entry['type'] ?? '') . ($entry['function'] ?? ''); $location = isset($entry['file']) ? $entry['file'] . ':' . ($entry['line'] ?? '') : ''; $lines[] = $call . ' ' . $location; } $message = sprintf( "[%s] %s: %s\n%s\n\n", date('Y-m-d H:i:s'), $action, implode(', ', $types), implode("\n", $lines) ); file_put_contents( $this->directoryList->getPath(DirectoryList::LOG) . '/cache-trace.log', $message, FILE_APPEND | LOCK_EX ); } } |
If, for example, the full_page or layout cache gets cleared, the corresponding call stack is written to var/log/cache-trace.log. You can often identify whether the call originated in Magento core, a cron job or a specific extension.
It is also important to distinguish CLEAN from FLUSH. Clean removes specific Magento cache types, while flush clears the underlying cache storage.
Use this kind of tracing only while debugging and remove it afterwards. When a store keeps losing its full page cache for no apparent reason, it can quickly reveal which code is clearing the cache..