LogDirectoryHandler: add filename prefix possibility

1.x 1.2.0
Julien Rosset 8 months ago
parent 066c0500ba
commit 79e9c6e1e5

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

@ -26,6 +26,7 @@ class LogDirectoryHandler extends StreamHandler {
* @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 bool $useLocking Try to lock log file before doing any writes
* @param string|null $filenamePrefix The filename prefix
*
* @throws Throwable If an error occurs
*/
@ -35,13 +36,14 @@ class LogDirectoryHandler extends StreamHandler {
int $historyNumberOfDays = 30,
bool $bubble = true,
?int $filePermission = null,
bool $useLocking = false
bool $useLocking = false,
?string $filenamePrefix = null
) {
$dirPath = $dirPath . DIRECTORY_SEPARATOR;
$this->normalizeDirectory($dirPath, $historyNumberOfDays);
$this->normalizeDirectory($dirPath, $filenamePrefix, $historyNumberOfDays);
parent::__construct(
$dirPath . date('Y-m-d') . '.log',
$dirPath . ($filenamePrefix ?? '') . date('Y-m-d') . '.log',
$level,
$bubble,
$filePermission,
@ -54,13 +56,14 @@ class LogDirectoryHandler extends StreamHandler {
* Normalize a directory: create if missing and clear old files
*
* @param string $dirPath The directory path
* @param string|null $filenamePrefix The filename prefix
* @param int $historyNumberOfDays The maximum number of history files to keep (in number of days)
*
* @return void
*
* @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)) {
error_clear_last();
if (!mkdir($dirPath, 0755, true)) {
@ -78,7 +81,13 @@ class LogDirectoryHandler extends StreamHandler {
if (!$fileInfo->isFile()) {
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;
}

Loading…
Cancel
Save