Skip to content
PHP Ecosystem
Explore

Logger

API reference › yii › log › Logger

classyii\log\Logger
Extendsyii\base\Component » yii\base\BaseObject
Implementsyii\base\Configurable
Since2.0
Sourceframework/log/Logger.php

Logger records logged messages in memory and sends them to different targets if $dispatcher is set.

A Logger instance can be accessed via Yii::getLogger(). You can call the method log() to record a single log message. For convenience, a set of shortcut methods are provided for logging messages of various severity levels via the Yii class:

For more details and usage information on Logger, see the guide article on logging.

When the application ends or $flushInterval is reached, Logger will call flush() to send logged messages to different log targets, such as file, email, or database, with the help of the $dispatcher.

PropertyTypeDescriptionDefined by
$behaviors read-onlyarray<yii\base\Behavior<static>>List of behaviors attached to this component.yii\base\Component
$dbEventNamesarrayOf event names used to get statistical results of DB queries. Default: ['yii\db\Command::query', 'yii\db\Command::execute']. Available since 2.0.41.Logger
$dbProfiling read-onlyarray{int, int|float}The first element indicates the number of SQL statements executed, and the second element the total time spent in SQL execution.Logger
$dispatcherDispatcherThe message dispatcher. Default: null.Logger
$elapsedTime read-onlyfloatThe total elapsed time in seconds for current request.Logger
$flushIntervalintHow many messages should be logged before they are flushed from memory and sent to targets. Default: 1000.Logger
$messagesarray<int|string, yii\log\LogMessage>Logged messages. Default: [].Logger
$profiling read-onlylist<yii\log\ProfilingTiming>The profiling results.Logger
$profilingAwareboolWhether the profiling-aware mode should be switched on. Default: false. Available since 2.0.43.Logger
$traceLevelintHow much call stack information (file name and line number) should be logged for each message. Default: 0.Logger
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
calculateTimings()Calculates the elapsed time for the given log messages.Logger
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
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
flush()Flushes log messages from memory to targets.Logger
getBehavior()Returns the named behavior object.yii\base\Component
getBehaviors()Returns all behaviors attached to this component.yii\base\Component
getDbProfiling()Returns the statistical results of DB queries.Logger
getElapsedTime()Returns the total elapsed time since the start of the current request.Logger
getLevelName() staticReturns the text display of the specified level.Logger
getProfiling()Returns the profiling results.Logger
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 logger by registering flush() as a shutdown function.Logger
log()Logs a message with the given type and category.Logger
off()Detaches an existing event handler from this component.yii\base\Component
on()Attaches an event handler to an event.yii\base\Component
trigger()Triggers an event.yii\base\Component
ConstantValueDescriptionDefined by
LEVEL_ERROR0x1Error message level. An error message is one that indicates the abnormal termination of the application and may require developer’s handling.Logger
LEVEL_WARNING0x2Warning message level. A warning message is one that indicates some abnormal happens but the application is able to continue to run. Developers should pay attention to this message.Logger
LEVEL_INFO0x4Informational message level. An informational message is one that includes certain information for developers to review.Logger
LEVEL_TRACE0x8Tracing message level. A tracing message is one that reveals the code execution flow.Logger
LEVEL_PROFILE0x40Profiling message level. This indicates the message is for profiling purpose.Logger
LEVEL_PROFILE_BEGIN0x50Profiling message level. This indicates the message is for profiling purpose. It marks the beginning of a profiling block.Logger
LEVEL_PROFILE_END0x60Profiling message level. This indicates the message is for profiling purpose. It marks the end of a profiling block.Logger
public int $flushInterval = 1000

How many messages should be logged before they are flushed from memory and sent to targets.

Defaults to 1000, meaning the flush() method will be invoked once every 1000 messages logged. Set this property to be 0 if you don’t want to flush messages until the application terminates. This property mainly affects how much memory will be taken by the logged messages. A smaller value means less memory, but will increase the execution time due to the overhead of flush().

public array<int|string, yii\log\LogMessage> $messages = []

Logged messages.

This property is managed by log() and flush(). Each log message is of the following structure:

