# Logger

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

[API reference](/docs/api/index.md) › [yii](/docs/api/yii/index.md) › [log](/docs/api/yii/log/index.md) › Logger

| class | `yii\log\Logger` |
| --- | --- |
| Extends | [`yii\base\Component`](/docs/api/yii/base/component/index.md) » [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| Implements | [`yii\base\Configurable`](/docs/api/yii/base/configurable/index.md) |
| Since | 2.0 |
| Source | [`framework/log/Logger.php`](https://github.com/yiisoft/yii2/blob/22.0/framework/log/Logger.php#L69) |

Logger records logged messages in memory and sends them to different targets if [`$dispatcher`](/docs/api/yii/log/logger/index.md#property-dispatcher) is set.

A Logger instance can be accessed via `Yii::getLogger()`. You can call the method [`log()`](/docs/api/yii/log/logger/index.md#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`](/docs/api/global/yii/index.md) class:

- `Yii::trace()`
- [`Yii::error()`](/docs/api/yii/baseyii/index.md#method-error)
- [`Yii::warning()`](/docs/api/yii/baseyii/index.md#method-warning)
- [`Yii::info()`](/docs/api/yii/baseyii/index.md#method-info)
- [`Yii::beginProfile()`](/docs/api/yii/baseyii/index.md#method-beginProfile)
- [`Yii::endProfile()`](/docs/api/yii/baseyii/index.md#method-endProfile)

For more details and usage information on Logger, see the [guide article on logging](/docs/guide/runtime-logging/index.md).

When the application ends or [`$flushInterval`](/docs/api/yii/log/logger/index.md#property-flushInterval) is reached, Logger will call [`flush()`](/docs/api/yii/log/logger/index.md#method-flush)
to send logged messages to different log targets, such as [file](/docs/api/yii/log/filetarget/index.md), [email](/docs/api/yii/log/emailtarget/index.md),
or [database](/docs/api/yii/log/dbtarget/index.md), with the help of the [`$dispatcher`](/docs/api/yii/log/logger/index.md#property-dispatcher).

## Properties

| Property | Type | Description | Defined by |
| --- | --- | --- | --- |
| <span id="property-behaviors"></span>[`$behaviors`](/docs/api/yii/base/component/index.md#property-behaviors) read-only | `array<`[`yii\base\Behavior`](/docs/api/yii/base/behavior/index.md)`<static>>` | List of behaviors attached to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="property-dbEventNames"></span>`$dbEventNames` | `array` | Of 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` |
| <span id="property-dbProfiling"></span>`$dbProfiling` read-only | `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. | `Logger` |
| <span id="property-dispatcher"></span>`$dispatcher` | [`Dispatcher`](/docs/api/yii/log/dispatcher/index.md) | The message dispatcher. Default: `null`. | `Logger` |
| <span id="property-elapsedTime"></span>`$elapsedTime` read-only | `float` | The total elapsed time in seconds for current request. | `Logger` |
| [`$flushInterval`](#property-flushInterval) | `int` | How many messages should be logged before they are flushed from memory and sent to targets. Default: `1000`. | `Logger` |
| [`$messages`](#property-messages) | `array<int\|string, yii\log\LogMessage>` | Logged messages. Default: `[]`. | `Logger` |
| [`$profiling`](#property-profiling) read-only | `list<yii\log\ProfilingTiming>` | The profiling results. | `Logger` |
| [`$profilingAware`](#property-profilingAware) | `bool` | Whether the profiling-aware mode should be switched on. Default: `false`. Available since 2.0.43. | `Logger` |
| [`$traceLevel`](#property-traceLevel) | `int` | How much call stack information (file name and line number) should be logged for each message. Default: `0`. | `Logger` |

## Methods

| Method | Description | Defined by |
| --- | --- | --- |
| <span id="method-__construct"></span>[`__construct()`](/docs/api/yii/base/baseobject/index.md#method-__construct) | Constructor. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__call"></span>[`__call()`](/docs/api/yii/base/component/index.md#method-__call) | Calls the named method which is not a class method. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__clone"></span>[`__clone()`](/docs/api/yii/base/component/index.md#method-__clone) | This method is called after the object is created by cloning an existing one. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__get"></span>[`__get()`](/docs/api/yii/base/component/index.md#method-__get) | Returns the value of a component property. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__isset"></span>[`__isset()`](/docs/api/yii/base/component/index.md#method-__isset) | Checks if a property is set, i.e. defined and not null. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__set"></span>[`__set()`](/docs/api/yii/base/component/index.md#method-__set) | Sets the value of a component property. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__unset"></span>[`__unset()`](/docs/api/yii/base/component/index.md#method-__unset) | Sets a component property to be null. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-attachBehavior"></span>[`attachBehavior()`](/docs/api/yii/base/component/index.md#method-attachBehavior) | Attaches a behavior to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-attachBehaviors"></span>[`attachBehaviors()`](/docs/api/yii/base/component/index.md#method-attachBehaviors) | Attaches a list of behaviors to the component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-behaviors"></span>[`behaviors()`](/docs/api/yii/base/component/index.md#method-behaviors) | Returns a list of behaviors that this component should behave as. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`calculateTimings()`](#method-calculateTimings) | Calculates the elapsed time for the given log messages. | `Logger` |
| <span id="method-canGetProperty"></span>[`canGetProperty()`](/docs/api/yii/base/component/index.md#method-canGetProperty) | Returns a value indicating whether a property can be read. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-canSetProperty"></span>[`canSetProperty()`](/docs/api/yii/base/component/index.md#method-canSetProperty) | Returns a value indicating whether a property can be set. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-className"></span>[`className()`](/docs/api/yii/base/baseobject/index.md#method-className) static | Returns the fully qualified name of this class. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-detachBehavior"></span>[`detachBehavior()`](/docs/api/yii/base/component/index.md#method-detachBehavior) | Detaches a behavior from the component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-detachBehaviors"></span>[`detachBehaviors()`](/docs/api/yii/base/component/index.md#method-detachBehaviors) | Detaches all behaviors from the component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-ensureBehaviors"></span>[`ensureBehaviors()`](/docs/api/yii/base/component/index.md#method-ensureBehaviors) | Makes sure that the behaviors declared in [`behaviors()`](/docs/api/yii/base/component/index.md#method-behaviors) are attached to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`flush()`](#method-flush) | Flushes log messages from memory to targets. | `Logger` |
| <span id="method-getBehavior"></span>[`getBehavior()`](/docs/api/yii/base/component/index.md#method-getBehavior) | Returns the named behavior object. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-getBehaviors"></span>[`getBehaviors()`](/docs/api/yii/base/component/index.md#method-getBehaviors) | Returns all behaviors attached to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`getDbProfiling()`](#method-getDbProfiling) | Returns the statistical results of DB queries. | `Logger` |
| [`getElapsedTime()`](#method-getElapsedTime) | Returns the total elapsed time since the start of the current request. | `Logger` |
| [`getLevelName()`](#method-getLevelName) static | Returns the text display of the specified level. | `Logger` |
| [`getProfiling()`](#method-getProfiling) | Returns the profiling results. | `Logger` |
| <span id="method-hasEventHandlers"></span>[`hasEventHandlers()`](/docs/api/yii/base/component/index.md#method-hasEventHandlers) | Returns a value indicating whether there is any handler attached to the named event. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-hasMethod"></span>[`hasMethod()`](/docs/api/yii/base/component/index.md#method-hasMethod) | Returns a value indicating whether a method is defined. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-hasProperty"></span>[`hasProperty()`](/docs/api/yii/base/component/index.md#method-hasProperty) | Returns a value indicating whether a property is defined for this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`init()`](#method-init) | Initializes the logger by registering [`flush()`](/docs/api/yii/log/logger/index.md#method-flush) as a shutdown function. | `Logger` |
| [`log()`](#method-log) | Logs a message with the given type and category. | `Logger` |
| <span id="method-off"></span>[`off()`](/docs/api/yii/base/component/index.md#method-off) | Detaches an existing event handler from this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-on"></span>[`on()`](/docs/api/yii/base/component/index.md#method-on) | Attaches an event handler to an event. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-trigger"></span>[`trigger()`](/docs/api/yii/base/component/index.md#method-trigger) | Triggers an event. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |

## Constants

| Constant | Value | Description | Defined by |
| --- | --- | --- | --- |
| <span id="const-LEVEL_ERROR"></span>`LEVEL_ERROR` | `0x1` | Error message level. An error message is one that indicates the abnormal termination of the application and may require developer's handling. | `Logger` |
| <span id="const-LEVEL_WARNING"></span>`LEVEL_WARNING` | `0x2` | Warning 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` |
| <span id="const-LEVEL_INFO"></span>`LEVEL_INFO` | `0x4` | Informational message level. An informational message is one that includes certain information for developers to review. | `Logger` |
| <span id="const-LEVEL_TRACE"></span>`LEVEL_TRACE` | `0x8` | Tracing message level. A tracing message is one that reveals the code execution flow. | `Logger` |
| <span id="const-LEVEL_PROFILE"></span>`LEVEL_PROFILE` | `0x40` | Profiling message level. This indicates the message is for profiling purpose. | `Logger` |
| <span id="const-LEVEL_PROFILE_BEGIN"></span>`LEVEL_PROFILE_BEGIN` | `0x50` | Profiling message level. This indicates the message is for profiling purpose. It marks the beginning of a profiling block. | `Logger` |
| <span id="const-LEVEL_PROFILE_END"></span>`LEVEL_PROFILE_END` | `0x60` | Profiling message level. This indicates the message is for profiling purpose. It marks the end of a profiling block. | `Logger` |

## Property details

### $flushInterval <span id="property-flushInterval"></span>

```php
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()`](/docs/api/yii/log/logger/index.md#method-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()`](/docs/api/yii/log/logger/index.md#method-flush).

### $messages <span id="property-messages"></span>

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

Logged messages.

This property is managed by [`log()`](/docs/api/yii/log/logger/index.md#method-log) and [`flush()`](/docs/api/yii/log/logger/index.md#method-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.
]
```

### $profiling <span id="property-profiling"></span>

```php
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).

### $profilingAware <span id="property-profilingAware"></span>

```php
public bool $profilingAware = false
```

Whether the profiling-aware mode should be switched on.

If on, [`flush()`](/docs/api/yii/log/logger/index.md#method-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

### $traceLevel <span id="property-traceLevel"></span>

```php
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.

## Method details

### calculateTimings() <span id="method-calculateTimings"></span>

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

Calculates the elapsed time for the given log messages.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$messages` | `array<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.

### flush() <span id="method-flush"></span>

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

Flushes log messages from memory to targets.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$final` | `bool` | Whether this is a final call during a request. |

**Returns**

`mixed`

### getDbProfiling() <span id="method-getDbProfiling"></span>

```php
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.

### getElapsedTime() <span id="method-getElapsedTime"></span>

```php
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`](/docs/api/yii/baseyii/index.md) class file.

**Returns**

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

### getLevelName() <span id="method-getLevelName"></span>

```php
public static function getLevelName(int $level): string
```

Returns the text display of the specified level.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$level` | `int` | The message level, e.g. [`LEVEL_ERROR`](/docs/api/yii/log/logger/index.md#const-LEVEL_ERROR), [`LEVEL_WARNING`](/docs/api/yii/log/logger/index.md#const-LEVEL_WARNING). |

**Returns**

`string`: The text display of the level

### getProfiling() <span id="method-getProfiling"></span>

```php
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**

| Parameter | Type | Description |
| --- | --- | --- |
| `$categories` | `list<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'. |
| `$excludeCategories` | `list<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.

### init() <span id="method-init"></span>

```php
public function init(): mixed
```

Initializes the logger by registering [`flush()`](/docs/api/yii/log/logger/index.md#method-flush) as a shutdown function.

**Returns**

`mixed`

### log() <span id="method-log"></span>

```php
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`](/docs/api/yii/log/logger/index.md#property-traceLevel) is greater than 0, additional call stack information about
the application code will be logged as well.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$message` | `string\|array\|`[`Throwable`](https://www.php.net/manual/en/class.throwable.php)`\|`[`PsrMessage`](/docs/api/yii/log/psrmessage/index.md) | The message to be logged. This can be a simple string or a more complex data structure that will be handled by a [log target](/docs/api/yii/log/target/index.md). |
| `$level` | `int` | The 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`. |
| `$category` | `string` | The category of the message. |

**Returns**

`mixed`