Skip to content

Commit

Permalink
Merge pull request #92 from danabens/metrics-buffering-fix
Browse files Browse the repository at this point in the history
fix metric buffer not flushing on newline
  • Loading branch information
KenHenderson authored Jul 31, 2020
2 parents 955b7c5 + 221d103 commit bd48bdc
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ var/
.installed.cfg
*.egg
*.gz
.eggs

# Installer logs
pip-log.txt
Expand Down
2 changes: 1 addition & 1 deletion src/smexperiments/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def log_metric(self, metric_name, value, timestamp=None, iteration_number=None):
if self._closed:
raise SageMakerMetricsWriterException("log_metric called on a closed writer")
elif not self._file:
self._file = open(self._get_metrics_file_path(), "a")
self._file = open(self._get_metrics_file_path(), "a", buffering=1)
self._file.write(json.dumps(raw_metric_data.to_record()))
self._file.write("\n")
else:
Expand Down
25 changes: 25 additions & 0 deletions tests/unit/test_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,31 @@ def test_file_metrics_writer_log_metric(timestamp, filepath):
assert 2 == entry_four["IterationNumber"]


def test_file_metrics_writer_flushes_buffer_every_line_log_metric(filepath):
writer = metrics.SageMakerFileMetricsWriter(filepath)

writer.log_metric(metric_name="foo", value=1.0)

lines = [x for x in open(filepath).read().split("\n") if x]
[entry_one] = [json.loads(line) for line in lines]
assert "foo" == entry_one["MetricName"]
assert 1.0 == entry_one["Value"]

writer.log_metric(metric_name="bar", value=2.0)
lines = [x for x in open(filepath).read().split("\n") if x]
[entry_one, entry_two] = [json.loads(line) for line in lines]
assert "bar" == entry_two["MetricName"]
assert 2.0 == entry_two["Value"]

writer.log_metric(metric_name="biz", value=3.0)
lines = [x for x in open(filepath).read().split("\n") if x]
[entry_one, entry_two, entry_three] = [json.loads(line) for line in lines]
assert "biz" == entry_three["MetricName"]
assert 3.0 == entry_three["Value"]

writer.close()


def test_file_metrics_writer_context_manager(timestamp, filepath):
with metrics.SageMakerFileMetricsWriter(filepath) as writer:
writer.log_metric("foo", value=1.0, timestamp=timestamp)
Expand Down

0 comments on commit bd48bdc

Please sign in to comment.