opentelemetry-java icon indicating copy to clipboard operation
opentelemetry-java copied to clipboard

How to add multiple attributes to a metrics instrument?

Open AlexP-Coding opened this issue 3 years ago • 5 comments

What are you trying to achieve? (Java) I want to measure the results of an sql query every X minutes, to export as a metric. I have determined that one way to do so is to use a an async gauge. However, the value I want to measure (one of the query result cells) is associated with other attributes (cells in same row).

How do I make a group of attributes to pass as an argument here?

Using the "getting started" example:

meter .gaugeBuilder("cpu_usage") .setDescription("CPU Usage") .setUnit("ms") .buildWithCallback(measurement -> { measurement.record(getCpuUsage(), attributes); });

AlexP-Coding avatar Jul 22 '22 10:07 AlexP-Coding

Transferring to opentelemetry-java.

jack-berg avatar Jul 22 '22 14:07 jack-berg

You can create Attributes as follows:

  • Attributes.builder().put("key1", "value1").put("key2", "value2").build()
  • Attributes.of(AttributeKey.stringKey("key1"), "value1", AttributeKey.stringKey("key2"), "value2")

jack-berg avatar Jul 22 '22 20:07 jack-berg

Thank you! Are those two lines both necessary, or are they alternatives to each other?

In regards to the second line you sent: how would you create these dynamically, when you don't know how many attributes you're getting from the start?

(Edit: sorry for closing the issue, it was not my intention)

AlexP-Coding avatar Jul 25 '22 09:07 AlexP-Coding

They are alternatives to each other. The second option is best for when you know all the attribute keys ahead of time.

jack-berg avatar Jul 27 '22 20:07 jack-berg

This issue was marked stale due to lack of author feedback. It will be closed in 7 days.

github-actions[bot] avatar Aug 03 '22 20:08 github-actions[bot]

Thank you for your help!

AlexP-Coding avatar Aug 08 '22 10:08 AlexP-Coding