0 追蹤者

類別 yii\log\FileTarget

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

FileTarget 將日誌訊息記錄在檔案中。

日誌檔案透過 $logFile 指定。如果日誌檔案大小超過 $maxFileSize (以 KB 為單位),將執行輪替,這會將目前的日誌檔案重新命名,並在檔名後綴 '.1'。所有現有的日誌檔案都會向後移動一個位置,即 '.2' 到 '.3','.1' 到 '.2',依此類推。屬性 $maxLogFiles 指定要保留多少個歷史檔案。

自 2.0.46 版本起,檔案的輪替僅透過複製完成,且 rotateByCopy 屬性已被棄用。

公共屬性

隱藏繼承的屬性

屬性 類型 描述 定義於
$behaviors yii\base\Behavior[] 附加到此組件的行為列表。 yii\base\Component
$categories array 此目標感興趣的訊息類別列表。 yii\log\Target
$dirMode integer 為新建立的目錄設定的權限。 yii\log\FileTarget
$enableRotation boolean 當日誌檔案達到特定的 最大大小 時,是否應輪替日誌檔案。 yii\log\FileTarget
$enabled boolean 指示是否啟用此日誌目標。 yii\log\Target
$except array 此目標不感興趣的訊息類別列表。 yii\log\Target
$exportInterval integer 在匯出訊息之前應累積多少訊息。 yii\log\Target
$fileMode integer|null 為新建立的日誌檔案設定的權限。 yii\log\FileTarget
$levels integer 此目標感興趣的訊息層級。 yii\log\Target
$logFile string|null 日誌檔案路徑或 路徑別名 yii\log\FileTarget
$logVars array 應記錄在訊息中的 PHP 預定義變數列表。 yii\log\Target
$maskVars array 當存在時,不應「按原樣」記錄且應始終替換為遮罩 *** 的 PHP 預定義變數列表。 yii\log\Target
$maxFileSize integer 最大日誌檔案大小,以 KB 為單位。 yii\log\FileTarget
$maxLogFiles integer 用於輪替的日誌檔案數量。 yii\log\FileTarget
$messages array 此日誌目標至今從記錄器檢索到的訊息。 yii\log\Target
$microtime boolean 是否記錄包含微秒的時間。 yii\log\Target
$prefix callable|null 一個 PHP 可調用物件,返回一個字串,該字串將作為每個匯出訊息的前綴。 yii\log\Target
$rotateByCopy boolean 是否透過複製並截斷來輪替日誌檔案,而不是透過重新命名檔案來輪替。 yii\log\FileTarget

公共方法

隱藏繼承的方法

方法 描述 定義於
__call() 調用不是類別方法的命名方法。 yii\base\Component
__clone() 在透過克隆現有物件建立物件後,將調用此方法。 yii\base\Component
__construct() 建構子。 yii\base\BaseObject
__get() 返回組件屬性的值。 yii\base\Component
__isset() 檢查是否已設定屬性,即已定義且不為 null。 yii\base\Component
__set() 設定組件屬性的值。 yii\base\Component
__unset() 將組件屬性設定為 null。 yii\base\Component
attachBehavior() 將行為附加到此組件。 yii\base\Component
attachBehaviors() 將行為列表附加到組件。 yii\base\Component
behaviors() 返回此組件應表現為的行為列表。 yii\base\Component
canGetProperty() 返回一個值,指示是否可以讀取屬性。 yii\base\Component
canSetProperty() 返回一個值,指示是否可以設定屬性。 yii\base\Component
className() 返回此類別的完整限定名稱。 yii\base\BaseObject
collect() 處理給定的日誌訊息。 yii\log\Target
detachBehavior() 從組件分離行為。 yii\base\Component
detachBehaviors() 從組件分離所有行為。 yii\base\Component
ensureBehaviors() 確保在 behaviors() 中宣告的行為已附加到此組件。 yii\base\Component
export() 將日誌訊息寫入檔案。 yii\log\FileTarget
filterMessages() 根據訊息的類別和層級篩選給定的訊息。 yii\log\Target
formatMessage() 格式化日誌訊息以顯示為字串。 yii\log\Target
getBehavior() 返回命名的行為物件。 yii\base\Component
getBehaviors() 返回附加到此組件的所有行為。 yii\base\Component
getEnabled() 檢查是否已啟用日誌目標。 yii\log\Target
getLevels() yii\log\Target
getMessagePrefix() 返回要作為給定訊息前綴的字串。 yii\log\Target
hasEventHandlers() 返回一個值,指示是否有名稱事件附加任何處理程序。 yii\base\Component
hasMethod() 返回一個值,指示是否定義了方法。 yii\base\Component
hasProperty() 返回一個值,指示是否為此組件定義了屬性。 yii\base\Component
init() 初始化路由。 yii\log\FileTarget
off() 從此組件分離現有的事件處理程序。 yii\base\Component
on() 將事件處理程序附加到事件。 yii\base\Component
setEnabled() 設定一個值,指示是否啟用此日誌目標。 yii\log\Target
setLevels() 設定此目標感興趣的訊息層級。 yii\log\Target
trigger() 觸發事件。 yii\base\Component

受保護方法

隱藏繼承的方法

方法 描述 定義於
getContextMessage() 產生要記錄的上下文資訊。 yii\log\Target
getTime() 返回訊息的格式化 ('Y-m-d H:i:s') 時間戳記。 yii\log\Target
rotateFiles() 輪替日誌檔案。 yii\log\FileTarget

屬性詳細資訊

隱藏繼承的屬性

$dirMode public property

要為新建立的目錄設定的權限。此值將會被 PHP 的 chmod() 函數使用。不會套用 umask。預設值為 0775,表示目錄對擁有者和群組具有讀寫權限,但對其他使用者為唯讀。

public integer $dirMode 0775
$enableRotation public property (自版本 2.0.3 起可用)

當日誌檔案達到特定最大大小時,是否應輪替日誌檔案。預設情況下啟用日誌輪替。當您已在伺服器上為日誌輪替配置外部工具時,此屬性允許您停用它。

public boolean $enableRotation true
$fileMode public property

要為新建立的日誌檔案設定的權限。此值將會被 PHP 的 chmod() 函數使用。不會套用 umask。如果未設定,權限將由目前的環境決定。

public integer|null $fileMode null
$logFile public property

日誌檔案路徑或 路徑別名。如果未設定,將使用 "@runtime/logs/app.log" 檔案。如果日誌檔案所在的目錄不存在,將會自動建立。

public string|null $logFile null
$maxFileSize public property

日誌檔案最大大小,以 KB 為單位。預設值為 10240,表示 10MB。

public integer $maxFileSize 10240
$maxLogFiles public property

用於輪替的日誌檔案數量。預設值為 5。

public integer $maxLogFiles 5
$rotateByCopy public property
自 2.0.46 版本起已棄用,並且將其設定為 false 已不再有任何效果,因為現在輪替始終透過複製完成。

是否透過複製和截斷來輪替日誌檔案,而不是透過重新命名檔案來輪替。預設值為 true,以便更相容於日誌追蹤器和 Windows 系統,這些系統在已開啟的檔案上使用重新命名時效果不佳。然而,透過重新命名進行輪替會稍微快一些。

Windows 系統的問題在於 rename() 函數不適用於某些程序開啟的檔案,這在 PHP 文件中的 Martin Pelletier 的評論 中有所描述。透過將 rotateByCopy 設定為 true,您可以解決此問題。

public boolean $rotateByCopy true

方法詳情

隱藏繼承的方法

__call() public method (公有方法)

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

調用不是類別方法的命名方法。

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

請勿直接呼叫此方法,因為它是一個 PHP 魔術方法,當調用未知方法時會被隱式呼叫。

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() public method (公有方法)

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

在透過克隆現有物件建立物件後,將調用此方法。

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

public void __clone ( )

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

            
__construct() public method (公有方法)

定義於: 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() public method (公有方法)

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

返回組件屬性的值。

此方法將依以下順序檢查並相應地執行動作

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

請勿直接呼叫此方法,因為它是一個 PHP 魔術方法,當執行 $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() public method (公有方法)

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

檢查是否已設定屬性,即已定義且不為 null。

此方法將依以下順序檢查並相應地執行動作

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

請勿直接呼叫此方法,因為它是一個 PHP 魔術方法,當執行 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() public method (公有方法)

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

設定組件屬性的值。

此方法將依以下順序檢查並相應地執行動作

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

請勿直接呼叫此方法,因為它是一個 PHP 魔術方法,當執行 $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() public method (公有方法)

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

將組件屬性設定為 null。

此方法將依以下順序檢查並相應地執行動作

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

請勿直接呼叫此方法,因為它是一個 PHP 魔術方法,當執行 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() public method (公有方法)

定義於: 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() public method (公有方法)

定義於: 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() public method (公有方法)

定義於: 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 [];
}

            
canGetProperty() public method (公有方法)

定義於: 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() public method (公有方法)

定義於: 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() public static method (公有靜態方法)
自 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();
}

            
collect() public method (公有方法)

定義於: yii\log\Target::collect()

處理給定的日誌訊息。

此方法將使用 $levels$categories 過濾給定的訊息。如果需要,它還會將過濾結果匯出到特定媒介(例如電子郵件)。

public void collect ( $messages, $final )
$messages array

要處理的日誌訊息。請參閱 yii\log\Logger::$messages 以了解每個訊息的結構。

$final boolean

此方法是否在目前應用程式的結尾呼叫

                public function collect($messages, $final)
{
    $this->messages = array_merge($this->messages, static::filterMessages($messages, $this->getLevels(), $this->categories, $this->except));
    $count = count($this->messages);
    if ($count > 0 && ($final || $this->exportInterval > 0 && $count >= $this->exportInterval)) {
        if (($context = $this->getContextMessage()) !== '') {
            $this->messages[] = [$context, Logger::LEVEL_INFO, 'application', YII_BEGIN_TIME, [], 0];
        }
        // set exportInterval to 0 to avoid triggering export again while exporting
        $oldExportInterval = $this->exportInterval;
        $this->exportInterval = 0;
        $this->export();
        $this->exportInterval = $oldExportInterval;
        $this->messages = [];
    }
}

            
detachBehavior() public method (公有方法)

定義於: 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() public method (公有方法)

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

從組件分離所有行為。

public void detachBehaviors ( )

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

            
ensureBehaviors() public method (公有方法)

定義於: 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);
        }
    }
}

            
export() public method (公有方法)

將日誌訊息寫入檔案。

從 2.0.14 版本開始,如果日誌無法匯出,此方法會拋出 LogRuntimeException。

public void export ( )
throws yii\base\InvalidConfigException

如果無法開啟日誌檔案進行寫入

throws yii\log\LogRuntimeException

如果無法將完整日誌寫入檔案

                public function export()
{
    $text = implode("\n", array_map([$this, 'formatMessage'], $this->messages)) . "\n";
    if (trim($text) === '') {
        return; // No messages to export, so we exit the function early
    }
    if (strpos($this->logFile, '://') === false || strncmp($this->logFile, 'file://', 7) === 0) {
        $logPath = dirname($this->logFile);
        FileHelper::createDirectory($logPath, $this->dirMode, true);
    }
    if (($fp = @fopen($this->logFile, 'a')) === false) {
        throw new InvalidConfigException("Unable to append to log file: {$this->logFile}");
    }
    @flock($fp, LOCK_EX);
    if ($this->enableRotation) {
        // clear stat cache to ensure getting the real current file size and not a cached one
        // this may result in rotating twice when cached file size is used on subsequent calls
        clearstatcache();
    }
    if ($this->enableRotation && @filesize($this->logFile) > $this->maxFileSize * 1024) {
        $this->rotateFiles();
    }
    $writeResult = @fwrite($fp, $text);
    if ($writeResult === false) {
        $error = error_get_last();
        throw new LogRuntimeException("Unable to export log through file ({$this->logFile})!: {$error['message']}");
    }
    $textSize = strlen($text);
    if ($writeResult < $textSize) {
        throw new LogRuntimeException("Unable to export whole log through file ({$this->logFile})! Wrote $writeResult out of $textSize bytes.");
    }
    @fflush($fp);
    @flock($fp, LOCK_UN);
    @fclose($fp);
    if ($this->fileMode !== null) {
        @chmod($this->logFile, $this->fileMode);
    }
}

            
filterMessages() public static method (公有靜態方法)

定義於: yii\log\Target::filterMessages()

根據訊息的類別和層級篩選給定的訊息。

public static array filterMessages ( $messages, $levels 0, $categories = [], $except = [] )
$messages array

要過濾的訊息。訊息結構遵循 yii\log\Logger::$messages 中的結構。

$levels integer

要依訊息層級過濾。這是層級值的位元遮罩。值 0 表示允許所有層級。

$categories array

要依訊息類別過濾。如果為空,則表示允許所有類別。

$except array

要排除的訊息類別。如果為空,則表示允許所有類別。

return array

