3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 namespace MediaWiki\Logger\Monolog
;
23 use Monolog\Handler\SyslogUdpHandler
;
27 * Log handler that will append the record's channel to a fixed 'application
28 * prefix' given at construction time.
30 * The use case for this handler is to deprecate udp2log with a localhost
31 * syslog endpoint. The application name is then used to reconstruct the
35 * @copyright © 2019 Wikimedia Foundation and contributors
37 class MwlogHandler
extends SyslogUdpHandler
{
40 * @var string $appprefix
45 * @var string $hostname
50 * @param string $appprefix Application prefix to use, channel will be appended.
51 * @param string $host Syslog host
52 * @param int $port Syslog port
53 * @param int $facility Syslog message facility
54 * @param int $level The minimum logging level at which this handler
56 * @param bool $bubble Whether the messages that are handled can bubble up
59 public function __construct(
64 $level = Logger
::DEBUG
,
67 parent
::__construct( $host, $port, $facility, $level, $bubble );
68 $this->appprefix
= $appprefix;
69 $this->hostname
= php_uname( 'n' );
72 protected function syslogHeader( $severity, $app ) {
73 $pri = $severity +
$this->facility
;
75 // Goofy date format courtesy of RFC 3164 :(
76 // RFC 3164 actually specifies that the day of month should be space
77 // padded rather than unpadded but this seems to work with rsyslog and
79 $timestamp = date( 'M j H:i:s' );
81 return "<{$pri}>{$timestamp} {$this->hostname} {$app}: ";
84 private function splitMessageIntoLines( $message ): array {
85 if ( is_array( $message ) ) {
86 $message = implode( "\n", $message );
89 return preg_split( '/$\R?^/m', (string)$message, -1, PREG_SPLIT_NO_EMPTY
);
92 protected function write( array $record ) {
93 $lines = $this->splitMessageIntoLines( $record['formatted'] );
94 $header = $this->syslogHeader(
95 $this->logLevels
[$record['level']],
96 $this->appprefix
. $record['channel'] );
98 foreach ( $lines as $line ) {
99 $this->socket
->write( $line, $header );