星期四, 2月 09, 2012

利用 php 本身寫 error log 及 error/warning/notice message

  • error_reporting
    設定php回發生錯誤的等級
    error_reporting(0);  // Turn off all error reporting
    ini_set('error_reporting', E_ALL);  // Same as error_reporting(E_ALL);
  • error_log
    bool error_log ( string $message [, int $message_type = 0 [, string $destination [, string $extra_headers ]]] )
    Sends an error message to the web server's error log or to a file.
    需寫入file,因此需指定file path
    用法
    //log to file
    ini_set('error_log', dirname(__FILE__) . '/error_log.txt');  
    
    // Send notification through the server log if we can not
    // connect to the database.
    if (!Ora_Logon($username, $password)) {
        error_log("Oracle database not available!", 0);
    }
    
    // Notify administrator by email if we run out of FOO
    if (!($foo = allocate_new_foo())) {
        error_log("Big trouble, we're all out of FOOs!", 1,
                   "operator@example.com");
    }
    
    // another way to call error_log():
    error_log("You messed up!", 3, "/var/tmp/my-errors.log");
    
  • error/warning/notice message
    定義log level多配合log4php,不過也可透過trigger_error
    即可靠php本身達成此效果
    trigger_error("Notice Message",E_USER_NOTICE);
    trigger_error("Warning Message",E_USER_WARNING);
    trigger_error("Error Message",E_USER_ERROR);
    如此就不用再掛log4php,就能方便帶訊息
也就是說error_report 是設定php觸發回報錯誤的等級
如果想利用此機制寫自定的訊息就可透過trigger_error
而error_log就自己想log什麼就log什麼

error_report設定篇
開啟是否顯示error及log的等級
  • 在php.ini中設定
    display_errors = On 
    
  • 在.php中設定
    每次要到php.ini設定就太累了,這邊有方法可以直接在.php裡,直接設定log,這樣開發起來就方便多了,且不會動到整體環境
    ini_set('display_errors', 1);   //turn on display error on screen
    ini_set('log_errors', 1);     //turn on log error
    error_reporting(E_ALL); //log all errors and warnings


常見常數定義
列出常見的幾個,其他看官網Predefined Constants
Constant Description Note
E_NOTICERun-time notices. Indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script.
E_STRICTEnable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code.Since PHP 5 but not included in E_ALL until PHP 5.4.0
E_ALLAll errors and warnings, as supported, except of level E_STRICT prior to PHP 5.4.0.

References

沒有留言: