Skip to content

Commit 0ea410e

Browse files
asanderson15bmoylan
authored andcommitted
Metrics: creating tags with fallback value (#152)
We frequently want to create a tag with a known key, but potentially invalid value, in which case we want to fall back to a known value such as the string `unknown`. This allows us to do so without repeatedly rewriting the same fallback code.
1 parent 7fd8d6e commit 0ea410e

1 file changed

Lines changed: 12 additions & 0 deletions

File tree

metrics/tag.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,18 @@ func MustNewTag(k, v string) Tag {
7676
return t
7777
}
7878

79+
// NewTagWithFallbackValue returns the result of calling NewTag, and if that fails, calls MustNewTag with a fallback
80+
// value. This function is useful when the value is provided as a runtime input and the desired behavior is to fall back
81+
// to using a known valid value (e.g., "unknown") when the value is invalid. Note: because MustNewTag will panic if it
82+
// fails, both the key and fallback value must be known valid.
83+
func NewTagWithFallbackValue(k, v, fallback string) Tag {
84+
tag, err := NewTag(k, v)
85+
if err != nil {
86+
return MustNewTag(k, fallback)
87+
}
88+
return tag
89+
}
90+
7991
// NewTag returns a tag that uses the provided key and value. The returned tag is normalized to conform with the DataDog
8092
// tag specification. The key and value must be non-empty and the key must begin with a letter. The string form of the
8193
// returned tag is "normalized(k):normalized(v)".

0 commit comments

Comments
 (0)