已過濾的訊息。

                public static function filterMessages($messages, $levels = 0, $categories = [], $except = [])
{
    foreach ($messages as $i => $message) {
        if ($levels && !($levels & $message[1])) {
            unset($messages[$i]);
            continue;
        }
        $matched = empty($categories);
        foreach ($categories as $category) {
            if ($message[2] === $category || !empty($category) && substr_compare($category, '*', -1, 1) === 0 && strpos($message[2], rtrim($category, '*')) === 0) {
                $matched = true;
                break;
            }
        }
        if ($matched) {
            foreach ($except as $category) {
                $prefix = rtrim($category, '*');
                if (($message[2] === $category || $prefix !== $category) && strpos($message[2], $prefix) === 0) {
                    $matched = false;
                    break;
                }
            }
        }
        if (!$matched) {
            unset($messages[$i]);
        }
    }
    return $messages;
}

            
formatMessage() public method (公有方法)

定義於: yii\log\Target::formatMessage()

格式化日誌訊息以顯示為字串。

public string formatMessage ( $message )
$message array

要格式化的日誌訊息。訊息結構遵循 yii\log\Logger::$messages 中的結構。

return string

已格式化的訊息

                public function formatMessage($message)
{
    list($text, $level, $category, $timestamp) = $message;
    $level = Logger::getLevelName($level);
    if (!is_string($text)) {
        // exceptions may not be serializable if in the call stack somewhere is a Closure
        if ($text instanceof \Exception || $text instanceof \Throwable) {
            $text = (string) $text;
        } else {
            $text = VarDumper::export($text);
        }
    }
    $traces = [];
    if (isset($message[4])) {
        foreach ($message[4] as $trace) {
            $traces[] = "in {$trace['file']}:{$trace['line']}";
        }
    }
    $prefix = $this->getMessagePrefix($message);
    return $this->getTime($timestamp) . " {$prefix}[$level][$category] $text"
        . (empty($traces) ? '' : "\n    " . implode("\n    ", $traces));
}

            
getBehavior() public 方法

定義於: 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() public 方法

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

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

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

附加到此組件的行為列表

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

            
getContextMessage() protected 方法

定義於: yii\log\Target::getContextMessage()

產生要記錄的上下文資訊。

預設實作將會傾印使用者資訊、系統變數等等。

protected string getContextMessage ( )
return string

上下文資訊。如果為空字串,則表示沒有上下文資訊。

                protected function getContextMessage()
{
    $context = ArrayHelper::filter($GLOBALS, $this->logVars);
    foreach ($this->maskVars as $var) {
        if (ArrayHelper::getValue($context, $var) !== null) {
            ArrayHelper::setValue($context, $var, '***');
        }
    }
    $result = [];
    foreach ($context as $key => $value) {
        $result[] = "\${$key} = " . VarDumper::dumpAsString($value);
    }
    return implode("\n\n", $result);
}

            
getEnabled() public 方法

定義於: yii\log\Target::getEnabled()

檢查是否已啟用日誌目標。

public boolean getEnabled ( )
return boolean

一個值,指示此日誌目標是否啟用。

                public function getEnabled()
{
    if (is_callable($this->_enabled)) {
        return call_user_func($this->_enabled, $this);
    }
    return $this->_enabled;
}

            
getLevels() public 方法
public integer getLevels ( )
return integer

此目標感興趣的訊息層級。這是層級值的位元遮罩。預設值為 0,表示所有可用層級。

                public function getLevels()
{
    return $this->_levels;
}

            
getMessagePrefix() public 方法

定義於: yii\log\Target::getMessagePrefix()

返回要作為給定訊息前綴的字串。

如果配置了 $prefix,它將返回回呼的結果。預設實作將返回使用者 IP、使用者 ID 和會話 ID 作為前綴。

public string getMessagePrefix ( $message )
$message array

正在匯出的訊息。訊息結構遵循 yii\log\Logger::$messages 中的結構。

return string

前綴字串

                public function getMessagePrefix($message)
{
    if ($this->prefix !== null) {
        return call_user_func($this->prefix, $message);
    }
    if (Yii::$app === null) {
        return '';
    }
    $request = Yii::$app->getRequest();
    $ip = $request instanceof Request ? $request->getUserIP() : '-';
    /* @var $user \yii\web\User */
    $user = Yii::$app->has('user', true) ? Yii::$app->get('user') : null;
    if ($user && ($identity = $user->getIdentity(false))) {
        $userID = $identity->getId();
    } else {
        $userID = '-';
    }
    /* @var $session \yii\web\Session */
    $session = Yii::$app->has('session', true) ? Yii::$app->get('session') : null;
    $sessionID = $session && $session->getIsActive() ? $session->getId() : '-';
    return "[$ip][$userID][$sessionID]";
}

            
getTime() protected 方法 (自版本 2.0.13 起可用)

