Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
93.24% covered (success)
93.24%
69 / 74
50.00% covered (danger)
50.00%
3 / 6
CRAP
0.00% covered (danger)
0.00%
0 / 1
LegacyHandler
93.24% covered (success)
93.24%
69 / 74
50.00% covered (danger)
50.00%
3 / 6
25.19
0.00% covered (danger)
0.00%
0 / 1
 __construct
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
2.03
 openSink
96.97% covered (success)
96.97%
32 / 33
0.00% covered (danger)
0.00%
0 / 1
8
 errorTrap
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 useUdp
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 write
89.66% covered (warning)
89.66%
26 / 29
0.00% covered (danger)
0.00%
0 / 1
10.11
 close
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @file
5 */
6
7namespace MediaWiki\Logger\Monolog;
8
9use LogicException;
10use MediaWiki\Logger\LegacyLogger;
11use Monolog\Handler\AbstractProcessingHandler;
12use Monolog\Level;
13use Monolog\LogRecord;
14use Socket;
15use UnexpectedValueException;
16use Wikimedia\ScopedCallback;
17
18/**
19 * Monolog imitation of MediaWiki\Logger\LegacyLogger
20 *
21 * This replicates the behavior of LegacyLogger, which in turn replicates
22 * MediaWiki's former wfErrorLog() function.
23 *
24 * The main use case of the LegacyHandler is to enable adoption of Monolog
25 * features (such as alternate formatters, extra processors, and enabling multiple
26 * destinations/handlers at the same time), where one of the handlers (this one)
27 * essentiallly does what the LegacySpi would do if you hadn't enabled
28 * MonologSpi. In particular: writing to a file like $wgDebugLogFile,
29 * and sending messages to a PHP stream or udp2log server.
30 *
31 * For udp2log output, the stream specification must have the form:
32 * "udp://HOST:PORT[/PREFIX]"
33 * where:
34 *
35 * - HOST: IPv4, IPv6 or hostname
36 * - PORT: server port
37 * - PREFIX: optional (but recommended) prefix telling udp2log how to route
38 *   the log event. The special prefix "{channel}" will use the log event's
39 *   channel as the prefix value.
40 *
41 * When not targeting a udp2log server, this class will act as a drop-in
42 * replacement for \Monolog\Handler\StreamHandler.
43 *
44 * @since 1.25
45 * @ingroup Debug
46 * @copyright © 2013 Wikimedia Foundation and contributors
47 */
48class LegacyHandler extends AbstractProcessingHandler {
49
50    private static int $limit = 65507;
51
52    /**
53     * Log sink descriptor
54     * @var string
55     */
56    protected $uri;
57
58    /**
59     * Filter log events using legacy rules
60     * @var bool
61     */
62    protected $useLegacyFilter;
63
64    /**
65     * Log sink
66     * @var Socket|resource|null
67     */
68    protected $sink;
69
70    /**
71     * @var string|null
72     */
73    protected $error;
74
75    /**
76     * @var string
77     */
78    protected $host;
79
80    /**
81     * @var int
82     */
83    protected $port;
84
85    /**
86     * @var string
87     */
88    protected $prefix;
89
90    /**
91     * @param string $stream Stream URI
92     * @param bool $useLegacyFilter Filter log events using legacy rules
93     * @param int|string|Level $level Minimum logging level that will trigger handler
94     * @param bool $bubble Can handled messages bubble up the handler stack?
95     */
96    public function __construct(
97        $stream,
98        $useLegacyFilter = false,
99        $level = Level::Debug,
100        $bubble = true
101    ) {
102        parent::__construct( $level, $bubble );
103        $this->uri = $stream;
104        $this->useLegacyFilter = $useLegacyFilter;
105
106        // macOS enforces a strict UDP maximum datagram size of 9216 bytes.
107        if ( PHP_OS_FAMILY === 'Darwin' ) {
108            self::$limit = 9216;
109        }
110    }
111
112    /**
113     * Open the log sink described by our stream URI.
114     */
115    protected function openSink() {
116        if ( !$this->uri ) {
117            throw new LogicException(
118                'Missing stream uri, the stream can not be opened.' );
119        }
120        $this->error = null;
121        set_error_handler( $this->errorTrap( ... ) );
122        $scopedErrorHandlerRestore = new ScopedCallback( restore_error_handler( ... ) );
123
124        if ( str_starts_with( $this->uri, 'udp:' ) ) {
125            $parsed = parse_url( $this->uri );
126            if ( !isset( $parsed['host'] ) ) {
127                throw new UnexpectedValueException( sprintf(
128                    'Udp transport "%s" must specify a host', $this->uri
129                ) );
130            }
131            if ( !isset( $parsed['port'] ) ) {
132                throw new UnexpectedValueException( sprintf(
133                    'Udp transport "%s" must specify a port', $this->uri
134                ) );
135            }
136
137            $this->host = $parsed['host'];
138            $this->port = $parsed['port'];
139            $this->prefix = '';
140
141            if ( isset( $parsed['path'] ) ) {
142                $this->prefix = ltrim( $parsed['path'], '/' );
143            }
144
145            if ( filter_var( $this->host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 ) ) {
146                $domain = AF_INET6;
147
148            } else {
149                $domain = AF_INET;
150            }
151
152            $this->sink = socket_create( $domain, SOCK_DGRAM, SOL_UDP );
153
154        } else {
155            $this->sink = fopen( $this->uri, 'a' );
156        }
157        ScopedCallback::consume( $scopedErrorHandlerRestore );
158
159        if ( !$this->sink ) {
160            $this->sink = null;
161            throw new UnexpectedValueException( sprintf(
162                'The stream or file "%s" could not be opened: %s',
163                // @phan-suppress-next-line PhanTypeMismatchArgumentInternalProbablyReal Set by error handler
164                $this->uri, $this->error
165            ) );
166        }
167    }
168
169    /**
170     * Custom error handler.
171     * @param int $code Error number
172     * @param string $msg Error message
173     */
174    protected function errorTrap( $code, $msg ) {
175        $this->error = $msg;
176    }
177
178    /**
179     * Should we use UDP to send messages to the sink?
180     * @return bool
181     */
182    protected function useUdp() {
183        return $this->host !== null;
184    }
185
186    protected function write( LogRecord $record ): void {
187        if ( $this->useLegacyFilter &&
188            !LegacyLogger::shouldEmit(
189                $record->channel, $record->message,
190                $record->level->value, $record
191        ) ) {
192            // Do not write record if we are enforcing legacy rules and they
193            // do not pass this message. This used to be done in isHandling(),
194            // but Monolog 1.12.0 made a breaking change that removed access
195            // to the needed channel and context information.
196            return;
197        }
198
199        if ( $this->sink === null ) {
200            $this->openSink();
201        }
202
203        $text = (string)$record->formatted;
204        if ( $this->useUdp() ) {
205            // Clean it up for the multiplexer
206            if ( $this->prefix !== '' ) {
207                $leader = ( $this->prefix === '{channel}' ) ?
208                    $record->channel : $this->prefix;
209                $text = preg_replace( '/^/m', "{$leader} ", $text );
210
211                // Limit to 64 KiB
212                if ( strlen( $text ) > self::$limit - 1 ) {
213                    $text = substr( $text, 0, self::$limit - 1 );
214                }
215
216                if ( !str_ends_with( $text, "\n" ) ) {
217                    $text .= "\n";
218                }
219
220            } elseif ( strlen( $text ) > self::$limit ) {
221                $text = substr( $text, 0, self::$limit );
222            }
223
224            socket_sendto(
225                $this->sink,
226                $text,
227                strlen( $text ),
228                0,
229                $this->host,
230                $this->port
231            );
232
233        } else {
234            fwrite( $this->sink, $text );
235        }
236    }
237
238    public function close(): void {
239        if ( $this->sink ) {
240            if ( $this->useUdp() ) {
241                socket_close( $this->sink );
242            } else {
243                fclose( $this->sink );
244            }
245        }
246        $this->sink = null;
247    }
248}