0 追蹤者

類別 yii\log\Logger

繼承yii\log\Logger » yii\base\Component » yii\base\BaseObject
實作yii\base\Configurable
自版本起可用2.0
原始碼 https://github.com/yiisoft/yii2/blob/master/framework/log/Logger.php

Logger 會將記錄的訊息儲存在記憶體中,並在設定 $dispatcher 時將其發送到不同的目標。

Logger 實例可以通過 Yii::getLogger() 存取。您可以呼叫 log() 方法來記錄單個日誌訊息。為了方便起見,提供了一組快捷方法,用於通過 Yii 類別記錄各種嚴重性級別的訊息

有關 Logger 的更多詳細資訊和使用資訊,請參閱關於日誌記錄的指南文章

當應用程式結束或達到 $flushInterval 時,Logger 將呼叫 flush(),以在 $dispatcher 的幫助下,將記錄的訊息發送到不同的日誌目標,例如檔案電子郵件資料庫

公開屬性

隱藏繼承的屬性

屬性 類型 描述 定義於
$behaviors yii\base\Behavior[] 附加到此元件的行為列表。 yii\base\Component
$dbEventNames array 用於獲取資料庫查詢統計結果的事件名稱。 yii\log\Logger
$dbProfiling array 第一個元素表示執行的 SQL 語句數量,第二個元素表示在 SQL 執行中花費的總時間。 yii\log\Logger
$dispatcher yii\log\Dispatcher 訊息調度器。 yii\log\Logger
$elapsedTime float 當前請求經過的總時間(秒)。 yii\log\Logger
$flushInterval integer 在訊息從記憶體刷新並發送到目標之前,應該記錄多少訊息。 yii\log\Logger
$messages array 已記錄的訊息。 yii\log\Logger
$profiling array 效能分析結果。 yii\log\Logger
$profilingAware boolean 是否應開啟效能分析感知模式。 yii\log\Logger
$traceLevel integer 每個訊息應記錄多少呼叫堆疊資訊(檔案名稱和行號)。 yii\log\Logger

公開方法

隱藏繼承的方法

方法 描述 定義於
__call() 呼叫指定的非類別方法。 yii\base\Component
__clone() 此方法在通過複製現有物件建立物件後調用。 yii\base\Component
__construct() 建構子。 yii\base\BaseObject
__get() 返回元件屬性的值。 yii\base\Component
__isset() 檢查屬性是否已設定,即已定義且非空。 yii\base\Component
__set() 設定元件屬性的值。 yii\base\Component
__unset() 將元件屬性設定為 null。 yii\base\Component
attachBehavior() 將行為附加到此元件。 yii\base\Component
attachBehaviors() 將行為列表附加到元件。 yii\base\Component
behaviors() 返回此元件應表現為的行為列表。 yii\base\Component
calculateTimings() 計算給定日誌訊息的經過時間。 yii\log\Logger
canGetProperty() 返回指示屬性是否可讀的值。 yii\base\Component
canSetProperty() 返回指示屬性是否可設定的值。 yii\base\Component
className() 返回此類別的完整限定名稱。 yii\base\BaseObject
detachBehavior() 從元件分離行為。 yii\base\Component
detachBehaviors() 從元件分離所有行為。 yii\base\Component
ensureBehaviors() 確保在 behaviors() 中宣告的行為已附加到此元件。 yii\base\Component
flush() 將日誌訊息從記憶體刷新到目標。 yii\log\Logger
getBehavior() 返回指定的行為物件。 yii\base\Component
getBehaviors() 返回附加到此元件的所有行為。 yii\base\Component
getDbProfiling() 返回資料庫查詢的統計結果。 yii\log\Logger
getElapsedTime() 返回自當前請求開始以來經過的總時間。 yii\log\Logger
getLevelName() 返回指定層級的文字顯示。 yii\log\Logger
getProfiling() 返回效能分析結果。 yii\log\Logger
hasEventHandlers() 返回指示是否有名稱事件的任何處理常式的值。 yii\base\Component
hasMethod() 傳回一個值,指出是否已定義方法。 yii\base\Component
hasProperty() 傳回一個值,指出是否已為此組件定義屬性。 yii\base\Component
init() 透過註冊 flush() 作為關閉函式,初始化記錄器。 yii\log\Logger
log() 使用給定的類型和類別記錄訊息。 yii\log\Logger
off() 從此組件分離現有的事件處理常式。 yii\base\Component
on() 將事件處理常式附加到事件。 yii\base\Component
trigger() 觸發事件。 yii\base\Component

