Skip to content

Commit

Permalink
feat: 支持日志轮转天数,自动删除历史日志
Browse files Browse the repository at this point in the history
  • Loading branch information
bingcool committed Jun 10, 2023
1 parent e64ad67 commit 831c4a0
Showing 1 changed file with 59 additions and 1 deletion.
60 changes: 59 additions & 1 deletion src/Util/Log.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,21 @@ class Log
*/
protected $dateLogFilePath;

/**
* @var string
*/
protected $splitString = '_';

/**
* @var int
*/
protected $rotateDay = 7;

/**
* @var bool
*/
protected $doUnlink = false;

/**
* @param string $type
* @param string|null $channel
Expand Down Expand Up @@ -139,6 +154,15 @@ public function setChannel(string $channel)
return $this;
}

/**
* @param int $rotateDay
* @return void
*/
public function setRotateDay(int $rotateDay)
{
$this->rotateDay = $rotateDay;
}

/**
* setLogFilePath
* @param string $logFilePath
Expand Down Expand Up @@ -166,7 +190,37 @@ protected function getDateLogFile(string $date, string $logFilePath)
if (!is_dir($fileInfo['dirname'])) {
mkdir($fileInfo['dirname'], 0777);
}
return $fileInfo['dirname'].DIRECTORY_SEPARATOR.$fileInfo['filename'].'_'.$date.'.'.$fileInfo['extension'];
return $fileInfo['dirname'].DIRECTORY_SEPARATOR.$fileInfo['filename'].$this->splitString.$date.'.'.$fileInfo['extension'];
}

/**
* @param string $logFilePath
* @return mixed
*/
protected function unlinkHistoryDayLogFile(string $logFilePath)
{
if ($this->doUnlink) {
return;
}

$fileInfo = pathinfo($logFilePath);
$logDir = $fileInfo['dirname'];
$fileList = scandir($logDir);
$lastDay = date('Ymd', time() - 24 * 3600 * ($this->rotateDay + 1));
foreach ($fileList as $file) {
$pathFile = $logDir . DIRECTORY_SEPARATOR . $file;
if ($pathFile == '.' || $pathFile == '..' || !is_file($pathFile)) {
continue;
}
$fileName = pathinfo($pathFile, PATHINFO_FILENAME);
$fileArr = explode($this->splitString, $fileName);
$fileDate = array_pop($fileArr);

if (is_numeric($fileDate) && $fileDate < $lastDay ) {
unlink($pathFile);
}
}
$this->doUnlink = true;
}

/**
Expand Down Expand Up @@ -307,6 +361,8 @@ public function insertLog($logInfo, array $context = [], $type = Logger::INFO)
});
}

$this->unlinkHistoryDayLogFile($this->logFilePath);

// add records to the log
$this->logger->addRecord($type, $logInfo, $context);
} catch (\Exception $e) {
Expand All @@ -332,6 +388,8 @@ public function insertLog($logInfo, array $context = [], $type = Logger::INFO)
*/
protected function pushProcessor($records, $App = null): array
{
$records['cid'] = \Swoole\Coroutine::getCid();
$records['process_id'] = (int)getmypid();
$records['timestamp'] = microtime(true);
$records['hostname'] = gethostname();
$records['process'] = 'task_worker|use_self_worker';
Expand Down

0 comments on commit 831c4a0

Please sign in to comment.