Skip to content
PHP Ecosystem
Explore

Target

API reference › yii › log › Target

abstract classyii\log\Target
Extendsyii\base\Component » yii\base\BaseObject
Implementsyii\base\Configurable
Since2.0
Sourceframework/log/Target.php
6 subclasses

Target is the base class for all log target classes.

A log target object will filter the messages logged by Logger according to its $levels and $categories properties. It may also export the filtered messages to specific destination defined by the target, such as emails, files.

Level filter and category filter are combinatorial, i.e., only messages satisfying both filter conditions will be handled. Additionally, you may specify $except to exclude messages of certain categories.

For more details and usage information on Target, see the guide article on logging & targets.

PropertyTypeDescriptionDefined by
$behaviors read-onlyarray<yii\base\Behavior<static>>List of behaviors attached to this component.yii\base\Component
$categorieslist<string>List of message categories that this target is interested in. Default: [].Target
$enabledbool|callableA boolean value or a callable to obtain the value from.Target
$exceptlist<string>List of message categories that this target is NOT interested in. Default: [].Target
$exportIntervalintHow many messages should be accumulated before they are exported. Default: 1000.Target
$levelsarray|intMessage levels that this target is interested in.Target
$logVarslist<string>List of the PHP predefined variables that should be logged in a message. Default: ['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION', '_SERVER'].Target
$maskVarslist<string>List of the PHP predefined variables that should NOT be logged “as is” and should always be replaced with a mask *** before logging, when exist. Default: ['_SERVER.HTTP_AUTHORIZATION', '_SERVER.PHP_AUTH_USER', '_SERVER.PHP_AUTH_PW']. Available since 2.0.16.Target
$messageslist<yii\log\LogMessage>The messages that are retrieved from the logger so far by this log target. Default: [].Target
$microtimeboolWhether to log time with microseconds. Default: false. Available since 2.0.13.Target
$prefixcallable(yii\log\LogMessage): string|nullA PHP callable that returns a string to be prefixed to every exported message. Default: null.Target
MethodDescriptionDefined by
__construct()Constructor.yii\base\BaseObject
__call()Calls the named method which is not a class method.yii\base\Component
__clone()This method is called after the object is created by cloning an existing one.yii\base\Component
__get()Returns the value of a component property.yii\base\Component
__isset()Checks if a property is set, i.e. defined and not null.yii\base\Component
__set()Sets the value of a component property.yii\base\Component
__unset()Sets a component property to be null.yii\base\Component
attachBehavior()Attaches a behavior to this component.yii\base\Component
attachBehaviors()Attaches a list of behaviors to the component.yii\base\Component
behaviors()Returns a list of behaviors that this component should behave as.yii\base\Component
canGetProperty()Returns a value indicating whether a property can be read.yii\base\Component
canSetProperty()Returns a value indicating whether a property can be set.yii\base\Component
className() staticReturns the fully qualified name of this class.yii\base\BaseObject
collect()Processes the given log messages.Target
detachBehavior()Detaches a behavior from the component.yii\base\Component
detachBehaviors()Detaches all behaviors from the component.yii\base\Component
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.yii\base\Component
export() abstractExports log $messages to a specific destination.Target
filterMessages() staticFilters the given messages according to their categories and levels.Target
formatMessage()Formats a log message for display as a string.Target
getBehavior()Returns the named behavior object.yii\base\Component
getBehaviors()Returns all behaviors attached to this component.yii\base\Component
getEnabled()Check whether the log target is enabled.Target
getLevels()Target
getMessagePrefix()Returns a string to be prefixed to the given message.Target
hasEventHandlers()Returns a value indicating whether there is any handler attached to the named event.yii\base\Component
hasMethod()Returns a value indicating whether a method is defined.yii\base\Component
hasProperty()Returns a value indicating whether a property is defined for this component.yii\base\Component
init()Initializes the object.yii\base\BaseObject
off()Detaches an existing event handler from this component.yii\base\Component
on()Attaches an event handler to an event.yii\base\Component
setEnabled()Sets a value indicating whether this log target is enabled.Target
setLevels()Sets the message levels that this target is interested in.Target
trigger()Triggers an event.yii\base\Component
formatMessageText() protectedConverts a log message value to text.Target
getContextMessage() protectedGenerates the context information to be logged.Target
getTime() protectedReturns formatted (‘Y-m-d H:i:s’) timestamp for message.Target
public list<string> $categories = []