常數

隱藏繼承的常數

常數 描述 定義於
LEVEL_ERROR 0x1 錯誤訊息層級。錯誤訊息表示應用程式異常終止,可能需要開發人員處理。 yii\log\Logger
LEVEL_INFO 0x4 資訊訊息層級。資訊訊息包含供開發人員檢閱的特定資訊。 yii\log\Logger
LEVEL_PROFILE 0x40 效能分析訊息層級。表示此訊息用於效能分析目的。 yii\log\Logger
LEVEL_PROFILE_BEGIN 0x50 效能分析訊息層級。表示此訊息用於效能分析目的。它標記效能分析區塊的開始。 yii\log\Logger
LEVEL_PROFILE_END 0x60 效能分析訊息層級。表示此訊息用於效能分析目的。它標記效能分析區塊的結束。 yii\log\Logger
LEVEL_TRACE 0x8 追蹤訊息層級。追蹤訊息揭示程式碼執行流程。 yii\log\Logger
LEVEL_WARNING 0x2 警告訊息層級。警告訊息表示發生一些異常情況,但應用程式仍可繼續執行。開發人員應注意此訊息。 yii\log\Logger

屬性詳細資訊

隱藏繼承的屬性

$dbEventNames 公開屬性 (自版本 2.0.41 起可用)

用於獲取資料庫查詢統計結果的事件名稱。

public array $dbEventNames = [
    
'yii\db\Command::query',
    
'yii\db\Command::execute',
]
$dbProfiling 公開屬性

第一個元素表示執行的 SQL 語句數量,第二個元素表示在 SQL 執行中花費的總時間。

public array $dbProfiling null
$dispatcher 公開屬性

訊息調度器。

$elapsedTime 公開屬性

當前請求經過的總時間(秒)。

public float $elapsedTime null
$flushInterval 公開屬性

在將訊息從記憶體清除並傳送到目標之前,應記錄多少訊息。預設值為 1000,表示每記錄 1000 條訊息就會調用一次 flush() 方法。如果您不想在應用程式終止之前清除訊息,請將此屬性設定為 0。此屬性主要影響記錄訊息將佔用多少記憶體。較小的值表示較少的記憶體,但由於 flush() 的額外負荷,將增加執行時間。

public integer $flushInterval 1000
$messages 公開屬性

已記錄的訊息。此屬性由 log()flush() 管理。每條記錄訊息的結構如下

[
  [0] => message (mixed, can be a string or some complex data, such as an exception object)
  [1] => level (integer)
  [2] => category (string)
  [3] => timestamp (float, obtained by microtime(true))
  [4] => traces (array, debug backtrace, contains the application code call stacks)
  [5] => memory usage in bytes (int, obtained by memory_get_usage()), available since version 2.0.11.
]
public array $messages = []
$profiling 公開屬性

效能分析結果。每個元素都是一個陣列,包含以下元素:infocategorytimestamptraceleveldurationmemorymemoryDiffmemorymemoryDiff 值自版本 2.0.11 起可用。

public array $profiling null
$profilingAware 公開屬性 (自版本 2.0.43 起可用)

是否應開啟效能分析感知模式。如果開啟,flush() 會確保成對清除效能分析區塊。如果偵測到任何懸而未決的訊息,這些訊息將保留到下一個清除間隔以尋找其配對。為防止記憶體洩漏,當懸而未決的訊息數量達到 flushInterval 值時,記錄器會立即清除它們並觸發警告。請記住,效能分析感知模式更耗費時間和記憶體。

public boolean $profilingAware false
$traceLevel 公開屬性

每條訊息應記錄多少呼叫堆疊資訊(檔案名稱和行號)。如果大於 0,則最多記錄該數量的呼叫堆疊。請注意,僅計算應用程式呼叫堆疊。

public integer $traceLevel 0

方法詳細資訊

隱藏繼承的方法

__call() 公開方法

定義於: yii\base\Component::__call()

呼叫指定的非類別方法。

此方法將檢查是否有任何附加的行為具有指定的名稱方法,如果有,則會執行它。

請勿直接呼叫此方法,因為它是 PHP magic method,當調用未知方法時,會隱含地呼叫它。

public mixed __call ( $name, $params )
$name string

方法名稱

$params array

方法參數

return mixed

方法傳回值

throws yii\base\UnknownMethodException

當呼叫未知方法時

                public function __call($name, $params)
{
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $object) {
        if ($object->hasMethod($name)) {
            return call_user_func_array([$object, $name], $params);
        }
    }
    throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}

            
