Move the current logfile to a backup name, taking care of any existing
backup files according to the configured limit.
764880
private void addBackup() {
        // move the current log file to the newly formatted backup name
        String newname = this.fileinfo + this.myFormat.format(new Date(HttpDispatcher.getApproxTime())) + this.extensioninfo;
        File newFile = new File(newname);
        renameFile(this.myFile, newFile);
        // now see if we need to delete an existing backup to make room
        if (this.backups.size() == getMaximumBackupFiles()) {
            File oldest = this.backups.removeLast();
            if (null != oldest && oldest.exists()) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, getFileName() + ": Purging oldest backup-> " + oldest.getName());
                }
                oldest.delete();
            }
        }
        this.backups.addFirst(newFile);
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, getFileName() + ": number of backup files-> " + this.backups.size());
        }
    }
289195
public function apply()
    {
        $this->backup = is_file($this->name) ? file_get_contents($this->name) : new NotSet();

        file_put_contents($this->name, $this->value);
    }
1350847
def rename_file(self, old_save_name, new_save_name, new_path):
        
        if old_save_name in self._files:
            del self._files[old_save_name]
        self.update_file(new_save_name, new_path)
247744
private void handleLogfile() {
        if (args.logFile != null) {
            FileUtils.close(out);
            FileUtils.close(err);
        }
    }
1062146
protected void setLogFileSize(long newFileSize)
                    throws ObjectManagerException
    {
        if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
            trace.entry(this, cclass
                        , "setLogFileSize"
                        , "newFileSize=" + newFileSize + "(long)"
                            );

        // Note where we are in the log file.
        long initialFilePosition = filePosition;

        synchronized (newFileSizeRequestLock) {
            // Force the new file size to be a whole number of pages.
            this.newFileSize = (newFileSize / pageSize) * pageSize;
            newFileSizeRequested = true;
            newFileSizeException = null;
            logFileSizeRequested = newFileSize;
            // We have not yet seen the log file wrap.
            boolean wrapped = false;

            // Keep requesting checkpoints until the start and end of the log data are both 
            // before the new end of the log, without the user log data wrapping round the 
            // end of the logFile.
            while (newFileSizeRequested) {

                // Check there is still some chance of fitting the current log into the new one.
                // and that we have not wrapped round the log file without succeeding.
                long fileSpaceAvailable = getLogFileSpaceLeft();
                long newFileSpaceAvailable = fileSpaceAvailable - fileLogHeader.fileSize + newFileSize;
                float newOcupancy = (float) 1.0 - (float) (newFileSpaceAvailable) / (float) (newFileSize);
                if (newOcupancy > objectManagerState.logFullPostCheckpointThreshold
                    || wrapped) {
                    newFileSizeRequested = false;
                    logFileSizeRequested = 0;
                    if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
                        trace.exit(this,
                                   cclass,
                                   "setLogFileSize",
                                   new Object[] { new Long(fileLogHeader.fileSize),
                                                 new Long(newFileSize),
                                                 new Float(newOcupancy) });
                    throw new LogFileSizeTooSmallException(this
                                                           , fileLogHeader.fileSize
                                                           , newFileSize
                                                           , fileSpaceAvailable
                                                           , newOcupancy
                                                           , objectManagerState.logFullPostCheckpointThreshold);
                } // if (   (fileSpaceLeft...

                if (Tracing.isAnyTracingEnabled() && trace.isDebugEnabled())
                    trace.debug(this,
                                cclass,
                                "setLogFileSize",
                                new Object[] { new Long(filePosition),
                                              new Long(initialFilePosition) });

                // If we have wrapped round the log file, give up after the next attempt to satisfy the 
                // request. 
                if (filePosition < initialFilePosition)
                    wrapped = true;

                // We have released the lock on writingFlushSet set so now we can request a checkpoint and
                // see if we are successful.
                objectManagerState.waitForCheckpoint(true);

                // Speed up moving the filePosition by writing a reasonable ammount of data.
                // The folowing is dangerous because it can cause the request to fail if we 
                // are trying to reduce the log file size close to the minimum possible. 
//        PaddingLogRecord paddingLogRecord = new PaddingLogRecord(logBufferSize/2);
//        writeNext(paddingLogRecord
//                 ,0
//                 ,true
//                 );

            } // while (newFileSizeRequested...

            logFileSizeRequested = 0;
        } // synchronized (newFileSizeRequestLock).                                            

        if (newFileSizeException != null) {
            if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
                trace.exit(this, cclass
                           , "setLogFileSize"
                           , "via PermanentIOException newFileSizeException=" + newFileSizeException + "(PermanentIOException)"
                                );
            throw newFileSizeException;
        }

        if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
            trace.exit(this, cclass
                       , "setLogFileSize"
                            );
    }
