Example #1
0
 protected function _rotate($config)
 {
     // do rotation
     $path = $config['path'];
     for ($i = $config['keep']; $i >= 0; $i--) {
         switch (true) {
             case $i == $config['keep']:
                 $SrcFile = $this->_getFile($path, $i);
                 if (!$SrcFile->exists()) {
                     continue;
                 }
                 // send report mail
                 if ($config['email_to']) {
                     try {
                         //TODO use dependency injection
                         //TODO use backend-wide email report settings
                         $email = new CakeEmail(array('transport' => 'Mail', 'from' => 'report@' . gethostname(), 'to' => $config['email_to'], 'subject' => 'Log report', 'emailFormat' => 'text', 'template' => false, 'layout' => false));
                         $email->addAttachments($SrcFile->path);
                         $email->send('Log file attached');
                     } catch (Exception $e) {
                         CakeLog::warning('LogRotation::rotate() - ' . $e->getMessage(), 'backend');
                     }
                 }
                 break;
             case $i > 0:
                 $SrcFile = $this->_getFile($path, $i);
                 if (!$SrcFile->exists()) {
                     continue;
                 }
                 if (!$config['rotate_empty'] && $SrcFile->size() < 1) {
                     #if (!$SrcFile->delete())
                     #	$this->log[] = "Failed to delete file";
                     continue;
                 }
                 $NewFile = $this->_getFile($path, $i + 1, true);
                 if (!$NewFile->write($SrcFile->read())) {
                     throw new Exception("Failed to copy log {$path}.'.'.{$i}");
                 }
                 if ($i == 1 && !$config['compress'] && $config['compress_delay']) {
                     $this->_compress($NewFile);
                 }
                 break;
             case $i == 0:
                 $SrcFile = $this->_getFile($path);
                 if (!$config['rotate_empty'] && $SrcFile->size() < 1) {
                     continue;
                 }
                 $NewFile = $this->_getFile($path, $i + 1, true);
                 if (!$NewFile->write($SrcFile->read())) {
                     throw new Exception("Failed to copy log {$path}");
                 }
                 if ($config['compress']) {
                     $this->_compress($NewFile);
                 }
                 if (!$SrcFile->write("")) {
                     throw new Exception("Failed to create empty log {$path}");
                 }
                 break;
             default:
                 throw new Exception("Fatal Error");
                 break;
         }
     }
 }