__clone() 公開方法

定義於: yii\base\Component::__clone()

此方法在通過複製現有物件建立物件後調用。

它會移除所有行為,因為它們附加到舊物件。

public void __clone ( )

                public function __clone()
{
    $this->_events = [];
    $this->_eventWildcards = [];
    $this->_behaviors = null;
}

            
__construct() 公開方法

定義於: yii\base\BaseObject::__construct()

建構子。

預設實作會執行兩件事

  • 使用給定的組態 $config 初始化物件。
  • 呼叫 init()

如果此方法在子類別中被覆寫,建議

  • 建構子的最後一個參數是組態陣列,例如此處的 $config
  • 在建構子的結尾呼叫父類別實作。
public void __construct ( $config = [] )
$config array

將用於初始化物件屬性的名稱-值對

                public function __construct($config = [])
{
    if (!empty($config)) {
        Yii::configure($this, $config);
    }
    $this->init();
}

            
__get() 公開方法

定義於: yii\base\Component::__get()

返回元件屬性的值。

此方法將依以下順序檢查並採取相應的動作

  • getter 定義的屬性:傳回 getter 結果
  • 行為的屬性:傳回行為屬性值

請勿直接呼叫此方法,因為它是 PHP magic method,當執行 $value = $component->property; 時,會隱含地呼叫它。

另請參閱 __set()

public mixed __get ( $name )
$name string

屬性名稱

return mixed

屬性值或行為的屬性值

throws yii\base\UnknownPropertyException

如果未定義屬性

throws yii\base\InvalidCallException

如果屬性為唯寫。

                public function __get($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        // read property, e.g. getName()
        return $this->$getter();
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canGetProperty($name)) {
            return $behavior->$name;
        }
    }
    if (method_exists($this, 'set' . $name)) {
        throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}

            
__isset() 公開方法

定義於: yii\base\Component::__isset()

檢查屬性是否已設定,即已定義且非空。

此方法將依以下順序檢查並採取相應的動作

  • setter 定義的屬性:傳回屬性是否已設定
  • 行為的屬性:傳回屬性是否已設定
  • 針對不存在的屬性傳回 false

請勿直接呼叫此方法,因為它是 PHP magic method,當執行 isset($component->property) 時,會隱含地呼叫它。

另請參閱 https://php.dev.org.tw/manual/en/function.isset.php

public boolean __isset ( $name )
$name string

屬性名稱或事件名稱

return boolean

具名屬性是否已設定

                public function __isset($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter() !== null;
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canGetProperty($name)) {
            return $behavior->$name !== null;
        }
    }
    return false;
}

            
__set() 公開方法

定義於: yii\base\Component::__set()

設定元件屬性的值。

此方法將依以下順序檢查並採取相應的動作

  • setter 定義的屬性:設定屬性值
  • 格式為 "on xyz" 的事件:將處理常式附加到事件 "xyz"
  • 格式為 "as xyz" 的行為:附加名為 "xyz" 的行為
  • 行為的屬性:設定行為屬性值

請勿直接呼叫此方法,因為它是 PHP magic method,當執行 $component->property = $value; 時,會隱含地呼叫它。

另請參閱 __get()

public void __set ( $name, $value )
$name string

屬性名稱或事件名稱

$value mixed

屬性值

throws yii\base\UnknownPropertyException

如果未定義屬性

throws yii\base\InvalidCallException

如果屬性為唯讀。

                public function __set($name, $value)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        // set property
        $this->$setter($value);
        return;
    } elseif (strncmp($name, 'on ', 3) === 0) {
        // on event: attach event handler
        $this->on(trim(substr($name, 3)), $value);
        return;
    } elseif (strncmp($name, 'as ', 3) === 0) {
        // as behavior: attach behavior
        $name = trim(substr($name, 3));
        $this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value));
        return;
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canSetProperty($name)) {
            $behavior->$name = $value;
            return;
        }
    }
    if (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}

            
__unset() 公開方法

定義於: yii\base\Component::__unset()

將元件屬性設定為 null。

此方法將依以下順序檢查並採取相應的動作

  • setter 定義的屬性:將屬性值設定為 null
  • 行為的屬性:將屬性值設定為 null

請勿直接呼叫此方法,因為它是 PHP magic method,當執行 unset($component->property) 時,會隱含地呼叫它。

另請參閱 https://php.dev.org.tw/manual/en/function.unset.php

public void __unset ( $name )
$name string

