Zend有提供一個專門紀錄Log的物件:Zend_Log,以下為Zend_Log定義的Log類型
EMERG = 0; // Emergency: system is unusable ALERT = 1; // Alert: action must be taken immediately CRIT = 2; // Critical: critical conditions ERR = 3; // Error: error conditions WARN = 4; // Warning: warning conditions NOTICE = 5; // Notice: normal but significant condition INFO = 6; // Informational: informational messages DEBUG = 7; // Debug: debug messages
Zend_log寫入檔案
//預設是使用Append mode開啟檔案 $writer = new Zend_Log_Writer_Stream(dirname(__DIR__) . '/log/logfile'); $logger = new Zend_Log($writer); //寫入 info log $logger->info('Informational message'); //寫入 err log $logger->err('Error'); //使用參數決定log型態 $logger->log('Info~~~ message', Zend_Log::INFO);
fopen檔案,修改檔案開啟權限
//可以使用fopen開啟檔案 $file = fopen(dirname(__DIR__) . '/log/logfile2','a+',false); $writer = new Zend_Log_Writer_Stream($file); $logger = new Zend_Log($writer); $logger->info('Informational message');
將Log寫入資料庫
//Log寫入資料庫 $db = Zend_Db::factory('Pdo_Mysql', array( 'host' => 'localhost', 'username' => 'johnson', 'password' => '123', 'dbname' => 'log' )); $db -> query('set names UTF8'); //將資料對應到欄位(Zend_Log本身有提供一些event item,例如priority、message) $columnMapping = array('lvl' => 'priority', 'msg' => 'message', 'date' => 'log_date'); $writer = new Zend_Log_Writer_Db($db, 'log_table', $columnMapping); $logger = new Zend_Log($writer); //自訂資料庫date的欄位 $logger->setEventItem('log_date',date('Y-m-d')); $logger->info('Informational message');