| 1 |
<?php |
| 2 |
|
| 3 |
namespace MediaWiki\Logger; |
| 4 |
|
| 5 |
use Psr\Log\AbstractLogger; |
| 6 |
use Psr\Log\LoggerInterface; |
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
class LogCapturingSpi implements Spi { |
| 18 |
|
| 19 |
private $singletons; |
| 20 |
|
| 21 |
private $inner; |
| 22 |
|
| 23 |
private $logs = []; |
| 24 |
|
| 25 |
public function __construct( Spi $inner ) { |
| 26 |
$this->inner = $inner; |
| 27 |
} |
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
public function getLogs() { |
| 33 |
return $this->logs; |
| 34 |
} |
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
public function getLogger( $channel ) { |
| 41 |
if ( !isset( $this->singletons[$channel] ) ) { |
| 42 |
$this->singletons[$channel] = $this->createLogger( $channel ); |
| 43 |
} |
| 44 |
return $this->singletons[$channel]; |
| 45 |
} |
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
public function capture( $log ) { |
| 51 |
$this->logs[] = $log; |
| 52 |
} |
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
private function createLogger( $channel ) { |
| 59 |
$inner = $this->inner->getLogger( $channel ); |
| 60 |
return new class( $channel, $inner, $this ) extends AbstractLogger { |
| 61 |
|
| 62 |
private $channel; |
| 63 |
|
| 64 |
private $logger; |
| 65 |
|
| 66 |
private $parent; |
| 67 |
|
| 68 |
public function __construct( $channel, LoggerInterface $logger, LogCapturingSpi $parent ) { |
| 69 |
$this->channel = $channel; |
| 70 |
$this->logger = $logger; |
| 71 |
$this->parent = $parent; |
| 72 |
} |
| 73 |
|
| 74 |
public function log( $level, $message, array $context = [] ): void { |
| 75 |
$this->parent->capture( [ |
| 76 |
'channel' => $this->channel, |
| 77 |
'level' => $level, |
| 78 |
'message' => $message, |
| 79 |
'context' => $context |
| 80 |
] ); |
| 81 |
$this->logger->log( $level, $message, $context ); |
| 82 |
} |
| 83 |
}; |
| 84 |
} |
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
public function getInnerSpi(): Spi { |
| 91 |
return $this->inner; |
| 92 |
} |
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
public function setLoggerForTest( $channel, ?LoggerInterface $logger = null ) { |
| 101 |
$ret = $this->singletons[$channel] ?? null; |
| 102 |
$this->singletons[$channel] = $logger; |
| 103 |
return $ret; |
| 104 |
} |
| 105 |
} |