glopgar / monolog-timer-processor

为 Monolog 添加时间信息的消息上下文的处理器

v0.1.1 2017-12-08 20:53 UTC

This package is not auto-updated.

Last update: 2024-09-29 04:37:20 UTC


README

monolog 提供的处理器,允许通过在消息上下文中添加计时器信息来计时代码片段。

基本用法

$logger = new \Monolog\Logger('timer.example');
$logger->pushHandler(new \Monolog\Handler\StreamHandler('php://stdout'));

$logger->pushProcessor(new Glopgar\Monolog\Processor\TimerProcessor());

// start a timer with name: 'exampleProcess'
$logger->debug('Process started', ['timer' => ['exampleProcess' => 'start']]);
usleep(1500000);
// stop the timer
$logger->debug('Process ended', ['timer' => ['exampleProcess' => 'stop']]);
$logger->debug('Process started again', ['timer' => ['exampleProcess' => 'start']]);
usleep(2300000);
$logger->debug('Process ended', ['timer' => ['exampleProcess' => 'stop']]);

日志输出

[2016-08-10 17:07:26] timer.example.DEBUG: Process started {"timer":{"exampleProcess":"start"}} []
[2016-08-10 17:07:27] timer.example.DEBUG: Process ended {"timer":{"exampleProcess":{"time":"1.50 s.","totalTime":"1.50 s.","count":1}}} []
[2016-08-10 17:07:27] timer.example.DEBUG: Process started again {"timer":{"exampleProcess":"start"}} []
[2016-08-10 17:07:30] timer.example.DEBUG: Process ended {"timer":{"exampleProcess":{"time":"2.30 s.","totalTime":"3.81 s.","count":2}}} []

多个计时器

您可以在每条日志行上启动或停止多个计时器

$logger->debug('Processes started', ['timer' => ['process1' => 'start', 'process2' => 'start']]);
sleep(1);
$logger->debug('Process ended, process started', ['timer' => ['process1' => 'stop', 'process3' => 'start']]);
sleep(1);
$logger->debug('Processes ended', ['timer' => ['process2' => 'stop', 'process3' => 'stop']]);

日志输出

[2016-08-10 17:17:26] timer.example.DEBUG: Processes started {"timer":{"process1":"start","process2":"start"}} []
[2016-08-10 17:17:27] timer.example.DEBUG: Process ended, process started {"timer":{"process1":{"time":"1.00","totalTime":"1.00","count":1},"process3":"start"}} []
[2016-08-10 17:17:28] timer.example.DEBUG: Processes ended {"timer":{"process2":{"time":"2.01","totalTime":"2.01","count":1},"process3":{"time":"1.00","totalTime":"1.00","count":1}}} []

获取计时器信息

您可以使用 TimerProcessor::getTimers 方法获取所有计时器信息的数组

这可以在过程结束时记录计时器总时间很有用

$timers = $processor->getTimers();
foreach ($timers as $timer => $info) {
    $logger->notice('%s executed %d times, total time: %.2f s.', $timer, $info['count'], $info['totalTime']);
}

github:glopgar