Logger
extends Component
in package
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:
- [[Yii::trace()]]
- [[Yii::error()]]
- [[Yii::warning()]]
- [[Yii::info()]]
- [[Yii::beginProfile()]]
- [[Yii::endProfile()]]
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 [[FileTarget|file]], [[EmailTarget|email]], or [[DbTarget|database]], with the help of the [[dispatcher]].
Tags
Table of Contents
Constants
- 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.
- LEVEL_INFO = 0x4
- Informational message level. An informational message is one that includes certain information for developers to review.
- LEVEL_PROFILE = 0x40
- Profiling message level. This indicates the message is for profiling purpose.
- LEVEL_PROFILE_BEGIN = 0x50
- Profiling message level. This indicates the message is for profiling purpose. It marks the beginning of a profiling block.
- LEVEL_PROFILE_END = 0x60
- Profiling message level. This indicates the message is for profiling purpose. It marks the end of a profiling block.
- LEVEL_TRACE = 0x8
- Tracing message level. A tracing message is one that reveals the code execution flow.
- 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.
Properties
- $behaviors : array<string|int, Behavior>
- $dbEventNames : array<string|int, mixed>
- $dbProfiling : array<string|int, mixed>
- $dispatcher : Dispatcher
- $elapsedTime : float
- $flushInterval : int
- $messages : array<string|int, mixed>
- $profiling : array<string|int, mixed>
- $profilingAware : bool
- $traceLevel : int
- $_behaviors : array<string|int, Behavior>|null
- $_events : array<string|int, mixed>
- $_eventWildcards : array<string|int, mixed>
Methods
- __call() : mixed
- Calls the named method which is not a class method.
- __clone() : mixed
- This method is called after the object is created by cloning an existing one.
- __construct() : mixed
- Constructor.
- __get() : mixed
- Returns the value of a component property.
- __isset() : bool
- Checks if a property is set, i.e. defined and not null.
- __set() : mixed
- Sets the value of a component property.
- __unset() : mixed
- Sets a component property to be null.
- attachBehavior() : Behavior
- Attaches a behavior to this component.
- attachBehaviors() : mixed
- Attaches a list of behaviors to the component.
- behaviors() : array<string|int, mixed>
- Returns a list of behaviors that this component should behave as.
- calculateTimings() : array<string|int, mixed>
- Calculates the elapsed time for the given log messages.
- canGetProperty() : bool
- Returns a value indicating whether a property can be read.
- canSetProperty() : bool
- Returns a value indicating whether a property can be set.
- className() : string
- Returns the fully qualified name of this class.
- detachBehavior() : Behavior|null
- Detaches a behavior from the component.
- detachBehaviors() : mixed
- Detaches all behaviors from the component.
- ensureBehaviors() : mixed
- Makes sure that the behaviors declared in [[behaviors()]] are attached to this component.
- flush() : mixed
- Flushes log messages from memory to targets.
- getBehavior() : Behavior|null
- Returns the named behavior object.
- getBehaviors() : array<string|int, Behavior>
- Returns all behaviors attached to this component.
- getDbProfiling() : array<string|int, mixed>
- Returns the statistical results of DB queries.
- getElapsedTime() : float
- Returns the total elapsed time since the start of the current request.
- getLevelName() : string
- Returns the text display of the specified level.
- getProfiling() : array<string|int, mixed>
- Returns the profiling results.
- hasEventHandlers() : bool
- Returns a value indicating whether there is any handler attached to the named event.
- hasMethod() : bool
- Returns a value indicating whether a method is defined.
- hasProperty() : bool
- Returns a value indicating whether a property is defined for this component.
- init() : mixed
- Initializes the logger by registering [[flush()]] as a shutdown function.
- log() : mixed
- Logs a message with the given type and category.
- off() : bool
- Detaches an existing event handler from this component.
- on() : mixed
- Attaches an event handler to an event.
- trigger() : mixed
- Triggers an event.
- attachBehaviorInternal() : Behavior
- Attaches a behavior to this component.
Constants
LEVEL_ERROR
Error message level. An error message is one that indicates the abnormal termination of the application and may require developer's handling.
public
mixed
LEVEL_ERROR
= 0x1
LEVEL_INFO
Informational message level. An informational message is one that includes certain information for developers to review.
public
mixed
LEVEL_INFO
= 0x4
LEVEL_PROFILE
Profiling message level. This indicates the message is for profiling purpose.
public
mixed
LEVEL_PROFILE
= 0x40
LEVEL_PROFILE_BEGIN
Profiling message level. This indicates the message is for profiling purpose. It marks the beginning of a profiling block.
public
mixed
LEVEL_PROFILE_BEGIN
= 0x50
LEVEL_PROFILE_END
Profiling message level. This indicates the message is for profiling purpose. It marks the end of a profiling block.
public
mixed
LEVEL_PROFILE_END
= 0x60
LEVEL_TRACE
Tracing message level. A tracing message is one that reveals the code execution flow.
public
mixed
LEVEL_TRACE
= 0x8
LEVEL_WARNING
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.
public
mixed
LEVEL_WARNING
= 0x2
Properties
$behaviors read-only
public
array<string|int, Behavior>
$behaviors
List of behaviors attached to this component.
$dbEventNames
public
array<string|int, mixed>
$dbEventNames
= ['yii\db\Command::query', 'yii\db\Command::execute']
of event names used to get statistical results of DB queries.
Tags
$dbProfiling read-only
public
array<string|int, mixed>
$dbProfiling
The first element indicates the number of SQL statements executed, and the second element the total time spent in SQL execution.
$dispatcher
public
Dispatcher
$dispatcher
the message dispatcher.
$elapsedTime read-only
public
float
$elapsedTime
The total elapsed time in seconds for current request.
$flushInterval
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()]].
$messages
public
array<string|int, mixed>
$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.
]
$profiling read-only
public
array<string|int, mixed>
$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.
$profilingAware
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.
Tags
$traceLevel
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.
$_behaviors
private
array<string|int, Behavior>|null
$_behaviors
the attached behaviors (behavior name => behavior). This is null
when not initialized.
$_events
private
array<string|int, mixed>
$_events
= []
the attached event handlers (event name => handlers)
$_eventWildcards
private
array<string|int, mixed>
$_eventWildcards
= []
the event handlers attached for wildcard patterns (event name wildcard => handlers)
Tags
Methods
__call()
Calls the named method which is not a class method.
public
__call(string $name, array<string|int, mixed> $params) : mixed
This method will check if any attached behavior has the named method and will execute it if available.
Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.
Parameters
- $name : string
-
the method name
- $params : array<string|int, mixed>
-
method parameters
Tags
Return values
mixed —the method return value
__clone()
This method is called after the object is created by cloning an existing one.
public
__clone() : mixed
It removes all behaviors because they are attached to the old object.
__construct()
Constructor.
public
__construct([array<string|int, mixed> $config = [] ]) : mixed
The default implementation does two things:
- Initializes the object with the given configuration
$config
. - Call [[init()]].
If this method is overridden in a child class, it is recommended that
- the last parameter of the constructor is a configuration array, like
$config
here. - call the parent implementation at the end of the constructor.
Parameters
- $config : array<string|int, mixed> = []
-
name-value pairs that will be used to initialize the object properties
__get()
Returns the value of a component property.
public
__get(string $name) : mixed
This method will check in the following order and act accordingly:
- a property defined by a getter: return the getter result
- a property of a behavior: return the behavior property value
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $value = $component->property;
.
Parameters
- $name : string
-
the property name
Tags
Return values
mixed —the property value or the value of a behavior's property
__isset()
Checks if a property is set, i.e. defined and not null.
public
__isset(string $name) : bool
This method will check in the following order and act accordingly:
- a property defined by a setter: return whether the property is set
- a property of a behavior: return whether the property is set
- return
false
for non existing properties
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing isset($component->property)
.
Parameters
- $name : string
-
the property name or the event name
Tags
Return values
bool —whether the named property is set
__set()
Sets the value of a component property.
public
__set(string $name, mixed $value) : mixed
This method will check in the following order and act accordingly:
- a property defined by a setter: set the property value
- an event in the format of "on xyz": attach the handler to the event "xyz"
- a behavior in the format of "as xyz": attach the behavior named as "xyz"
- a property of a behavior: set the behavior property value
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $component->property = $value;
.
Parameters
- $name : string
-
the property name or the event name
- $value : mixed
-
the property value
Tags
__unset()
Sets a component property to be null.
public
__unset(string $name) : mixed
This method will check in the following order and act accordingly:
- a property defined by a setter: set the property value to be null
- a property of a behavior: set the property value to be null
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing unset($component->property)
.
Parameters
- $name : string
-
the property name
Tags
attachBehavior()
Attaches a behavior to this component.
public
attachBehavior(string $name, string|array<string|int, mixed>|Behavior $behavior) : Behavior
This method will create the behavior object based on the given configuration. After that, the behavior object will be attached to this component by calling the [[Behavior::attach()]] method.
Parameters
- $name : string
-
the name of the behavior.
- $behavior : string|array<string|int, mixed>|Behavior
-
the behavior configuration. This can be one of the following:
- a [[Behavior]] object
- a string specifying the behavior class
- an object configuration array that will be passed to [[Yii::createObject()]] to create the behavior object.
Tags
Return values
Behavior —the behavior object
attachBehaviors()
Attaches a list of behaviors to the component.
public
attachBehaviors(array<string|int, mixed> $behaviors) : mixed
Each behavior is indexed by its name and should be a [[Behavior]] object, a string specifying the behavior class, or an configuration array for creating the behavior.
Parameters
- $behaviors : array<string|int, mixed>
-
list of behaviors to be attached to the component
Tags
behaviors()
Returns a list of behaviors that this component should behave as.
public
behaviors() : array<string|int, mixed>
Child classes may override this method to specify the behaviors they want to behave as.
The return value of this method should be an array of behavior objects or configurations indexed by behavior names. A behavior configuration can be either a string specifying the behavior class or an array of the following structure:
'behaviorName' => [
'class' => 'BehaviorClass',
'property1' => 'value1',
'property2' => 'value2',
]
Note that a behavior class must extend from [[Behavior]]. Behaviors can be attached using a name or anonymously. When a name is used as the array key, using this name, the behavior can later be retrieved using [[getBehavior()]] or be detached using [[detachBehavior()]]. Anonymous behaviors can not be retrieved or detached.
Behaviors declared in this method will be attached to the component automatically (on demand).
Return values
array<string|int, mixed> —the behavior configurations.
calculateTimings()
Calculates the elapsed time for the given log messages.
public
calculateTimings(array<string|int, mixed> $messages) : array<string|int, mixed>
Parameters
- $messages : array<string|int, mixed>
-
the log messages obtained from profiling
Return values
array<string|int, mixed> —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.
canGetProperty()
Returns a value indicating whether a property can be read.
public
canGetProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool
A property can be read if:
- the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true); - an attached behavior has a readable property of the given name (when
$checkBehaviors
is true).
Parameters
- $name : string
-
the property name
- $checkVars : bool = true
-
whether to treat member variables as properties
- $checkBehaviors : bool = true
-
whether to treat behaviors' properties as properties of this component
Tags
Return values
bool —whether the property can be read
canSetProperty()
Returns a value indicating whether a property can be set.
public
canSetProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool
A property can be written if:
- the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true); - an attached behavior has a writable property of the given name (when
$checkBehaviors
is true).
Parameters
- $name : string
-
the property name
- $checkVars : bool = true
-
whether to treat member variables as properties
- $checkBehaviors : bool = true
-
whether to treat behaviors' properties as properties of this component
Tags
Return values
bool —whether the property can be written
className()
Returns the fully qualified name of this class.
public
static className() : string
Tags
Return values
string —the fully qualified name of this class.
detachBehavior()
Detaches a behavior from the component.
public
detachBehavior(string $name) : Behavior|null
The behavior's [[Behavior::detach()]] method will be invoked.
Parameters
- $name : string
-
the behavior's name.
Return values
Behavior|null —the detached behavior. Null if the behavior does not exist.
detachBehaviors()
Detaches all behaviors from the component.
public
detachBehaviors() : mixed
ensureBehaviors()
Makes sure that the behaviors declared in [[behaviors()]] are attached to this component.
public
ensureBehaviors() : mixed
flush()
Flushes log messages from memory to targets.
public
flush([bool $final = false ]) : mixed
Parameters
- $final : bool = false
-
whether this is a final call during a request.
getBehavior()
Returns the named behavior object.
public
getBehavior(string $name) : Behavior|null
Parameters
- $name : string
-
the behavior name
Return values
Behavior|null —the behavior object, or null if the behavior does not exist
getBehaviors()
Returns all behaviors attached to this component.
public
getBehaviors() : array<string|int, Behavior>
Return values
array<string|int, Behavior> —list of behaviors attached to this component
getDbProfiling()
Returns the statistical results of DB queries.
public
getDbProfiling() : array<string|int, mixed>
The results returned include the number of SQL statements executed and the total time spent.
Return values
array<string|int, mixed> —the first element indicates the number of SQL statements executed, and the second element the total time spent in SQL execution.
getElapsedTime()
Returns the total elapsed time since the start of the current request.
public
getElapsedTime() : float
This method calculates the difference between now and the timestamp
defined by constant YII_BEGIN_TIME
which is evaluated at the beginning
of [[\yii\BaseYii]] class file.
Return values
float —the total elapsed time in seconds for current request.
getLevelName()
Returns the text display of the specified level.
public
static getLevelName(int $level) : string
Parameters
- $level : int
-
the message level, e.g. [[LEVEL_ERROR]], [[LEVEL_WARNING]].
Return values
string —the text display of the level
getProfiling()
Returns the profiling results.
public
getProfiling([array<string|int, mixed> $categories = [] ][, array<string|int, mixed> $excludeCategories = [] ]) : array<string|int, mixed>
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
- $categories : array<string|int, mixed> = []
-
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 : array<string|int, mixed> = []
-
list of categories that you want to exclude
Return values
array<string|int, mixed> —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.
hasEventHandlers()
Returns a value indicating whether there is any handler attached to the named event.
public
hasEventHandlers(string $name) : bool
Parameters
- $name : string
-
the event name
Return values
bool —whether there is any handler attached to the event.
hasMethod()
Returns a value indicating whether a method is defined.
public
hasMethod(string $name[, bool $checkBehaviors = true ]) : bool
A method is defined if:
- the class has a method with the specified name
- an attached behavior has a method with the given name (when
$checkBehaviors
is true).
Parameters
- $name : string
-
the property name
- $checkBehaviors : bool = true
-
whether to treat behaviors' methods as methods of this component
Return values
bool —whether the method is defined
hasProperty()
Returns a value indicating whether a property is defined for this component.
public
hasProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool
A property is defined if:
- the class has a getter or setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true); - an attached behavior has a property of the given name (when
$checkBehaviors
is true).
Parameters
- $name : string
-
the property name
- $checkVars : bool = true
-
whether to treat member variables as properties
- $checkBehaviors : bool = true
-
whether to treat behaviors' properties as properties of this component
Tags
Return values
bool —whether the property is defined
init()
Initializes the logger by registering [[flush()]] as a shutdown function.
public
init() : mixed
log()
Logs a message with the given type and category.
public
log(string|array<string|int, mixed> $message, int $level[, string $category = 'application' ]) : mixed
If [[traceLevel]] is greater than 0, additional call stack information about the application code will be logged as well.
Parameters
- $message : string|array<string|int, mixed>
-
the message to be logged. This can be a simple string or a more complex data structure that will be handled by a [[Target|log target]].
- $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 = 'application'
-
the category of the message.
off()
Detaches an existing event handler from this component.
public
off(string $name[, callable|null $handler = null ]) : bool
This method is the opposite of [[on()]].
Note: in case wildcard pattern is passed for event name, only the handlers registered with this wildcard will be removed, while handlers registered with plain names matching this wildcard will remain.
Parameters
- $name : string
-
event name
- $handler : callable|null = null
-
the event handler to be removed. If it is null, all handlers attached to the named event will be removed.
Tags
Return values
bool —if a handler is found and detached
on()
Attaches an event handler to an event.
public
on(string $name, callable $handler[, mixed $data = null ][, bool $append = true ]) : mixed
The event handler must be a valid PHP callback. The following are some examples:
function ($event) { ... } // anonymous function
[$object, 'handleClick'] // $object->handleClick()
['Page', 'handleClick'] // Page::handleClick()
'handleClick' // global function handleClick()
The event handler must be defined with the following signature,
function ($event)
where $event
is an [[Event]] object which includes parameters associated with the event.
Since 2.0.14 you can specify event name as a wildcard pattern:
$component->on('event.group.*', function ($event) {
Yii::trace($event->name . ' is triggered.');
});
Parameters
- $name : string
-
the event name
- $handler : callable
-
the event handler
- $data : mixed = null
-
the data to be passed to the event handler when the event is triggered. When the event handler is invoked, this data can be accessed via [[Event::data]].
- $append : bool = true
-
whether to append new event handler to the end of the existing handler list. If false, the new handler will be inserted at the beginning of the existing handler list.
Tags
trigger()
Triggers an event.
public
trigger(string $name[, Event|null $event = null ]) : mixed
This method represents the happening of an event. It invokes all attached handlers for the event including class-level handlers.
Parameters
- $name : string
-
the event name
- $event : Event|null = null
-
the event instance. If not set, a default [[Event]] object will be created.
attachBehaviorInternal()
Attaches a behavior to this component.
private
attachBehaviorInternal(string|int $name, string|array<string|int, mixed>|Behavior $behavior) : Behavior
Parameters
- $name : string|int
-
the name of the behavior. If this is an integer, it means the behavior is an anonymous one. Otherwise, the behavior is a named one and any existing behavior with the same name will be detached first.
- $behavior : string|array<string|int, mixed>|Behavior
-
the behavior to be attached
Return values
Behavior —the attached behavior.