[
[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 list<yii\log\ProfilingTiming> $profiling

The profiling results.

Each element is an array consisting of these elements: info, category, timestamp, trace, level, duration, memory, memoryDiff. The memory and memoryDiff values are available since version 2.0.11.

Access

Read-only (virtual property).

public bool $profilingAware = false

Whether the profiling-aware mode should be switched on.

If on, flush() makes sure that profiling blocks are flushed in pairs. In case that any dangling messages are detected these are kept for the next flush interval to find their pair. To prevent memory leaks, when number of dangling messages reaches flushInterval value, logger flushes them immediately and triggers a warning. Keep in mind that profiling-aware mode is more time and memory consuming.

Since

2.0.43

public int $traceLevel = 0

How much call stack information (file name and line number) should be logged for each message.

If it is greater than 0, at most that number of call stacks will be logged. Note that only application call stacks are counted.

public function calculateTimings(array<int|string, yii\log\LogMessage> $messages): list<yii\log\ProfilingTiming>

Calculates the elapsed time for the given log messages.

Parameters

ParameterTypeDescription
$messagesarray<int|string, yii\log\LogMessage>The log messages obtained from profiling

Returns

list<yii\log\ProfilingTiming>: Timings. Each element is an array consisting of these elements: info, category, timestamp, trace, level, duration, memory, memoryDiff. The memory and memoryDiff values are available since version 2.0.11.

public function flush(bool $final = false): mixed

Flushes log messages from memory to targets.

Parameters

ParameterTypeDescription
$finalboolWhether this is a final call during a request.

Returns

mixed

public function getDbProfiling(): array{int, int|float}

Returns the statistical results of DB queries.

The results returned include the number of SQL statements executed and the total time spent.

Returns

array{int, int|float}: The first element indicates the number of SQL statements executed, and the second element the total time spent in SQL execution.

public function getElapsedTime(): float

Returns the total elapsed time since the start of the current request.

This method calculates the difference between now and the timestamp defined by constant YII_BEGIN_TIME which is evaluated at the beginning of BaseYii class file.

Returns

float: The total elapsed time in seconds for current request.

public static function getLevelName(int $level): string

Returns the text display of the specified level.

Parameters

ParameterTypeDescription
$levelintThe message level, e.g. LEVEL_ERROR, LEVEL_WARNING.

Returns

string: The text display of the level

public function getProfiling(list<string> $categories = [], list<string> $excludeCategories = []): list<yii\log\ProfilingTiming>

Returns the profiling results.

By default, all profiling results will be returned. You may provide $categories and $excludeCategories as parameters to retrieve the results that you are interested in.

Parameters

ParameterTypeDescription
$categorieslist<string>List of categories that you are interested in. You can use an asterisk at the end of a category to do a prefix match. For example, ‘yii\db*’ will match categories starting with ‘yii\db’, such as ‘yii\db\Connection’.
$excludeCategorieslist<string>List of categories that you want to exclude

Returns

list<yii\log\ProfilingTiming>: The profiling results. Each element is an array consisting of these elements: info, category, timestamp, trace, level, duration, memory, memoryDiff. The memory and memoryDiff values are available since version 2.0.11.

public function init(): mixed

Initializes the logger by registering flush() as a shutdown function.

Returns

mixed

public function log(string|array|Throwable|yii\log\PsrMessage $message, int $level, string $category = 'application'): mixed

Logs a message with the given type and category.

If $traceLevel is greater than 0, additional call stack information about the application code will be logged as well.

Parameters

ParameterTypeDescription
$messagestring|array|Throwable|PsrMessageThe message to be logged. This can be a simple string or a more complex data structure that will be handled by a log target.
$levelintThe level of the message. This must be one of the following: Logger::LEVEL_ERROR, Logger::LEVEL_WARNING, Logger::LEVEL_INFO, Logger::LEVEL_TRACE, Logger::LEVEL_PROFILE, Logger::LEVEL_PROFILE_BEGIN, Logger::LEVEL_PROFILE_END.
$categorystringThe category of the message.

Returns

mixed