Reputation: 6812
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)
Upvotes: 0
Views: 496
Reputation: 154886
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()
Upvotes: 2