0

For a bulk task I create a couple of instances of the ProgressLog object which will each create an empty log-file no matter if there actually will be any errors. what is the best way to prevent this?

class ProgressLog(object):
    """Write a message to log + progress indicator.

    """
    total = 0

    def __init__(self, name):
        source_path, file_name = os.path.split(name)
        self.name = file_name
        self.source_path = source_path
        self.log_dir_name = r'log'
        self.make_log_dir(self.source_path, self.log_dir_name)
        self.reset()
        log_file = self._logfilename()
        try:
            self.f = open(log_file, 'w')
            print('\n***logging errors to {0}***\n'.format(log_file))
        except IOError, err:
            msg = 'Cannot open logfile {0}. Traceback is: {1}'.format(
                log_file, err)
            raise msg

    def _logfilename(self):
        ## hms_ddmmyyyy format
        log_name = r'{1}_{0}{2}_errors.csv'.format(
                                  time.strftime("%I%M%S"),
                                  time.strftime("%d%m%Y"),
                                  self.name)
        return os.path.join(self.source_path, self.log_dir_name, log_name)
3
  • Why are you creating the logfile yourself and not let python handle it? docs.python.org/2/howto/logging-cookbook.html Commented Feb 26, 2015 at 10:12
  • The code base is written by someone else... Commented Feb 26, 2015 at 10:15
  • As for as I understand this should be expected open(log_file, 'w') creates a file if none exists. What exactly are you trying to do? When are you expecting an exception to be thrown? Commented Feb 26, 2015 at 10:23

1 Answer 1

2

There is no "magical" way to do it, you simply need to refactor the code to open the log file only on first actual call to log.

To achieve this, extract the part of __init__ that opens the log file into a separate _open_log method. In __init__ initialize self.f to None. Then, your actual logging method can begin with:

if self.f is None:
    self._open_log()
Sign up to request clarification or add additional context in comments.

2 Comments

explained another way: open the output (log) file only when/if there is data to be written.
@Skaperen Thanks, I've now amended the answer to start off with an abstract similar to yours.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.