Skip to content

Commit

Permalink
Add .extend_prefix() to hone a MetricsInterface prefix (#142)
Browse files Browse the repository at this point in the history
This makes it possible to iteratively hone a MetricsInterface prefix. So
you can do things like this:

    # prefix here is "module"
    metrics = markus.get_metrics("module")

    # prefix here is "module.somefunc"
    func_metrics = metrics.extend_prefix("somefunc")
  • Loading branch information
willkg committed Jun 24, 2024
1 parent b679093 commit 8ed7c43
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 1 deletion.
3 changes: 3 additions & 0 deletions src/markus/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ class AddTagFilter(MetricsFilter):
def __init__(self, tag):
self.tag = tag

def __repr__(self):
return f"<AddTagFilter {self.tag}>"

def filter(self, record):
record.tags.append(self.tag)
return record
11 changes: 11 additions & 0 deletions src/markus/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,9 @@ class MetricsFilter:
"""

def __repr__(self):
return "<MetricsFilter>"

def filter(self, record):
"""Filter a record
Expand Down Expand Up @@ -284,6 +287,14 @@ def _publish(self, record):
fresh_record = record.__copy__()
backend.emit_to_backend(fresh_record)

def extend_prefix(self, prefix):
prefix = prefix.strip(".")

return MetricsInterface(
f"{self.prefix}.{prefix}",
filters=list(self.filters),
)

def incr(self, stat, value=1, tags=None):
"""Incr is used for counting things.
Expand Down
26 changes: 25 additions & 1 deletion tests/test_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,34 @@ class Foo:
("foo", "namespace1", "foo.namespace1"),
],
)
def test_get_metrics(thing, extra, expected):
def test_get_metrics_prefix(thing, extra, expected):
assert get_metrics(thing, extra=extra).prefix == expected


def test_metricsinterface_extend_prefix():
metrics = get_metrics("a")
sub_metrics = metrics.extend_prefix("b")
assert sub_metrics.prefix == "a.b"
assert sub_metrics.filters == []

sub_metrics = metrics.extend_prefix(".b.")
assert sub_metrics.prefix == "a.b"
assert sub_metrics.filters == []

tag_filter_host_foo = AddTagFilter("host:foo")

metrics.filters.append(tag_filter_host_foo)
sub_metrics = metrics.extend_prefix("b")
assert sub_metrics.prefix == "a.b"
assert sub_metrics.filters == [tag_filter_host_foo]

tag_filter_env_prod = AddTagFilter("env:prod")
# Add a second tag filter and make sure the two lists are independent
metrics.filters.append(tag_filter_env_prod)
assert metrics.filters == [tag_filter_host_foo, tag_filter_env_prod]
assert sub_metrics.filters == [tag_filter_host_foo]


def test_dunders():
record = MetricsRecord("incr", "foo", 10, [])
record2 = record.__copy__()
Expand Down

0 comments on commit 8ed7c43

Please sign in to comment.