def rollover_logs_by_date(self, backup_dir=None, date_pattern='%Y%m%d%H%M%S', zip_file=True): """ If the filename exists, roll it over to a new file based on the parameters. Return the name of the new file. :type backup_dir: str :type date_pattern: str :type zip_file: bool :return: str """ for file_loc, logger_list in self.open_log_files.iteritems(): cli = LinuxCLI(priv=False) if cli.exists(file_loc.full_path()) and os.path.getsize(file_loc.full_path()) > 0: # Close previous, now-stale file handlers for l, h, df, dp in logger_list: h.close() l.removeHandler(h) self._rollover_file(file_loc.full_path(), backup_dir, date_pattern, zip_file) # Pop off old logger/handler pairs and re-populate with new handler objects # which point to the original file location for i in range(0, len(logger_list)): l, h, df, dp = logger_list.pop() new_handler = logging.FileHandler(filename=file_loc.full_path(), mode='w') l.addHandler(new_handler) logger_list.append((l, new_handler, df, dp))
def _rollover_file(self, file_path, backup_dir=None, date_pattern='%Y%m%d%H%M%S', zip_file=True): cli = LinuxCLI(priv=False) suff_str = '.' + datetime.datetime.now().strftime(date_pattern) dest_dir = backup_dir if backup_dir is not None else (self.root_dir + '/log_bak') if not cli.exists(dest_dir): cli.mkdir(dest_dir) dest_filename = dest_dir + '/' + os.path.basename(file_path) + suff_str # Move the file, zip if requested cli.move(file_path, dest_filename) if zip_file: cli.cmd('gzip -9 ' + dest_filename)
def test_get_file(self): try: cli = LinuxCLI(priv=False) cli.write_to_file('test', 'teststr') cli.write_to_file('testdir/test2', 'test2str') fl = FileLocation('test') self.assertEqual('.', fl.path) fl.get_file(FileAccessor(), near_filename='test_copy') self.assertTrue(cli.exists('test_copy')) fl2 = FileLocation('testdir/test2') self.assertEqual('testdir', fl2.path) #fl2.get_file(SSHFileAccessor('localhost', LinuxCLI().whoami()), near_filename='test2_copy') #self.assertTrue(cli.exists('test2_copy')) finally: LinuxCLI().rm('test') LinuxCLI().rm('testdir') LinuxCLI().rm('test_copy') LinuxCLI().rm('test2_copy')