List of message categories that this target is interested in.

Defaults to empty, meaning all categories. You can use an asterisk at the end of a category so that the category may be used to match those categories sharing the same common prefix. For example, ‘yii\db*’ will match categories starting with ‘yii\db’, such as ‘yii\db\Connection’.

public bool|callable $enabled

A boolean value or a callable to obtain the value from.

The callable value is available since version 2.0.13.

A callable may be used to determine whether the log target should be enabled in a dynamic way. For example, to only enable a log if the current user is logged in you can configure the target as follows:

'enabled' => function() {
return !Yii::$app->user->isGuest;
}
public list<string> $except = []

List of message categories that this target is NOT interested in.

Defaults to empty, meaning no uninteresting messages. If this property is not empty, then any category listed here will be excluded from $categories. You can use an asterisk at the end of a category so that the category can be used to match those categories sharing the same common prefix. For example, ‘yii\db*’ will match categories starting with ‘yii\db’, such as ‘yii\db\Connection’.

public int $exportInterval = 1000

How many messages should be accumulated before they are exported.

Defaults to 1000. Note that messages will always be exported when the application terminates. Set this property to be 0 if you don’t want to export messages until the application terminates.

public list<string> $logVars = ['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION', '_SERVER']

List of the PHP predefined variables that should be logged in a message.

Note that a variable must be accessible via $GLOBALS. Otherwise it won’t be logged.

Defaults to ['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION', '_SERVER'].

Since version 2.0.9 additional syntax can be used: Each element could be specified as one of the following:

  • var - var will be logged.
  • var.key - only var[key] key will be logged.
  • !var.key - var[key] key will be excluded.

Note that if you need $_SESSION to logged regardless if session was used you have to open it right at the start of your request.

public list<string> $maskVars = ['_SERVER.HTTP_AUTHORIZATION', '_SERVER.PHP_AUTH_USER', '_SERVER.PHP_AUTH_PW']

List of the PHP predefined variables that should NOT be logged “as is” and should always be replaced with a mask *** before logging, when exist.

Defaults to [ '_SERVER.HTTP_AUTHORIZATION', '_SERVER.PHP_AUTH_USER', '_SERVER.PHP_AUTH_PW']

Each element could be specified as one of the following:

  • var - var will be logged as ***
  • var.key - only var[key] will be logged as ***

In addition, this property accepts (case-insensitive) patterns. For example:

  • _SERVER.*_SECRET matches all ending with _SECRET, such as $_SERVER['TOKEN_SECRET'] etc.
  • _SERVER.SECRET_* matches all starting with SECRET_, such as $_SERVER['SECRET_TOKEN'] etc.
  • _SERVER.*SECRET* matches all containing SECRET i.e. both of the above.

Since

2.0.16

public list<yii\log\LogMessage> $messages = []

The messages that are retrieved from the logger so far by this log target.

Please refer to Logger::$messages for the details about the message structure.

public bool $microtime = false

Whether to log time with microseconds.

Defaults to false.

Since

2.0.13

public callable(yii\log\LogMessage): string|null $prefix = null

A PHP callable that returns a string to be prefixed to every exported message.

If not set, getMessagePrefix() will be used, which prefixes the message with context information such as user IP, user ID and session ID.

The signature of the callable should be function ($message).

public function collect(array<int|string, yii\log\LogMessage> $messages, bool $final): mixed

Processes the given log messages.

This method will filter the given messages with $levels and $categories. And if requested, it will also export the filtering result to specific medium (e.g. email).

