Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

Debug และ Log PHP OPcache Issues

OPcache ปรับปรุง Performance โดย Cache Compiled Bytecode แต่บางครั้งก่อให้เกิด Bug ที่ยากต่อการ Debug (Stale Cache, Corruption, Incompatibility)

1. ปิด OPcache ชั่วคราว (Quick Test)

ถ้า Bug หายเมื่อปิด OPcache → ปัญหาอยู่ที่ OPcache

2. เปิด Error Reporting เต็มที่

ini_set('display_errors', '1');
error_reporting(E_ALL); // หรือ -1 (ทั้งหมด)

// ใน php.ini
// display_errors = On
// error_reporting = E_ALL
// log_errors = On
// error_log = /var/log/php_errors.log

3. OPcache Configuration สำหรับ Development

; php.ini หรือ .user.ini
opcache.enable=1
opcache.enable_cli=1

; Development: Revalidate ทุกครั้ง (ไม่ Cache)
opcache.validate_timestamps=1
opcache.revalidate_freq=0  ; 0 = Check ทุก Request

; Production: Revalidate ทุก N วินาที
; opcache.validate_timestamps=1
; opcache.revalidate_freq=60

; Logging
opcache.error_log=/var/log/opcache.log
opcache.log_verbosity_level=3  ; 1=Fatal, 2=Error, 3=Warning, 4=Info, 5=Debug

; Memory
opcache.memory_consumption=128
opcache.max_accelerated_files=10000
opcache.interned_strings_buffer=16

4. Clear OPcache แบบ Manual

5. ตรวจสอบ OPcache Status

 true/false
['cache_full'] => true/false (Cache เต็ม)
['wasted_percentage'] => % Memory ที่ Waste
['num_cached_scripts'] => จำนวนไฟล์ที่ Cache
['hit_rate'] => Cache Hit Rate (%)
*/

// ดู Scripts ที่ Cache
$scripts = $status['scripts'] ?? [];
foreach ($scripts as $path => $info) {
    echo "$path: {$info['memory_consumption']} bytes, hits: {$info['hit_count']}\n";
}

6. ใช้ Xdebug (Debugger จริง)

OPcache และ Xdebug ทำงานร่วมได้ แต่ Xdebug จะ Disable OPcache สำหรับไฟล์ที่ Debug อยู่

; php.ini (Development)
zend_extension=xdebug.so
xdebug.mode=debug,develop,trace
xdebug.client_host=127.0.0.1
xdebug.client_port=9003
xdebug.start_with_request=trigger

; OPcache ยังคงทำงานสำหรับไฟล์อื่น
opcache.enable=1

7. Common OPcache Issues และ Fix

อาการสาเหตุแก้ไข
Code ใหม่ไม่ Run (Run Code เก่า)Cache ไม่ Invalidateopcache.validate_timestamps=1, revalidate_freq=0 (Dev)
Fatal Error: Cannot redeclare classCache Corrupt / Symlink Issueopcache_reset(), Restart PHP-FPM
Segfault / CrashIncompatible Extension / BugUpdate PHP, Disable JIT, Check Extensions
Memory Exhaustedopcache.memory_consumption น้อยเกินเพิ่มเป็น 256MB+
File ถูก Delete แต่ยัง Cacheopcache.enable_file_override=1ตั้งค่า 0 หรือ Restart

8. JIT (PHP 8.0+) และ OPcache

; php.ini
opcache.jit_buffer_size=100M
opcache.jit=1255 (tracing) หรือ function

; หากมีปัญหา: ปิด JIT
opcache.jit=off

Best Practice Checklist

  • ☐ Development: validate_timestamps=1, revalidate_freq=0
  • ☐ Production: validate_timestamps=1, revalidate_freq=60 (หรือ 0 + Deploy Script Clear Cache)
  • ☐ Deploy Script: เรียก opcache_reset() หรือ Restart PHP-FPM หลัง Deploy
  • ☐ Monitor: opcache_get_status() - Hit Rate > 90%, Wasted < 10%
  • ☐ Preload (PHP 7.4+): ใช้ opcache.preload สำหรับ Framework Core