屬性名稱

throws yii\base\InvalidCallException

如果屬性為唯讀。

                public function __unset($name)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        $this->$setter(null);
        return;
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canSetProperty($name)) {
            $behavior->$name = null;
            return;
        }
    }
    throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
}

            
attachBehavior() 公開方法

定義於: yii\base\Component::attachBehavior()

將行為附加到此元件。

此方法將根據給定的組態建立行為物件。之後,將透過呼叫 yii\base\Behavior::attach() 方法,將行為物件附加到此組件。

另請參閱 detachBehavior()

public yii\base\Behavior attachBehavior ( $name, $behavior )
$name string

行為的名稱。

$behavior string|array|yii\base\Behavior

行為組態。這可以是以下其中之一

return yii\base\Behavior

行為物件

                public function attachBehavior($name, $behavior)
{
    $this->ensureBehaviors();
    return $this->attachBehaviorInternal($name, $behavior);
}

            
attachBehaviors() 公開方法

定義於: yii\base\Component::attachBehaviors()

將行為列表附加到元件。

每個行為都由其名稱索引,並且應該是 yii\base\Behavior 物件、指定行為類別的字串或用於建立行為的組態陣列。

另請參閱 attachBehavior()

public void attachBehaviors ( $behaviors )
$behaviors array

要附加到組件的行為列表

                public function attachBehaviors($behaviors)
{
    $this->ensureBehaviors();
    foreach ($behaviors as $name => $behavior) {
        $this->attachBehaviorInternal($name, $behavior);
    }
}

            
behaviors() 公開方法

定義於: yii\base\Component::behaviors()

返回此元件應表現為的行為列表。

子類別可以覆寫此方法,以指定它們想要表現為的行為。

此方法的傳回值應為行為物件或組態的陣列,並由行為名稱索引。行為組態可以是指定行為類別的字串,或具有以下結構的陣列

'behaviorName' => [
    'class' => 'BehaviorClass',
    'property1' => 'value1',
    'property2' => 'value2',
]

請注意,行為類別必須從 yii\base\Behavior 擴展。行為可以使用名稱或匿名方式附加。當名稱用作陣列鍵時,使用此名稱,稍後可以使用 getBehavior() 檢索行為,或使用 detachBehavior() 分離行為。匿名行為無法檢索或分離。

在此方法中宣告的行為將自動(按需)附加到組件。

public array behaviors ( )
return array

行為組態。

                public function behaviors()
{
    return [];
}

            
calculateTimings() 公開方法

計算給定日誌訊息的經過時間。

public array calculateTimings ( $messages )
$messages array

從效能分析取得的記錄訊息

return array

計時。每個元素都是一個陣列,包含以下元素:infocategorytimestamptraceleveldurationmemorymemoryDiffmemorymemoryDiff 值自版本 2.0.11 起可用。

                public function calculateTimings($messages)
{
    $timings = [];
    $stack = [];
    foreach ($messages as $i => $log) {
        list($token, $level, $category, $timestamp, $traces) = $log;
        $memory = isset($log[5]) ? $log[5] : 0;
        $log[6] = $i;
        $hash = md5(json_encode($token));
        if ($level == self::LEVEL_PROFILE_BEGIN) {
            $stack[$hash] = $log;
        } elseif ($level == self::LEVEL_PROFILE_END) {
            if (isset($stack[$hash])) {
                $timings[$stack[$hash][6]] = [
                    'info' => $stack[$hash][0],
                    'category' => $stack[$hash][2],
                    'timestamp' => $stack[$hash][3],
                    'trace' => $stack[$hash][4],
                    'level' => count($stack) - 1,
                    'duration' => $timestamp - $stack[$hash][3],
                    'memory' => $memory,
                    'memoryDiff' => $memory - (isset($stack[$hash][5]) ? $stack[$hash][5] : 0),
                ];
                unset($stack[$hash]);
            }
        }
    }
    ksort($timings);
    return array_values($timings);
}

            
canGetProperty() 公開方法

定義於: yii\base\Component::canGetProperty()

返回指示屬性是否可讀的值。

如果符合以下條件,則可以讀取屬性

  • 類別具有與指定名稱關聯的 getter 方法(在這種情況下,屬性名稱不區分大小寫);
  • 類別具有具有指定名稱的成員變數(當 $checkVars 為 true 時);
  • 附加的行為具有給定名稱的可讀屬性(當 $checkBehaviors 為 true 時)。

另請參閱 canSetProperty()

public boolean canGetProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