431987
def add_log_file(path):
    
    logfile_handler = RotatingFileHandler(
        path, maxBytes=50000, backupCount=2)
    formatter = logging.Formatter(
        fmt='%(asctime)s %(levelname)s %(module)s - %(message)s',
        datefmt="%d-%b-%Y %H:%M:%S")
    logfile_handler.setFormatter(formatter)
    geoparse_logger.addHandler(logfile_handler)
319484
private void createBackupFile() {
        if (createBackupFile) {
            if (backupFileExtension.trim().length() == 0) {
                throw new FailureException("Could not create backup file, extension name was empty");
            }
            fileUtil.backupFile();
            log.info(String.format("Saved backup of %s to %s%s", pomFile.getAbsolutePath(),
                    pomFile.getAbsolutePath(), backupFileExtension));
        }
    }
1322276
public function moveOldBackup()
    {
        Service::$log->msg('Filesystem: moving old backups');
        // remove the 2-day file
        if(file_exists($this->storagePath.'backup-2days-old')){
            unlink($this->storagePath.'backup-2days-old');
        }

        // copy current 1-day file to 2-day
        $sourceFile = $this->storagePath . 'backup-1day-old';
        $destinationFile = $this->storagePath . 'backup-2days-old';
        if (file_exists($sourceFile)) {
            copy($sourceFile, $destinationFile);
        }

        // remove the old 1-day file
        $destinationFileTemp = $this->storagePath. 'backup-1day-old';
        if (file_exists($destinationFileTemp)) {
            unlink($destinationFileTemp);
        }

        Service::$log->msg('Filesystem: moving old backups done');

        return $destinationFile;
    }
200560
def setLog(self, fileName, writeName=False):
        
        self.log = 1
        self.logFile = fileName
        self._logPtr = open(fileName, "w")
        if writeName:
            self._namePtr = open(fileName + ".name", "w")
9212
protected function updateLogFile()
    {
        // update file. $dtStr is '_Y-m-d' or '_Y-m-d_H'
        if ($this->fileIsChanged()) {
            fclose($this->fileHandle);

            $logFile = $this->genLogFile(true);
            $this->file = $logFile;
            $this->fileHandle = @fopen($logFile, 'ab');

            if (!$this->fileHandle) {
                $this->stderr("Could not open the log file {$logFile}");
            }
        }
    }
1170996
function proceedWithBackup() {
    if (options.resume) {
      // pick up from existing log file from previous run
      downloadRemainingBatches(options.log, db, ee, start, batchesPerDownloadSession, options.parallelism);
    } else {
      // create new log file and process
      spoolchanges(db, options.log, options.bufferSize, ee, function(err) {
        if (err) {
          ee.emit('error', err);
        } else {
          downloadRemainingBatches(options.log, db, ee, start, batchesPerDownloadSession, options.parallelism);
        }
      });
    }
  }
1082914
private void updateIndicesAfterLogTruncation(TaskAttemptID firstAttempt,
      Map<Task, Map<LogName, LogFileDetail>> updatedTaskLogFileDetails) {
    for (Entry<Task, Map<LogName, LogFileDetail>> entry : 
                                updatedTaskLogFileDetails.entrySet()) {
      Task task = entry.getKey();
      Map<LogName, LogFileDetail> logFileDetails = entry.getValue();
      Map<LogName, Long[]> logLengths = new HashMap<LogName, Long[]>();
      // set current and previous lengths
      for (LogName logName : TaskLog.LOGS_TRACKED_BY_INDEX_FILES) {
        logLengths.put(logName, new Long[] { Long.valueOf(0L),
            Long.valueOf(0L) });
        LogFileDetail lfd = logFileDetails.get(logName);
        if (lfd != null) {
          // Set previous lengths
          logLengths.get(logName)[0] = Long.valueOf(lfd.start);
          // Set current lengths
          logLengths.get(logName)[1] = Long.valueOf(lfd.start + lfd.length);
        }
      }
      try {
        TaskLog.writeToIndexFile(firstAttempt, task.getTaskID(),
            task.isTaskCleanupTask(), logLengths);
      } catch (IOException ioe) {
        LOG.warn("Exception in updateIndicesAfterLogTruncation : "
            + StringUtils.stringifyException(ioe));
        LOG.warn("Exception encountered while updating index file of task "
            + task.getTaskID()
            + ". Ignoring and continuing with other tasks.");
      }
    }
  }