定義於: yii\log\Target::getTime()

返回訊息的格式化 ('Y-m-d H:i:s') 時間戳記。

如果 $microtime 配置為 true,它將返回 'Y-m-d H:i:s.u' 格式。

protected string getTime ( $timestamp )
$timestamp float

                protected function getTime($timestamp)
{
    $parts = explode('.', sprintf('%F', $timestamp));
    return date('Y-m-d H:i:s', $parts[0]) . ($this->microtime ? ('.' . $parts[1]) : '');
}

            
hasEventHandlers() public 方法

定義於: 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() public 方法

定義於: 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() public 方法

定義於: 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() public 方法

初始化路由。

在路由管理器建立路由後,將會調用此方法。

public void init ( )

                public function init()
{
    parent::init();
    if ($this->logFile === null) {
        $this->logFile = Yii::$app->getRuntimePath() . '/logs/app.log';
    } else {
        $this->logFile = Yii::getAlias($this->logFile);
    }
    if ($this->maxLogFiles < 1) {
        $this->maxLogFiles = 1;
    }
    if ($this->maxFileSize < 1) {
        $this->maxFileSize = 1;
    }
}

            
off() public 方法

定義於: 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() public 方法

定義於: 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 可呼叫

事件處理常式

$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]);
    }
}

            
rotateFiles() protected 方法

輪替日誌檔案。

protected void rotateFiles ( )

                protected function rotateFiles()
{
    $file = $this->logFile;
    for ($i = $this->maxLogFiles; $i >= 0; --$i) {
        // $i == 0 is the original log file
        $rotateFile = $file . ($i === 0 ? '' : '.' . $i);
        if (is_file($rotateFile)) {
            // suppress errors because it's possible multiple processes enter into this section
            if ($i === $this->maxLogFiles) {
                @unlink($rotateFile);
                continue;
            }
            $newFile = $this->logFile . '.' . ($i + 1);
            $this->rotateByCopy($rotateFile, $newFile);
            if ($i === 0) {
                $this->clearLogFile($rotateFile);
            }
        }
    }
}

            
setEnabled() public 方法

定義於: yii\log\Target::setEnabled()

設定一個值,指示是否啟用此日誌目標。

public void setEnabled ( $value )
$value boolean|callable

布林值或可呼叫值,用於從中取得值。可呼叫值自版本 2.0.13 起可用。

可使用可呼叫值來動態確定是否應啟用日誌目標。例如,若要僅在目前使用者登入時才啟用日誌,您可以將目標配置為如下

'enabled' => function() {
    return !Yii::$app->user->isGuest;
}

                public function setEnabled($value)
{
    $this->_enabled = $value;
}

            
setLevels() public 方法

定義於: yii\log\Target::setLevels()

設定此目標感興趣的訊息層級。

參數可以是感興趣的層級名稱陣列,也可以是表示感興趣的層級值的位元遮罩的整數。有效的層級名稱包括:'error'、'warning'、'info'、'trace' 和 'profile';有效的層級值包括:yii\log\Logger::LEVEL_ERRORyii\log\Logger::LEVEL_WARNINGyii\log\Logger::LEVEL_INFOyii\log\Logger::LEVEL_TRACEyii\log\Logger::LEVEL_PROFILE

例如,

['error', 'warning']
// which is equivalent to:
Logger::LEVEL_ERROR | Logger::LEVEL_WARNING
public void setLevels ( $levels )
$levels array|integer

此目標感興趣的訊息層級。

throws yii\base\InvalidConfigException

如果 $levels 值不正確。

                public function setLevels($levels)
{
    static $levelMap = [
        'error' => Logger::LEVEL_ERROR,
        'warning' => Logger::LEVEL_WARNING,
        'info' => Logger::LEVEL_INFO,
        'trace' => Logger::LEVEL_TRACE,
        'profile' => Logger::LEVEL_PROFILE,
    ];
    if (is_array($levels)) {
        $this->_levels = 0;
        foreach ($levels as $level) {
            if (isset($levelMap[$level])) {
                $this->_levels |= $levelMap[$level];
            } else {
                throw new InvalidConfigException("Unrecognized level: $level");
            }
        }
    } else {
        $bitmapValues = array_reduce($levelMap, function ($carry, $item) {
            return $carry | $item;
        });
        if (!($bitmapValues & $levels) && $levels !== 0) {
            throw new InvalidConfigException("Incorrect $levels value");
        }
        $this->_levels = $levels;
    }
}

            
trigger() public 方法

定義於: 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);
}