屬性名稱

$checkVars boolean

是否將成員變數視為屬性

$checkBehaviors boolean

是否將行為的屬性視為此組件的屬性

return boolean

屬性是否可以讀取

                public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
    if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
        return true;
    } elseif ($checkBehaviors) {
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->canGetProperty($name, $checkVars)) {
                return true;
            }
        }
    }
    return false;
}

            
canSetProperty() 公開方法

定義於: yii\base\Component::canSetProperty()

返回指示屬性是否可設定的值。

如果符合以下條件,則可以寫入屬性

  • 類別具有與指定名稱關聯的 setter 方法(在這種情況下,屬性名稱不區分大小寫);
  • 類別具有具有指定名稱的成員變數(當 $checkVars 為 true 時);
  • 附加的行為具有給定名稱的可寫入屬性(當 $checkBehaviors 為 true 時)。

另請參閱 canGetProperty()

public boolean canSetProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

屬性名稱

$checkVars boolean

是否將成員變數視為屬性

$checkBehaviors boolean

是否將行為的屬性視為此組件的屬性

return boolean

屬性是否可以寫入

                public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
    if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
        return true;
    } elseif ($checkBehaviors) {
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->canSetProperty($name, $checkVars)) {
                return true;
            }
        }
    }
    return false;
}

            
className() 公開靜態方法
自 2.0.14 版本起已棄用。在 PHP >=5.5 上,請改用 ::class

定義於: yii\base\BaseObject::className()

返回此類別的完整限定名稱。

public static string className ( )
return string

此類別的完整限定名稱。

                public static function className()
{
    return get_called_class();
}

            
detachBehavior() 公開方法

定義於: yii\base\Component::detachBehavior()

從元件分離行為。

將調用行為的 yii\base\Behavior::detach() 方法。

public yii\base\Behavior|null detachBehavior ( $name )
$name string

行為的名稱。

return yii\base\Behavior|null

分離的行為。如果行為不存在,則為 Null。

                public function detachBehavior($name)
{
    $this->ensureBehaviors();
    if (isset($this->_behaviors[$name])) {
        $behavior = $this->_behaviors[$name];
        unset($this->_behaviors[$name]);
        $behavior->detach();
        return $behavior;
    }
    return null;
}

            
detachBehaviors() 公有方法

Defined in: yii\base\Component::detachBehaviors()

從元件分離所有行為。

public void detachBehaviors ( )

                public function detachBehaviors()
{
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $name => $behavior) {
        $this->detachBehavior($name);
    }
}

            
ensureBehaviors() 公有方法

Defined in: yii\base\Component::ensureBehaviors()

確保在 behaviors() 中宣告的行為已附加到此元件。

public void ensureBehaviors ( )

                public function ensureBehaviors()
{
    if ($this->_behaviors === null) {
        $this->_behaviors = [];
        foreach ($this->behaviors() as $name => $behavior) {
            $this->attachBehaviorInternal($name, $behavior);
        }
    }
}

            
flush() 公有方法

將日誌訊息從記憶體刷新到目標。

public void flush ( $final false )
$final boolean

是否為請求期間的最終呼叫。

                public function flush($final = false)
{
    if ($this->profilingAware) {
        $keep = [];
        $messages = [];
        foreach ($this->messages as $index => $message) {
            if (is_int($index)) {
                $messages[] = $message;
            } else {
                if (strncmp($index, 'begin-', 6) === 0) {
                    $oppositeProfile = 'end-' . substr($index, 6);
                } else {
                    $oppositeProfile = 'begin-' . substr($index, 4);
                }
                if (array_key_exists($oppositeProfile, $this->messages)) {
                    $messages[] = $message;
                } else {
                    $keep[$index] = $message;
                }
            }
        }
        if ($this->flushInterval > 0 && count($keep) >= $this->flushInterval) {
            $this->messages = [];
            $this->log(
                'Number of dangling profiling block messages reached flushInterval value and therefore these were flushed. Please consider setting higher flushInterval value or making profiling blocks shorter.',
                self::LEVEL_WARNING
            );
            $messages = array_merge($messages, array_values($keep));
        } else {
            $this->messages = $keep;
        }
    } else {
        $messages = $this->messages;
        $this->messages = [];
    }
    if ($this->dispatcher instanceof Dispatcher) {
        $this->dispatcher->dispatch($messages, $final);
    }
}

            
getBehavior() 公有方法

Defined in: yii\base\Component::getBehavior()

返回指定的行為物件。

