You are here

protected function LogRotator::rotateFile in File Log 8

Same name and namespace in other branches
  1. 2.0.x src/LogRotator.php \Drupal\filelog\LogRotator::rotateFile()

Rotate the log file.

Throws

\Drupal\filelog\FileLogException

1 call to LogRotator::rotateFile()
LogRotator::run in src/LogRotator.php
Check and rotate if necessary.

File

src/LogRotator.php, line 146

Class

LogRotator
Log rotation cron service.

Namespace

Drupal\filelog

Code

protected function rotateFile() : bool {
  $logFile = $this->fileManager
    ->getFileName();
  $truncate = $this->config
    ->get('rotation.delete');
  $timestamp = $this->state
    ->get('filelog.rotation');
  if (!$truncate) {
    $destination = $this->token
      ->replace($this->config
      ->get('rotation.destination'), [
      'date' => $timestamp,
    ]);
    $destination = PlainTextOutput::renderFromHtml($destination);
    $destination = $this->config
      ->get('location') . '/' . $destination;
    $directory = dirname($destination);
    $this->fileSystem
      ->prepareDirectory($directory, $this->fileSystem::CREATE_DIRECTORY);
    if ($this->config
      ->get('rotation.gzip')) {
      $truncate = TRUE;
      $data = file_get_contents($logFile);
      if (!file_put_contents($destination . '.gz', gzencode($data))) {
        throw new FileLogException("Log file could not be compressed from {$logFile} to {$destination}.gz.");
      }
    }
    elseif (!rename($logFile, $destination)) {
      throw new FileLogException("Log file could not be moved from {$logFile} to {$destination}.");
    }
  }
  if ($truncate) {

    // Simply truncate the log file, to save some file-system operations.
    $file = fopen($logFile, 'wb');
    if (!$file || !fclose($file)) {
      throw new FileLogException("Log file {$logFile} could not be truncated.");
    }
  }
  $this->state
    ->set('filelog.rotation', $this->time
    ->getRequestTime());
  return TRUE;
}