77import sys
88import json
99import requests
10+ import pygelf
1011from prometheus_client import start_http_server
1112from prometheus_client .core import REGISTRY , GaugeMetricFamily
1213
1920)
2021
2122
23+ def configure_logging ():
24+ """ Configures the logging """
25+ gelf_enabled : False
26+
27+ if os .environ .get ('GELF_HOST' ):
28+ GELF = pygelf .GelfUdpHandler (
29+ host = os .environ .get ('GELF_HOST' ),
30+ port = int (os .environ .get ('GELF_PORT' , 12201 )),
31+ debug = True ,
32+ include_extra_fields = True ,
33+ )
34+ LOG .addHandler (GELF )
35+ gelf_enabled = True
36+ LOG .info ('Initialized logging with GELF enabled: {}' .format (gelf_enabled ))
37+
38+
2239class EtherscanCollector :
2340 """ The EtherscanCollector class """
2441
@@ -32,13 +49,16 @@ def __init__(self):
3249 'addresses' : os .environ .get ("ADDRESSES" ),
3350 'tokens' : [],
3451 }
52+ if not self .settings .get ('api_key' ):
53+ raise ValueError ("Missing API_KEY environment variable." )
54+
3555 if os .environ .get ('TOKENS' ):
3656 self .settings ['tokens' ] = (json .loads (os .environ .get ("TOKENS" )))
3757
3858 def get_tokens (self ):
3959 """ Gets the tokens from an account """
40- # Ensure that we don't get blocked
41- time .sleep (1 )
60+
61+ time .sleep (1 ) # Ensure that we don't get rate limited
4262 for account in self .accounts :
4363 for token in self .settings ['tokens' ]:
4464 request_data = {
@@ -59,7 +79,7 @@ def get_tokens(self):
5979 requests .exceptions .ConnectionError ,
6080 requests .exceptions .ReadTimeout ,
6181 ) as error :
62- LOG .warning ( error )
82+ LOG .exception ( 'Exception caught: {}' . format ( error ) )
6383 req = {}
6484 if req .get ('result' ) and int (req ['result' ]) > 0 :
6585 self .tokens .update ({
@@ -90,7 +110,7 @@ def get_balances(self):
90110 requests .exceptions .ConnectionError ,
91111 requests .exceptions .ReadTimeout ,
92112 ) as error :
93- LOG .warning ( error )
113+ LOG .exception ( 'Exception caught: {}' . format ( error ) )
94114 req = {}
95115 if req .get ('message' ) == 'OK' and req .get ('result' ):
96116 for result in req .get ('result' ):
@@ -140,8 +160,10 @@ def collect(self):
140160
141161
142162if __name__ == '__main__' :
143- LOG .info ("Starting" )
163+ configure_logging ()
164+ PORT = int (os .environ .get ('PORT' , 9308 ))
165+ LOG .info ("Starting on port {}" .format (PORT ))
144166 REGISTRY .register (EtherscanCollector ())
145- start_http_server (9308 )
167+ start_http_server (PORT )
146168 while True :
147169 time .sleep (1 )
0 commit comments