public yii\base\Behavior|null getBehavior ( $name )
$name string

行為名稱

return yii\base\Behavior|null

行為物件,如果行為不存在則為 null

                public function getBehavior($name)
{
    $this->ensureBehaviors();
    return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}

            
getBehaviors() 公有方法

Defined in: yii\base\Component::getBehaviors()

返回附加到此元件的所有行為。

public yii\base\Behavior[] getBehaviors ( )
return yii\base\Behavior[]

附加到此組件的行為列表

                public function getBehaviors()
{
    $this->ensureBehaviors();
    return $this->_behaviors;
}

            
getDbProfiling() 公有方法

返回資料庫查詢的統計結果。

傳回的結果包含執行的 SQL 陳述式數量和花費的總時間。

public array getDbProfiling ( )
return array

第一個元素表示執行的 SQL 語句數量,第二個元素表示在 SQL 執行中花費的總時間。

                public function getDbProfiling()
{
    $timings = $this->getProfiling($this->dbEventNames);
    $count = count($timings);
    $time = 0;
    foreach ($timings as $timing) {
        $time += $timing['duration'];
    }
    return [$count, $time];
}

            
getElapsedTime() 公有方法

返回自當前請求開始以來經過的總時間。

此方法計算現在與常數 YII_BEGIN_TIME 定義的時間戳記之間的差異,該時間戳記在 yii\BaseYii 類別檔案的開頭評估。

public float getElapsedTime ( )
return float

當前請求經過的總時間(秒)。

                public function getElapsedTime()
{
    return microtime(true) - YII_BEGIN_TIME;
}

            
getLevelName() public static method

返回指定層級的文字顯示。

public static string getLevelName ( $level )
$level integer

訊息層級,例如 LEVEL_ERRORLEVEL_WARNING

return string

層級的文字顯示

                public static function getLevelName($level)
{
    static $levels = [
        self::LEVEL_ERROR => 'error',
        self::LEVEL_WARNING => 'warning',
        self::LEVEL_INFO => 'info',
        self::LEVEL_TRACE => 'trace',
        self::LEVEL_PROFILE_BEGIN => 'profile begin',
        self::LEVEL_PROFILE_END => 'profile end',
        self::LEVEL_PROFILE => 'profile',
    ];
    return isset($levels[$level]) ? $levels[$level] : 'unknown';
}

            
getProfiling() 公有方法

返回效能分析結果。

預設情況下,將傳回所有效能分析結果。您可以提供 $categories$excludeCategories 作為參數,以檢索您感興趣的結果。

public array getProfiling ( $categories = [], $excludeCategories = [] )
$categories array

您感興趣的類別列表。您可以在類別的末尾使用星號來進行前綴比對。例如,'yii\db*' 將比對以 'yii\db\' 開頭的類別,例如 'yii\db\Connection'。

$excludeCategories array

您想要排除的類別列表

return array

效能分析結果。每個元素都是一個陣列,包含以下元素:infocategorytimestamptraceleveldurationmemorymemoryDiffmemorymemoryDiff 值自版本 2.0.11 起可用。

                public function getProfiling($categories = [], $excludeCategories = [])
{
    $timings = $this->calculateTimings($this->messages);
    if (empty($categories) && empty($excludeCategories)) {
        return $timings;
    }
    foreach ($timings as $outerIndex => $outerTimingItem) {
        $currentIndex = $outerIndex;
        $matched = empty($categories);
        foreach ($categories as $category) {
            $prefix = rtrim($category, '*');
            if (
                ($outerTimingItem['category'] === $category || $prefix !== $category)
                && strpos($outerTimingItem['category'], $prefix) === 0
            ) {
                $matched = true;
                break;
            }
        }
        if ($matched) {
            foreach ($excludeCategories as $category) {
                $prefix = rtrim($category, '*');
                foreach ($timings as $innerIndex => $innerTimingItem) {
                    $currentIndex = $innerIndex;
                    if (
                        ($innerTimingItem['category'] === $category || $prefix !== $category)
                        && strpos($innerTimingItem['category'], $prefix) === 0
                    ) {
                        $matched = false;
                        break;
                    }
                }
            }
        }
        if (!$matched) {
            unset($timings[$currentIndex]);
        }
    }
    return array_values($timings);
}

            
hasEventHandlers() 公有方法

Defined in: yii\base\Component::hasEventHandlers()

返回指示是否有名稱事件的任何處理常式的值。

public boolean hasEventHandlers ( $name )
$name string

事件名稱

return boolean

