3 namespace Mediawiki\Logger
;
5 use Psr\Log\AbstractLogger
;
6 use Psr\Log\LoggerInterface
;
9 * Wraps another spi to capture all logs generated. This can be
10 * used, for example, to collect all logs generated during a
11 * unit test and report them when the test fails.
13 class LogCapturingSpi
implements Spi
{
14 /** @var LoggerInterface[] */
21 public function __construct( Spi
$inner ) {
22 $this->inner
= $inner;
28 public function getLogs() {
33 * @param string $channel
34 * @return LoggerInterface
36 public function getLogger( $channel ) {
37 if ( !isset( $this->singletons
[$channel] ) ) {
38 $this->singletons
[$channel] = $this->createLogger( $channel );
40 return $this->singletons
[$channel];
46 public function capture( $log ) {
51 * @param string $channel
52 * @return LoggerInterface
54 private function createLogger( $channel ) {
55 $inner = $this->inner
->getLogger( $channel );
56 return new class( $channel, $inner, $this ) extends AbstractLogger
{
59 /** @var LoggerInterface */
61 /** @var LogCapturingSpi */
64 // phpcs:ignore MediaWiki.Usage.NestedFunctions.NestedFunction
65 public function __construct( $channel, LoggerInterface
$logger, LogCapturingSpi
$parent ) {
66 $this->channel
= $channel;
67 $this->logger
= $logger;
68 $this->parent
= $parent;
71 // phpcs:ignore MediaWiki.Usage.NestedFunctions.NestedFunction
72 public function log( $level, $message, array $context = [] ) {
73 $this->parent
->capture( [
74 'channel' => $this->channel
,
76 'message' => $message,
79 $this->logger
->log( $level, $message, $context );