Parameters

ParameterTypeDescription
$messagesarray<int|string, yii\log\LogMessage>Log messages to be processed. See Logger::$messages for the structure of each message.
$finalboolWhether this method is called at the end of the current application

Returns

mixed

abstract public function export(): mixed

Exports log $messages to a specific destination.

Child classes must implement this method.

Returns

mixed

public static function filterMessages(array<yii\log\TKey, yii\log\LogMessage> $messages, int $levels = 0, list<string> $categories = [], list<string> $except = []): array<yii\log\TKey, yii\log\LogMessage>

Filters the given messages according to their categories and levels.

Parameters

ParameterTypeDescription
$messagesarray<yii\log\TKey, yii\log\LogMessage>Messages to be filtered. The message structure follows that in Logger::$messages.
$levelsintThe message levels to filter by. This is a bitmap of level values. Value 0 means allowing all levels.
$categorieslist<string>The message categories to filter by. If empty, it means all categories are allowed.
$exceptlist<string>The message categories to exclude. If empty, it means all categories are allowed.

Returns

array<yii\log\TKey, yii\log\LogMessage>: The filtered messages.

public function formatMessage(yii\log\LogMessage $message): string

Formats a log message for display as a string.

Parameters

ParameterTypeDescription
$messageyii\log\LogMessageThe log message to be formatted. The message structure follows that in Logger::$messages.

Returns

string: The formatted message

public function getEnabled(): bool

Check whether the log target is enabled.

Returns

bool: A value indicating whether this log target is enabled.

public function getLevels(): int

Returns

int: The message levels that this target is interested in. This is a bitmap of level values. Defaults to 0, meaning all available levels.

public function getMessagePrefix(yii\log\LogMessage $message): string

Returns a string to be prefixed to the given message.

If $prefix is configured it will return the result of the callback. The default implementation will return user IP, user ID and session ID as a prefix.

Parameters

ParameterTypeDescription
$messageyii\log\LogMessageThe message being exported. The message structure follows that in Logger::$messages.

Returns

string: The prefix string

public function setEnabled(bool|callable $value): mixed

Sets a value indicating whether this log target is enabled.

Parameters

ParameterTypeDescription
$valuebool|callableA boolean value or a callable to obtain the value from. The callable value is available since version 2.0.13. A callable may be used to determine whether the log target should be enabled in a dynamic way. For example, to only enable a log if the current user is logged in you can configure the target as follows: ‘enabled’ => function() { return !Yii::$app->user->isGuest; }

Returns

mixed

public function setLevels(array|int $levels): mixed

Sets the message levels that this target is interested in.

The parameter can be either an array of interested level names or an integer representing the bitmap of the interested level values. Valid level names include: ‘error’, ‘warning’, ‘info’, ‘trace’ and ‘profile’; valid level values include: Logger::LEVEL_ERROR, Logger::LEVEL_WARNING, Logger::LEVEL_INFO, Logger::LEVEL_TRACE and Logger::LEVEL_PROFILE.

For example,

['error', 'warning']
// which is equivalent to:
Logger::LEVEL_ERROR | Logger::LEVEL_WARNING

Parameters

ParameterTypeDescription
$levelsarray|intMessage levels that this target is interested in.

Returns

mixed

Throws

protected function formatMessageText(mixed $text): string

Converts a log message value to text.

Parameters

ParameterTypeDescription
$textmixedLog message value.

Returns

string: Formatted message value.

Since

22.0

protected function getContextMessage(): string

Generates the context information to be logged.

The default implementation will dump user information, system variables, etc.

Returns

string: The context information. If an empty string, it means no context information.

protected function getTime(float $timestamp): string

Returns formatted (‘Y-m-d H:i:s’) timestamp for message.

If $microtime is configured to true it will return format ‘Y-m-d H:i:s.u’.

Parameters

ParameterTypeDescription
$timestampfloat

Returns

string

Since

2.0.13