【问题标题】:How to log the calling class infos?如何记录调用类信息?
【发布时间】:2011-08-11 09:55:49
【问题描述】:

我想重写 CI_Log 类来改进日志行。 我想记录调用类的名称和方法。 示例:

DEBUG - 2011-04-23 09:21:29 - MY_Class - method --> Router Class Initialized

我试图像这样覆盖 write_log 方法:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Log extends CI_Log {

    public function write_log($level = 'error', $msg, $php_error = FALSE)
    {
        [...]

        $message .= 
            $level .
            (($level == 'INFO') ? '  - ' : ' - ') .
            $this->router->fetch_class() .
            ' - ' .
            $this->router->fetch_method() .
            ' - ' .
            date($this->_date_fmt). ' --> ' .
            $msg .
            "\n";

        [...]
    }

}

但它不起作用,$this-&gt;router 不可访问。 你能帮帮我吗?

【问题讨论】:

  • 当然,$this-&gt;router 只适用于控制器,所以这不是一个好主意。我希望这适用于模型等......

标签: php codeigniter logging


【解决方案1】:

你可以在你的方法的某个地方使用:

//$RTR 可从 system/core/CodeIgniter.php 获得 全球$RTR; $router_class= $RTR->fetch_class(); $rotuer_method = $RTR->fetch_method();

【讨论】:

  • 感谢您的回答。因为 Log 类是在 Router 类之前初始化的,所以我不得不使用这种语法:$router_class = ''; $router_method = ''; //$RTR is available from system/core/CodeIgniter.php global $RTR; if ( isset($RTR)) { $router_class = $RTR-&gt;fetch_class(); $router_method = $RTR-&gt;fetch_method(); } 但这仅适用于当前控制器...
  • 我解释一下:我希望当控制器/模型/任何调用log_message('debug', 'blabla');的东西生成以下行DEBUG - 2011-04-23 09:21:29 - Class - method --&gt; Router Class Initialized
【解决方案2】:

好的,我想我明白了。这是我的代码:

    [...]

    $message .= $level.(($level == 'INFO') ? '  - ' : ' - ') . date($this->_date_fmt);

    $stack = debug_backtrace();
    // We are searching for the 2nd element of the $stack array beacause :
    // - $stack[0] is always taken by JG_Log->write_log()
    // - $stack[1] is always taken by log_message()
    if (isset($stack[2]['class'])) {
        $message .= ' - ' . $stack[2]['class'] . ' - ' . $stack[2]['function'];
    }

    $message .= ' --> '.$msg."\n";

    [...]

我希望可以帮助别人! :-)

【讨论】:

    猜你喜欢
    • 2011-11-23
    • 2011-07-08
    • 1970-01-01
    • 1970-01-01
    • 2013-12-06
    • 1970-01-01
    • 2021-11-11
    • 2011-11-10
    • 2016-07-28
    相关资源
    最近更新 更多