PHP code example of samdark / yii2-psr-log-target

1. Go to this page and download the library: Download samdark/yii2-psr-log-target library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

samdark / yii2-psr-log-target example snippets


// $psrLogger should be an instance of PSR-3 compatible logger.
// As an example, we'll use Monolog to send log to Slack.
$psrLogger = new \Monolog\Logger('my_logger');
$psrLogger->pushHandler(new \Monolog\Handler\SlackHandler('slack_token', 'logs', null, true, null, \Monolog\Logger::DEBUG));

return [
    // ...
    'bootstrap' => ['log'],    
    // ...    
    'components' => [
        // ...        
        'log' => [
            'targets' => [
                [
                    'class' => 'samdark\log\PsrTarget',
                    'logger' => $psrLogger,
                    
                    // It is optional parameter. The message levels that this target is interested in.
                    // The parameter can be an array.
                    'levels' => ['info', yii\log\Logger::LEVEL_WARNING, Psr\Log\LogLevel::CRITICAL],
                    // It is optional parameter. Default value is false. If you use Yii log buffering, you see buffer write time, and not real timestamp.
                    // If you want write real time to logs, you can set addTimestampToContext as true and use timestamp from log event context.
                    'addTimestampToContext' => true,
                ],
                // ...
            ],
        ],
    ],
];

Yii::info('Info message');
Yii::error('Error message');

Yii::getLogger()->log('Critical message', Psr\Log\LogLevel::CRITICAL);
Yii::getLogger()->log('Alert message', Psr\Log\LogLevel::ALERT);

// $psrLogger should be an instance of PSR-3 compatible logger.
// As an example, we'll use Monolog to send log to Slack.
$psrLogger = new \Monolog\Logger('my_logger');

$psrLogger->pushProcessor(function($record) {
    if (isset($record['context']['timestamp'])) {
        $dateTime = DateTime::createFromFormat('U.u', $record['context']['timestamp']);
        $timeZone = $record['datetime']->getTimezone();
        $dateTime->setTimezone($timeZone);
        $record['datetime'] = $dateTime;

        unset($record['context']['timestamp']);
    }

    return $record;
});

Yii::error(new \samdark\log\PsrMessage("Critical message", [
    'custom' => 'context',
    'key' => 'value',
]));

Yii::getLogger()->log(new \samdark\log\PsrMessage("Critical message", [
    'important' => 'context'
]), Psr\Log\LogLevel::CRITICAL);

$psrLogger = new \Monolog\Logger('my_logger');
$psrLogger->pushProcessor(new \Monolog\Processor\PsrLogMessageProcessor());

Yii::debug(new \samdark\log\PsrMessage("Greetings from {fruit}", [
    'fruit' => 'banana'
]));