是否有任何處理常式附加到事件。

                public function hasEventHandlers($name)
{
    $this->ensureBehaviors();
    if (!empty($this->_events[$name])) {
        return true;
    }
    foreach ($this->_eventWildcards as $wildcard => $handlers) {
        if (!empty($handlers) && StringHelper::matchWildcard($wildcard, $name)) {
            return true;
        }
    }
    return Event::hasHandlers($this, $name);
}

            
hasMethod() 公有方法

Defined in: yii\base\Component::hasMethod()

傳回一個值,指出是否已定義方法。

如果滿足以下條件,則定義方法:

  • 類別具有具有指定名稱的方法
  • 附加的行為具有給定名稱的方法(當 $checkBehaviors 為 true 時)。
public boolean hasMethod ( $name, $checkBehaviors true )
$name string

屬性名稱

$checkBehaviors boolean

是否將行為的方法視為此組件的方法

return boolean

是否已定義方法

                public function hasMethod($name, $checkBehaviors = true)
{
    if (method_exists($this, $name)) {
        return true;
    } elseif ($checkBehaviors) {
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->hasMethod($name)) {
                return true;
            }
        }
    }
    return false;
}

            
hasProperty() 公有方法

Defined in: yii\base\Component::hasProperty()

傳回一個值,指出是否已為此組件定義屬性。

如果滿足以下條件,則定義屬性:

  • 類別具有與指定名稱關聯的 getter 或 setter 方法(在這種情況下,屬性名稱不區分大小寫);
  • 類別具有具有指定名稱的成員變數(當 $checkVars 為 true 時);
  • 附加的行為具有給定名稱的屬性(當 $checkBehaviors 為 true 時)。

參見

public boolean hasProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

屬性名稱

$checkVars boolean

是否將成員變數視為屬性

$checkBehaviors boolean

是否將行為的屬性視為此組件的屬性

return boolean

是否已定義屬性

                public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
    return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}

            
init() 公有方法

透過註冊 flush() 作為關閉函式,初始化記錄器。

public void init ( )

                public function init()
{
    parent::init();
    register_shutdown_function(function () {
        // make regular flush before other shutdown functions, which allows session data collection and so on
        $this->flush();
        // make sure log entries written by shutdown functions are also flushed
        // ensure "flush()" is called last when there are multiple shutdown functions
        register_shutdown_function([$this, 'flush'], true);
    });
}

            
log() 公有方法

使用給定的類型和類別記錄訊息。

如果 $traceLevel 大於 0,則也會記錄關於應用程式碼的其他呼叫堆疊資訊。

public void log ( $message, $level, $category 'application' )
$message string|array

要記錄的訊息。這可以是簡單的字串,也可以是更複雜的資料結構,將由 log target 處理。

$level integer

訊息的層級。這必須是以下其中一項:Logger::LEVEL_ERRORLogger::LEVEL_WARNINGLogger::LEVEL_INFOLogger::LEVEL_TRACELogger::LEVEL_PROFILELogger::LEVEL_PROFILE_BEGINLogger::LEVEL_PROFILE_END

$category string

訊息的類別。

                public function log($message, $level, $category = 'application')
{
    $time = microtime(true);
    $traces = [];
    if ($this->traceLevel > 0) {
        $count = 0;
        $ts = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
        array_pop($ts); // remove the last trace since it would be the entry script, not very useful
        foreach ($ts as $trace) {
            if (isset($trace['file'], $trace['line']) && strpos($trace['file'], YII2_PATH) !== 0) {
                unset($trace['object'], $trace['args']);
                $traces[] = $trace;
                if (++$count >= $this->traceLevel) {
                    break;
                }
            }
        }
    }
    $data = [$message, $level, $category, $time, $traces, memory_get_usage()];
    if ($this->profilingAware && in_array($level, [self::LEVEL_PROFILE_BEGIN, self::LEVEL_PROFILE_END])) {
        $this->messages[($level == self::LEVEL_PROFILE_BEGIN ? 'begin-' : 'end-') . md5(json_encode($message))] = $data;
    } else {
        $this->messages[] = $data;
    }
    if ($this->flushInterval > 0 && count($this->messages) >= $this->flushInterval) {
        $this->flush();
    }
}

            
off() 公有方法

Defined in: yii\base\Component::off()

從此組件分離現有的事件處理常式。

此方法與 on() 相反。

注意:如果為事件名稱傳遞了萬用字元模式,則僅會移除使用此萬用字元註冊的處理常式,而使用與此萬用字元匹配的純名稱註冊的處理常式將保留。

