You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
PhpExtendedMonolog/src/ExtendedMonolog/LogFileFormatter.php

57 lines
1.7 KiB
PHP

<?php
namespace jrosset\ExtendedMonolog;
use Monolog\Formatter\LineFormatter;
use Monolog\LogRecord;
/**
* A formater for log files
*/
class LogFileFormatter extends LineFormatter {
/**
* @inheritDoc
*/
public function __construct () {
parent::__construct(
'[%datetime%] %level_name% : %message%' . PHP_EOL . '%context%' . PHP_EOL . '%extra%',
'H:i:s',
true,
true,
true
);
}
/**
* @inheritDoc
*/
public function format (LogRecord $record): string {
//region Get then remove newlines at record message end (*before* the formatting)
$messageEndNewlines = '';
$record = $record->with(
message: preg_replace_callback(
'/(?:(?<!\\\\)(?:\\\\[rn]|\\r|\\n))+$/',
function (array $match) use (&$messageEndNewlines): string {
$messageEndNewlines = $match[0];
return '';
},
$this->normalize($record->message)
)
);
//endregion
//region Format the record
$output = parent::format($record);
//endregion
//region Remove newlines at end (introduced by context, extra or record message itself)
$output = preg_replace('/(?:(?<!\\\\)(?:\\\\[rn]|\\r|\\n))+$/', '', $output);
//endregion
//region Re-add the newlines of record message end
$output .= $messageEndNewlines;
//endregion
//region Then finally, replace manual "\r" or "\n" by theirs equivalent
return preg_replace(
'/(?:(?<!\\\\)\\\\[rn])+/', PHP_EOL, $output
);
//endregion
}
}