This package provides a PSR-3 compatible logging library. It is used extensively in the Yii Framework but it can also be used as a separate package.
The logger sends or passes messages to multiple targets. Each target may filter these messages according to their severity level, and category, and then export them to some medium such as a file, an email or a syslog.
- PHP 8.0 or higher.
The package can be installed with Composer:
composer require yiisoft/logCreating a logger:
/**
* List of class instances that extend the \Yiisoft\Log\Target abstract class.
*
* @var \Yiisoft\Log\Target[] $targets
*/
$logger = new \Yiisoft\Log\Logger($targets);Writing logs:
$logger->emergency('Emergency message', ['key' => 'value']);
$logger->alert('Alert message', ['key' => 'value']);
$logger->critical('Critical message', ['key' => 'value']);
$logger->warning('Warning message', ['key' => 'value']);
$logger->notice('Notice message', ['key' => 'value']);
$logger->info('Info message', ['key' => 'value']);
$logger->debug('Debug message', ['key' => 'value']);The logger is PSR-3 compatible and supports message placeholders with additional enhancements. Placeholders in the message string are replaced with values from the context array:
$logger->info('User {username} logged in from {ip}', [
'username' => 'john_doe',
'ip' => '192.168.1.1',
]);
// Logs: "User john_doe logged in from 192.168.1.1"Placeholder names must be enclosed in curly braces {placeholder} and correspond to keys in the context array.
As an enhancement beyond the PSR-3 specification, the logger supports accessing nested array values using dot notation:
$logger->info('User {user.name} with ID {user.id} performed action', [
'user' => [
'id' => 123,
'name' => 'John Doe',
],
]);
// Logs: "User John Doe with ID 123 performed action"Placeholders can handle various data types:
- Strings and numbers: Rendered as-is
- null: Rendered as an empty string
- Stringable objects: Converted using
__toString() - Arrays and objects: Rendered as formatted strings using VarDumper
$logger->warning('Failed to process order {order_id}', [
'order_id' => 12345,
]);
$logger->error('Invalid data: {data}', [
'data' => ['key' => 'value'],
]);The context array is preserved in the log message and can be used by log targets for filtering, formatting, or exporting. This allows you to pass structured data alongside human-readable messages:
$logger->info('Payment processed', [
'amount' => 99.99,
'currency' => 'USD',
'transaction_id' => 'txn_123456',
'user_id' => 42,
]);Log messages are collected and stored in memory. To limit memory consumption, the logger will flush
the recorded messages to the log targets each time a certain number of log messages accumulate.
You can customize this number by calling the \Yiisoft\Log\Logger::setFlushInterval() method:
$logger->setFlushInterval(100); // default is 1000Each log target also collects and stores messages in memory.
Message exporting in a target follows the same principle as in the logger.
To change the number of stored messages, call the \Yiisoft\Log\Target::setExportInterval() method:
$target->setExportInterval(100); // default is 1000Note: All message flushing and exporting also occurs when the application ends.
This package contains two targets:
Yiisoft\Log\PsrTarget- passes log messages to another PSR-3 compatible logger.Yiisoft\Log\StreamTarget- writes log messages to the specified output stream.
Extra logging targets are implemented as separate packages:
Context providers are used to provide additional context data for log messages. You can define your own context provider
in the Logger constructor:
$logger = new \Yiisoft\Log\Logger(contextProvider: $myContextProvider);Out of the box, the following context providers are available:
SystemContextProvider— adds system information (time, memory usage, trace, default category);CommonContextProvider— adds common data;CompositeContextProvider— allows combining multiple context providers.
By default, the logger uses the built-in SystemContextProvider.
The SystemContextProvider adds the following data to the context:
time— current Unix timestamp with microseconds (float value);trace— array of call stack information;memory— memory usage in bytes.category— category of the log message (always "application").
Yiisoft\Log\ContextProvider\SystemContextProvider constructor parameters:
traceLevel— how much call stack information (file name and line number) should be logged for each log message. If the traceLevel is greater than 0, a similar number of call stacks will be logged at most. Note that only application call stacks are counted.excludedTracePaths— array of paths to exclude from tracing when tracing is enabled withtraceLevel.
An example of custom parameters' usage:
$logger = new \Yiisoft\Log\Logger(
contextProvider: new Yiisoft\Log\ContextProvider\SystemContextProvider(
traceLevel: 3,
excludedTracePaths: [
'/vendor/yiisoft/di',
],
),
);The CommonContextProvider allows the adding of additional common information to the log context, for example:
$logger = new \Yiisoft\Log\Logger(
contextProvider: new Yiisoft\Log\ContextProvider\CommonContextProvider([
'environment' => 'production',
]),
);The CompositeContextProvider allows the combining of multiple context providers into one, for example:
$logger = new \Yiisoft\Log\Logger(
contextProvider: new Yiisoft\Log\ContextProvider\CompositeContextProvider(
new Yiisoft\Log\ContextProvider\SystemContextProvider(),
new Yiisoft\Log\ContextProvider\CommonContextProvider(['environment' => 'production'])
),
);In a Yii 3 application, Psr\Log\LoggerInterface is resolved through the DI container.
To use Yiisoft\Log\Logger as the implementation, add the binding to your application's DI config
(e.g. config/common/di/logger.php):
use Psr\Log\LoggerInterface;
use Yiisoft\Definitions\ReferencesArray;
use Yiisoft\Log\Logger;
use Yiisoft\Log\StreamTarget;
use Yiisoft\Log\Target\File\FileTarget;
return [
LoggerInterface::class => [
'class' => Logger::class,
'__construct()' => [
'targets' => ReferencesArray::from([
FileTarget::class,
StreamTarget::class,
]),
],
],
];This is the same pattern used in yiisoft/demo-blog.
Each target listed in ReferencesArray::from() is resolved by the DI container as a separate service.
Target packages like yiisoft/log-target-file ship their
own di.php and params.php configs that are merged automatically by the
config plugin, so FileTarget works out of the box with
default settings (writes to @runtime/logs/app.log with rotation). StreamTarget from this package
writes to php://stdout by default and requires no extra configuration.
To use only StreamTarget without the file target package:
use Psr\Log\LoggerInterface;
use Yiisoft\Definitions\ReferencesArray;
use Yiisoft\Log\Logger;
use Yiisoft\Log\StreamTarget;
return [
LoggerInterface::class => [
'class' => Logger::class,
'__construct()' => [
'targets' => ReferencesArray::from([
StreamTarget::class,
]),
],
],
];When using the yiisoft/config plugin, the shipped event configs are loaded automatically.
The package provides events-web.php and events-console.php files that define event handlers to flush logs after the HTTP response
is emitted and when a console command terminates.
If you need help or have a question, the Yii Forum is available. You may also check out other Yii Community Resources.
The Yii Logging Library is free software. It is released under the terms of the BSD License.
Please see LICENSE for more information.
Maintained by Yii Software.