การใช้งาน error_log() ของ PHP ในการบันทึกค่าต่างๆ
ในการเฝ้าระวังระบบที่เป็น PHP Web Application บางครั้งก็ต้องการเก็บค่าบางอย่างลง Log file ทำไงดี ? อาจจะใช้วิธี สร้างไฟล์ไว้ในพื้นที่ ที่ web user สามารถเขียนได้ แล้วก็จัดการเอง ด้วย function พวก fopen(), fwrite(), fclose(); เช่น $fp = fopen(‘/var/log/mylog.txt’, ‘a’); fwrite($fp, ‘20121207:some text’); fclose($fp); เป็นต้น ซึ่ง ก็พอจะทำได้ แต่ต้องคำนึงถึงเรื่อง permission ในการเขียน และพวกสิทธิต่างๆ ใน PHP เราสามารถบันทึกสิ่งต่างๆลงไปในไฟล์ System Log ได้เลย โดยใช้ฟังก์ชั่น error_log นอกจากนั้น ยังสามารถเลือกให้เป็นการส่ง email แทนการเขียน log ลงไฟล์ก็ได้ หรือ จะเลือกเขียนลงไฟล์อื่นที่แยกไปจาก System Log ก็ได้ การใช้งาน error_log(message, message_type, destination, options) message: เป็นข้อความที่ต้องการบันทึก message_type: ใช้ค่า 0,1,3,4 ซึ่งมีความหมายดังนี้ 0: เป็นค่า Default ซึ่งเขียนลงไปใน System Log (ตามที่ระบุในค่า error_log ของ PHP ในไฟล์ php.ini) 1: เลือกให้ส่ง message ในรูปแบบ email ไปยัง destination โดยใช้ Header ของ email ตาม options 3: เลือกให้เขียน message ลงในไฟล์ที่กำหนดใน destination (ไม่ใช่ system log) โดยจะต้องเขียน newline ต่อท้ายบรรทัดเอง 4: เลือกให้เขียนลงไปใน SAPI (จากการทดสอบบน apache บน Ubuntu พบว่า เขียนลงที่เดียวกับ System Log) destination: หาก message_type=1 ให้ระบบ email address ที่ต้องการส่งถึง, หาก message_type=3 ให้ระบุตำแหน่งของไฟล์ที่ต้องการเขียน options: ในกรณี message_type=1 สามารถระบุ header ของ email ได้ ลองเขียน PHP ตามนี้ ลงในไฟล์ test-error_log.php <?php #ini_set(‘error_log’,’/var/log/myother.log’); echo ‘error_log = ‘ . ini_get(‘error_log’) . “\n”; error_log(“This is error_log #0”, 0); error_log(“This is error_log #1”, 1, “username.s@yourdomain.com”, “Subject: Message Type #1\n”); error_log(“This is error_log #3”, 3, “/var/log/mytest.log”); error_log(“This is error_log #4”, 4); ?> แล้วใช้คำสั่ง php test-error_log.php ผลที่ออกมานั้น ถ้า 1. ใน php.ini ไม่ได้ระบุว่า error_log เขียนไปที่ไหน (error_log=) ก็จะแสดงผลออกมาทาง stderr error_log = This is error_log #0 This is error_log #4 จะมี email ส่งถึงตัวเรา มี Subject