479064
def rotating_file_handler(name, logname, filename, mode='a', maxBytes=0,
                          backupCount=0, encoding=None, delay=False):
    

    return wrap_log_handler(logging.handlers.RotatingFileHandler(
        filename, mode=mode, maxBytes=maxBytes, backupCount=backupCount,
        encoding=encoding, delay=delay))
826913
private void setFileSpaceLeft()
                    throws ObjectManagerException
    {
        if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
            trace.entry(this, cclass,
                        "setFileSpaceLeft",
                        new Object[] { new Long(fileLogHeader.fileSize), new Long(fileLogHeader.startByteAddress),
                                      new Long(filePosition) }
                            );

        // Assume we have wrapped around the end of the file, the space left is between the current
        // file position and the start of the log file.
        long newFileSpaceLeft = fileLogHeader.startByteAddress - filePosition;
        if (newFileSpaceLeft <= 0) // If we have not wrapped. 
            newFileSpaceLeft = newFileSpaceLeft + fileLogHeader.fileSize - FileLogHeader.headerLength * 2;
        fileSpaceLeft = newFileSpaceLeft;

        if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
            trace.exit(this,
                       cclass,
                       "setFileSpaceLeft",
                       new Object[] { new Long(fileSpaceLeft) });
    }
1295816
private void rollOverFiles() {

        Context context = appContextRef.get();

        if (context != null) {

            File dir = context.getFilesDir();

            File mainFile = new File(dir, name(1));

            if (mainFile.exists()) {

                float fileSize = mainFile.length();
                fileSize = fileSize / 1024.0f; //In kilobytes

                if (fileSize > fileSizeLimitKb) {

                    File file;
                    File target;

                    file = new File(dir, name(maxFiles));
                    if (file.exists()) {
                        file.delete();
                    }

                    for (int i = maxFiles - 1; i > 0; i--) {
                        file = new File(dir, name(i));
                        if (file.exists()) {
                            target = new File(dir, name(i + 1));
                            file.renameTo(target);
                        }
                    }
                }
            }
        }
    }
1016970
def logfile_generator(self):
        """"""
        if not self.args['exclude']:
            # ask all filters for a start_limit and fast-forward to the maximum
            start_limits = [f.start_limit for f in self.filters
                            if hasattr(f, 'start_limit')]

            if start_limits:
                for logfile in self.args['logfile']:
                    logfile.fast_forward(max(start_limits))

        if len(self.args['logfile']) > 1:
            # merge log files by time
            for logevent in self._merge_logfiles():
                yield logevent
        else:
            # only one file
            for logevent in self.args['logfile'][0]:
                if self.args['timezone'][0] != 0 and logevent.datetime:
                    logevent._datetime = (logevent.datetime +
                                          timedelta(hours=self
                                                    .args['timezone'][0]))
                yield logevent
529211
def __set_log_file_name(self):
        """"""
        # ensure directory exists
        dir, _ = os.path.split(self.__logFileBasename)
        if len(dir) and not os.path.exists(dir):
            os.makedirs(dir)
        # create logFileName
        self.__logFileName = self.__logFileBasename+"."+self.__logFileExtension
        number = 0
        while os.path.isfile(self.__logFileName):
            if os.stat(self.__logFileName).st_size/1e6 < self.__maxlogFileSize:
                break
            number += 1
            self.__logFileName = self.__logFileBasename+"_"+str(number)+"."+self.__logFileExtension
        # create log file stram
        self.__logFileStream = None