Compare commits

...

2 Commits
master ... 1.x

@ -16,9 +16,10 @@
"minimum-stability": "stable", "minimum-stability": "stable",
"require": { "require": {
"php": "^7.4 || ^8.0", "php": "^7.4 || ^8.0",
"jrosset/exceptionhelper": "^1.0", "ext-mbstring": "*",
"jrosset/lasterrorexception": "^1.0", "jrosset/exceptionhelper": "^1.1",
"monolog/monolog": "^2.9" "jrosset/lasterrorexception": "^1.1",
"monolog/monolog": "^2.10"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {

@ -1,4 +1,5 @@
<?php <?php
/** @noinspection PhpDocFinalChecksInspection */
namespace jrosset\ExtendedMonolog; namespace jrosset\ExtendedMonolog;
@ -16,7 +17,7 @@ class ExceptionLogger extends Logger implements ExceptionLoggerInterface {
public function exception (int $level, Throwable $exception, array $context = []): void { public function exception (int $level, Throwable $exception, array $context = []): void {
$this->addRecord( $this->addRecord(
$level, $level,
ExceptionHelper::toString($exception, false), ExceptionHelper::toString($exception, false) . PHP_EOL,
array_merge( array_merge(
[ [
'exception' => $exception, 'exception' => $exception,

@ -20,28 +20,30 @@ class LogDirectoryHandler extends StreamHandler {
/** /**
* Initialization * Initialization
* *
* @param string $dirPath The log directory path * @param string $dirPath The log directory path
* @param int|string $level The minimum logging level at which this handler will be triggered * @param int|string $level The minimum logging level at which this handler will be triggered
* @param int $historyNumberOfDays The maximum number of history files to keep (in number of days) * @param int $historyNumberOfDays The maximum number of history files to keep (in number of days)
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param int|null $filePermission Optional file permissions (default (0644) are only for owner read/write) * @param int|null $filePermission Optional file permissions (default (0644) are only for owner read/write)
* @param bool $useLocking Try to lock log file before doing any writes * @param bool $useLocking Try to lock log file before doing any writes
* @param string|null $filenamePrefix The filename prefix
* *
* @throws Throwable If an error occurs * @throws Throwable If an error occurs
*/ */
public function __construct ( public function __construct (
string $dirPath, string $dirPath,
$level = Logger::DEBUG, $level = Logger::DEBUG,
int $historyNumberOfDays = 30, int $historyNumberOfDays = 30,
bool $bubble = true, bool $bubble = true,
?int $filePermission = null, ?int $filePermission = null,
bool $useLocking = false bool $useLocking = false,
?string $filenamePrefix = null
) { ) {
$dirPath = $dirPath . DIRECTORY_SEPARATOR; $dirPath = $dirPath . DIRECTORY_SEPARATOR;
$this->normalizeDirectory($dirPath, $historyNumberOfDays); $this->normalizeDirectory($dirPath, $filenamePrefix, $historyNumberOfDays);
parent::__construct( parent::__construct(
$dirPath . date('Y-m-d') . '.log', $dirPath . ($filenamePrefix ?? '') . date('Y-m-d') . '.log',
$level, $level,
$bubble, $bubble,
$filePermission, $filePermission,
@ -53,14 +55,15 @@ class LogDirectoryHandler extends StreamHandler {
/** /**
* Normalize a directory: create if missing and clear old files * Normalize a directory: create if missing and clear old files
* *
* @param string $dirPath The directory path * @param string $dirPath The directory path
* @param int $historyNumberOfDays The maximum number of history files to keep (in number of days) * @param string|null $filenamePrefix The filename prefix
* @param int $historyNumberOfDays The maximum number of history files to keep (in number of days)
* *
* @return void * @return void
* *
* @throws Throwable If an error occurs * @throws Throwable If an error occurs
*/ */
private function normalizeDirectory (string $dirPath, int $historyNumberOfDays = 30): void { protected final function normalizeDirectory (string $dirPath, ?string $filenamePrefix, int $historyNumberOfDays = 30): void {
if (!file_exists($dirPath) || !is_dir($dirPath)) { if (!file_exists($dirPath) || !is_dir($dirPath)) {
error_clear_last(); error_clear_last();
if (!mkdir($dirPath, 0755, true)) { if (!mkdir($dirPath, 0755, true)) {
@ -78,7 +81,13 @@ class LogDirectoryHandler extends StreamHandler {
if (!$fileInfo->isFile()) { if (!$fileInfo->isFile()) {
continue; continue;
} }
if (preg_match('/^(?<date>\\d{4}-\\d{2}-\\d{2})(?:[_-].*)?\.log$/i', $fileInfo->getFilename(), $match) !== 1) { if (
preg_match(
'/^' . preg_quote($filenamePrefix ?? '', '/') . '(?<date>\\d{4}-\\d{2}-\\d{2})(?:[_-].*)?\.log$/i',
$fileInfo->getFilename(),
$match
) !== 1
) {
continue; continue;
} }

@ -25,6 +25,30 @@ class LogFileFormatter extends LineFormatter {
* @inheritDoc * @inheritDoc
*/ */
public function format (array $record): string { public function format (array $record): string {
return preg_replace('/((?<!\\\\)\\\\[rn])+$/', PHP_EOL, parent::format($record)); //region Get then remove newlines at record message end (*before* the formatting)
$messageEndNewlines = '';
$record['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
} }
} }

@ -4,6 +4,7 @@ require_once __DIR__ . '/../vendor/autoload.php';
use jrosset\ExtendedMonolog\ExceptionLogger; use jrosset\ExtendedMonolog\ExceptionLogger;
use jrosset\ExtendedMonolog\LogDirectoryHandler; use jrosset\ExtendedMonolog\LogDirectoryHandler;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler; use Monolog\Handler\StreamHandler;
use Monolog\Logger; use Monolog\Logger;
@ -11,18 +12,25 @@ use Monolog\Logger;
$logger = new ExceptionLogger( $logger = new ExceptionLogger(
'test', 'test',
[ [
new StreamHandler(STDOUT), (new StreamHandler(STDOUT))
->setFormatter(
new LineFormatter(
'[%datetime%] %level_name% : %message%',
'Y-m-d H:i:s',
true
)
),
new LogDirectoryHandler(__DIR__ . '/logs/'), new LogDirectoryHandler(__DIR__ . '/logs/'),
] ]
); );
try { try {
$logger->info('START'); $logger->info('======= test =======' . PHP_EOL . 'START' . PHP_EOL);
throw new RuntimeException('An unexpected error occurs'); throw new RuntimeException('An unexpected error occurs');
/** @noinspection PhpUnreachableStatementInspection */ /** @noinspection PhpUnreachableStatementInspection */
$logger->info('END'); $logger->info('END' . PHP_EOL);
} }
catch (Throwable $exception) { catch (Throwable $exception) {
$logger->exception(Logger::ERROR, $exception); $logger->exception(Logger::ERROR, $exception);

Loading…
Cancel
Save