Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Newbie: Defining Metrics Programmatically Not Working #923

Unanswered
prime-minister-of-fun asked this question in Q&A
Discussion options

Hi,
I'm attempting to build a scraper that returns both values and the metric definition dynamically.

If I hardcode two metrics at the global level of the script:
DEMO_EVENTS = Gauge('demo_notification', 'A value')
OTHER_EVENTS = Gauge('other_notification', 'A value', ,['server', 'region'])
def foo (a_dictionary):
 for key in a_dictionary:
 ..parse dictionary into commands..
 exec(DEMO_EVENTS.set(2))
 exec(OTHER_EVENTS.labels( server=tomato, region=us-west).set(3)
 exec(OTHER_EVENTS.labels( server=orange, region=us-east).set(3)
 return()
 foo(a_dictionary)

Everything works as expected.
If I add the below, and remove the global declaration, then python returns an error.

def bar (a_dictionary)
 for key in a_dictionary:
 .... parse dictionary into commands....
 exec("global DEMO_EVENTS")
 exec("OTHER_EVENTS = Gauge('other_notification', 'A value', ,['server', 'region'])")
 
 bar(a_dictionary)
 foo(a_dictionary)

This example returns an error on attempting .set(). The error:"name 'OTHER_EVENTS' is not defined". Python does not register the global object. You can delete the global command and the error is the same.

My gut feeling is, I'm missing something. Is dynamically generating the metric not supported?

You must be logged in to vote

Replies: 1 comment

Comment options

Is there a reason that you are using exec rather than just creating and calling OTHER_EVENTS directly from within the loop?

I think you need to add global OTHER_EVENTS not DEMO_EVENTS in your second example.

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
Converted from issue

This discussion was converted from issue #920 on June 13, 2023 15:37.

AltStyle によって変換されたページ (->オリジナル) /