網站製作學習誌

記錄學習製作網站的一切

在 Zend Framework 中的 MVC 裡使用 Zend_Log

一般我們都在程式裡去做一些 log 的動作,而在 Zend Framework 裡,這件工作可以交給 Zend_Log 來完成。

Zend_Log 的詳細用法,可以參考官方手冊中有關 Zend_Log 套件的介紹;這邊我將簡單為大家介紹如何在 MVC 架構裡使用 Zend_Log 。

在 Action Controller 中使用 Zend_Log

首先我們要在 application.ini 中加入以下設定:

1
2
3
resources.log.logger1.writerName = "Firebug"
resources.log.logger1.filterName = "Priority"
resources.log.logger1.filterParams.priority = 3

這樣的設定會透過 Zend_Application_Resource_Log 建立一個使用 Firebug 做為寫入器的 logger ;這裡的 logger1 只是為了區隔多組 logger 所用的名稱,在程式中並沒有特別的用途。

註:當然不見得只能用 Firebug ,大家可以參考官方手冊的「 Using the Factory to Create a Log 」一節來設定其他的寫入器。

然後我們可以在想要做 log 動作的 Action Controller 裡加入以下方法:

1
2
3
4
5
6
7
8
9
10
11
protected function _log($message, $priority, $extras = null)
    {
        if ($log = $this->getLog()) {
            $log->log($message, $priority, $extras);
        }
    }
    public function getLog()
    {
        return ($log = $this->getInvokeArg('bootstrap')->getResource('Log'))
             ? $log : false;
    }

在 action 中就可以這樣呼叫了:

1
$this->_log('test', Zend_Log::ERR);

在 Model 中使用 Zend_Log

在 Model 中其實並不能直接取得 Zend_Application_Resource_Log 所產生的 logger ,因此我們要使用注入的方式來達成這個目標。

請在有需要做 Log 的 Model 中加入以下程式碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
protected $_log = null;
    public function setLog($log)
    {
        if ($log instanceof Zend_Log) {
            $this->_log = $log;
        }
    }
    public function getLog()
    {
        return $this->_log;
    }
    protected function _log($message, $priority, $extras = null)
    {
        if ($log = $this->getLog()) {
            $log->log($message, $priority, $extras);
        }
    }

這樣我們就可以在 Model 的其他部份用 _log 方法來做 log ,例如:

1
2
3
4
5
6
7
8
class Application_Model_Test
{
    public function run()
    {
        $this->_log('run', Zend_Log::ERR);
    }
    // ... 略 ...
}

那麼怎麼注入 log 物件呢?如下例:

1
2
3
4
5
6
7
8
9
10
class IndexController extends Zend_Controller_Action
{
    public function indexAction()
    {
        $test = new Application_Model_Test();
        $test->setLog($this->getLog());
        $test->run();
    }
    // ... 略 ...
}

這裡的 $this->getLog() 就是剛剛我們在 Action Controller 裡所建立的方法。

心得

這裡介紹的方法,是參考了網路上一些文章後,我自己歸納出來的心得;不過我自己覺得應該是還有更簡單的方式,而不需要在每個 Controller 裡去建立這樣的機制。

如果有找到比較好的方法時,我會再分享給大家;當然大家若有任何更好的建議的話,也歡迎告訴我。

Comments