另請參閱 on()

public boolean off ( $name, $handler null )
$name string

事件名稱

$handler callable|null

要移除的事件處理常式。如果為 null,則將移除附加到具名事件的所有處理常式。

return boolean

如果找到並分離處理常式

                public function off($name, $handler = null)
{
    $this->ensureBehaviors();
    if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
        return false;
    }
    if ($handler === null) {
        unset($this->_events[$name], $this->_eventWildcards[$name]);
        return true;
    }
    $removed = false;
    // plain event names
    if (isset($this->_events[$name])) {
        foreach ($this->_events[$name] as $i => $event) {
            if ($event[0] === $handler) {
                unset($this->_events[$name][$i]);
                $removed = true;
            }
        }
        if ($removed) {
            $this->_events[$name] = array_values($this->_events[$name]);
            return true;
        }
    }
    // wildcard event names
    if (isset($this->_eventWildcards[$name])) {
        foreach ($this->_eventWildcards[$name] as $i => $event) {
            if ($event[0] === $handler) {
                unset($this->_eventWildcards[$name][$i]);
                $removed = true;
            }
        }
        if ($removed) {
            $this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
            // remove empty wildcards to save future redundant regex checks:
            if (empty($this->_eventWildcards[$name])) {
                unset($this->_eventWildcards[$name]);
            }
        }
    }
    return $removed;
}

            
on() 公有方法

Defined in: yii\base\Component::on()

將事件處理常式附加到事件。

事件處理常式必須是有效的 PHP 回呼。以下是一些範例

function ($event) { ... }         // anonymous function
[$object, 'handleClick']          // $object->handleClick()
['Page', 'handleClick']           // Page::handleClick()
'handleClick'                     // global function handleClick()

事件處理常式必須使用以下簽名定義:

function ($event)

其中 $event 是一個 yii\base\Event 物件,其中包含與事件關聯的參數。

自 2.0.14 起,您可以將事件名稱指定為萬用字元模式

$component->on('event.group.*', function ($event) {
    Yii::trace($event->name . ' is triggered.');
});

另請參閱 off()

public void on ( $name, $handler, $data null, $append true )
$name string

事件名稱

$handler callable

事件處理常式

$data mixed

事件觸發時要傳遞給事件處理常式的資料。叫用事件處理常式時,可以透過 yii\base\Event::$data 存取此資料。

$append boolean

是否將新的事件處理常式附加到現有處理常式列表的末尾。如果為 false,則新處理常式將插入到現有處理常式列表的開頭。

                public function on($name, $handler, $data = null, $append = true)
{
    $this->ensureBehaviors();
    if (strpos($name, '*') !== false) {
        if ($append || empty($this->_eventWildcards[$name])) {
            $this->_eventWildcards[$name][] = [$handler, $data];
        } else {
            array_unshift($this->_eventWildcards[$name], [$handler, $data]);
        }
        return;
    }
    if ($append || empty($this->_events[$name])) {
        $this->_events[$name][] = [$handler, $data];
    } else {
        array_unshift($this->_events[$name], [$handler, $data]);
    }
}

            
trigger() 公有方法

Defined in: yii\base\Component::trigger()

觸發事件。

此方法表示事件的發生。它會叫用事件的所有附加處理常式,包括類別層級的處理常式。

public void trigger ( $name, yii\base\Event $event null )
$name string

事件名稱

$event yii\base\Event|null

事件實例。如果未設定,將建立預設的 yii\base\Event 物件。

                public function trigger($name, Event $event = null)
{
    $this->ensureBehaviors();
    $eventHandlers = [];
    foreach ($this->_eventWildcards as $wildcard => $handlers) {
        if (StringHelper::matchWildcard($wildcard, $name)) {
            $eventHandlers[] = $handlers;
        }
    }
    if (!empty($this->_events[$name])) {
        $eventHandlers[] = $this->_events[$name];
    }
    if (!empty($eventHandlers)) {
        $eventHandlers = call_user_func_array('array_merge', $eventHandlers);
        if ($event === null) {
            $event = new Event();
        }
        if ($event->sender === null) {
            $event->sender = $this;
        }
        $event->handled = false;
        $event->name = $name;
        foreach ($eventHandlers as $handler) {
            $event->data = $handler[1];
            call_user_func($handler[0], $event);
            // stop further handling if the event is handled
            if ($event->handled) {
                return;
            }
        }
    }
    // invoke class-level attached handlers
    Event::trigger($this, $name, $event);
}