Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
63 / 63
100.00% covered (success)
100.00%
5 / 5
CRAP
100.00% covered (success)
100.00%
1 / 1
LineFormatter
100.00% covered (success)
100.00%
63 / 63
100.00% covered (success)
100.00%
5 / 5
19
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 format
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
6
 normalizeException
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 exceptionAsArray
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
2
 normalizeExceptionArray
100.00% covered (success)
100.00%
28 / 28
100.00% covered (success)
100.00%
1 / 1
9
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @file
5 */
6
7namespace MediaWiki\Logger\Monolog;
8
9use Error;
10use MediaWiki\Exception\MWExceptionHandler;
11use Monolog\Formatter\LineFormatter as MonologLineFormatter;
12use Monolog\LogRecord;
13use Throwable;
14
15/**
16 * Formats incoming records into a one-line string.
17 *
18 * An 'exception' in the log record's context will be treated specially.
19 * It will be output for an '%exception%' placeholder in the format and
20 * excluded from '%context%' output if the '%exception%' placeholder is
21 * present.
22 *
23 * Throwables that are logged with this formatter will optional have their
24 * stack traces appended. If that is done, MWExceptionHandler::redactedTrace()
25 * will be used to redact the trace information.
26 *
27 * @since 1.26
28 * @ingroup Debug
29 * @copyright © 2015 Wikimedia Foundation and contributors
30 */
31class LineFormatter extends MonologLineFormatter {
32
33    /**
34     * @param string|null $format The format of the message
35     * @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format
36     * @param bool $allowInlineLineBreaks Whether to allow inline line breaks in log entries
37     * @param bool $ignoreEmptyContextAndExtra
38     * @param bool $includeStacktraces
39     */
40    public function __construct(
41        $format = null, $dateFormat = null, $allowInlineLineBreaks = false,
42        $ignoreEmptyContextAndExtra = false, $includeStacktraces = false
43    ) {
44        parent::__construct(
45            $format, $dateFormat, $allowInlineLineBreaks,
46            $ignoreEmptyContextAndExtra
47        );
48        $this->includeStacktraces( $includeStacktraces );
49    }
50
51    /**
52     * @inheritDoc
53     */
54    public function format( LogRecord $record ): string {
55        // A Monolog 3 LogRecord's context is readonly, so drop keys on a copy
56        // and rebuild the record before delegating; mutating $record->context
57        // in place would silently no-op (T397070).
58        $context = $record->context;
59
60        // Drop the 'private' flag from the context
61        unset( $context['private'] );
62
63        // Handle throwables specially: pretty format and remove from context
64        // Will be output for a '%exception%' placeholder in format
65        $prettyException = '';
66        if ( isset( $context['exception'] ) &&
67            str_contains( $this->format, '%exception%' )
68        ) {
69            $e = $context['exception'];
70            unset( $context['exception'] );
71
72            if ( $e instanceof Throwable ) {
73                $prettyException = $this->normalizeException( $e );
74            } elseif ( is_array( $e ) ) {
75                $prettyException = $this->normalizeExceptionArray( $e );
76            } else {
77                $prettyException = $this->stringify( $e );
78            }
79        }
80
81        $record = $record->with( context: $context );
82
83        $output = parent::format( $record );
84
85        if ( str_contains( $output, '%exception%' ) ) {
86            $output = str_replace( '%exception%', $prettyException, $output );
87        }
88        return $output;
89    }
90
91    /**
92     * Convert a Throwable to a string.
93     *
94     * @param Throwable $e
95     * @param int $depth
96     * @return string
97     */
98    protected function normalizeException( Throwable $e, int $depth = 0 ): string {
99        // Can't use typehint. Must match Monolog\Formatter\LineFormatter::normalizeException($e)
100        return $this->normalizeExceptionArray( $this->exceptionAsArray( $e ) );
101    }
102
103    /**
104     * Convert a throwable to an array of structured data.
105     *
106     * @param Throwable $e
107     * @return array
108     */
109    protected function exceptionAsArray( Throwable $e ) {
110        $out = [
111            'class' => get_class( $e ),
112            'message' => $e->getMessage(),
113            'code' => $e->getCode(),
114            'file' => $e->getFile(),
115            'line' => $e->getLine(),
116            'trace' => MWExceptionHandler::redactTrace( $e->getTrace() ),
117        ];
118
119        $prev = $e->getPrevious();
120        if ( $prev ) {
121            $out['previous'] = $this->exceptionAsArray( $prev );
122        }
123
124        return $out;
125    }
126
127    /**
128     * Convert an array of Throwable data to a string.
129     *
130     * @param array{class:class-string,message:string,code:int,file:string,line:int,trace:array,previous?:array} $e
131     * @return string
132     */
133    protected function normalizeExceptionArray( array $e ) {
134        $defaults = [
135            'class' => 'Unknown',
136            'file' => 'unknown',
137            'line' => 0,
138            'message' => 'unknown',
139            'trace' => [],
140        ];
141        $e = array_merge( $defaults, $e );
142
143        $which = is_a( $e['class'], Error::class, true ) ? 'Error' : 'Exception';
144        $str = "\n[$which {$e['class']}] (" .
145            "{$e['file']}:{$e['line']}) {$e['message']}";
146
147        if ( $this->includeStacktraces && $e['trace'] ) {
148            $str .= "\n" .
149                MWExceptionHandler::prettyPrintTrace( $e['trace'], '  ' );
150        }
151
152        if ( isset( $e['previous'] ) ) {
153            $prev = $e['previous'];
154            while ( $prev ) {
155                $prev = array_merge( $defaults, $prev );
156                $which = is_a( $prev['class'], Error::class, true ) ? 'Error' : 'Exception';
157                $str .= "\nCaused by: [$which {$prev['class']}] (" .
158                    "{$prev['file']}:{$prev['line']}) {$prev['message']}";
159
160                if ( $this->includeStacktraces && $prev['trace'] ) {
161                    $str .= "\n" .
162                        MWExceptionHandler::prettyPrintTrace(
163                            $prev['trace'], '  '
164                        );
165                }
166
167                $prev = $prev['previous'] ?? null;
168            }
169        }
170        return $str;
171    }
172}