Skip to content

Commit

Permalink
Add support for parsing timestamps. (#483)
Browse files Browse the repository at this point in the history
* Add support for parsing timestamps.

Signed-off-by: Asher Foa <asher@asherfoa.com>
  • Loading branch information
asherf authored and brian-brazil committed Oct 29, 2019
1 parent db04b10 commit f11b6d9
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 12 deletions.
20 changes: 11 additions & 9 deletions prometheus_client/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,15 +103,17 @@ def _parse_labels(labels_string):


# If we have multiple values only consider the first
def _parse_value(s):
def _parse_value_and_timestamp(s):
s = s.lstrip()
separator = " "
if separator not in s:
separator = "\t"
i = s.find(separator)
if i == -1:
return s
return s[:i]
values = [value.strip() for value in s.split(separator) if value.strip()]
if not values:
return float(s), None
value = float(values[0])
timestamp = (float(values[-1])/1000) if len(values) > 1 else None
return value, timestamp


def _parse_sample(text):
Expand All @@ -123,8 +125,8 @@ def _parse_sample(text):
# We ignore the starting curly brace
label = text[label_start + 1:label_end]
# The value is after the label end (ignoring curly brace and space)
value = float(_parse_value(text[label_end + 2:]))
return Sample(name, _parse_labels(label), value)
value, timestamp = _parse_value_and_timestamp(text[label_end + 2:])
return Sample(name, _parse_labels(label), value, timestamp)

# We don't have labels
except ValueError:
Expand All @@ -135,8 +137,8 @@ def _parse_sample(text):
name_end = text.index(separator)
name = text[:name_end]
# The value is after the name
value = float(_parse_value(text[name_end:]))
return Sample(name, {}, value)
value, timestamp = _parse_value_and_timestamp(text[name_end:])
return Sample(name, {}, value, timestamp)


def text_fd_to_metric_families(fd):
Expand Down
9 changes: 6 additions & 3 deletions tests/test_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,17 +273,20 @@ def test_escaping(self):
metric_family.add_metric(["b\\a\\z"], 2)
self.assertEqualMetrics([metric_family], list(families))

def test_timestamps_discarded(self):
def test_timestamps(self):
families = text_string_to_metric_families("""# TYPE a counter
# HELP a help
a{foo="bar"} 1\t000
# TYPE b counter
# HELP b help
b 2 1234567890
b 88 1234566000
""")
a = CounterMetricFamily("a", "help", labels=["foo"])
a.add_metric(["bar"], 1)
b = CounterMetricFamily("b", "help", value=2)
a.add_metric(["bar"], 1, timestamp=0)
b = CounterMetricFamily("b", "help")
b.add_metric([], 2, timestamp=1234567.89)
b.add_metric([], 88, timestamp=1234566)
self.assertEqualMetrics([a, b], list(families))

@unittest.skipIf(sys.version_info < (2, 7), "Test requires Python 2.7+.")
Expand Down

0 comments on commit f11b6d9

Please sign in to comment.