当前位置: 首页>>代码示例>>Python>>正文


Python StatsClient.gauge方法代码示例

本文整理汇总了Python中statsd.StatsClient.gauge方法的典型用法代码示例。如果您正苦于以下问题:Python StatsClient.gauge方法的具体用法?Python StatsClient.gauge怎么用?Python StatsClient.gauge使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在statsd.StatsClient的用法示例。


在下文中一共展示了StatsClient.gauge方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: StatsdStatsLogger

# 需要导入模块: from statsd import StatsClient [as 别名]
# 或者: from statsd.StatsClient import gauge [as 别名]
    class StatsdStatsLogger(BaseStatsLogger):

        def __init__(self, host='localhost', port=8125,
                     prefix='superset', statsd_client=None):
            """
            Initializes from either params or a supplied, pre-constructed statsd client.

            If statsd_client argument is given, all other arguments are ignored and the
            supplied client will be used to emit metrics.
            """
            if statsd_client:
                self.client = statsd_client
            else:
                self.client = StatsClient(host=host, port=port, prefix=prefix)

        def incr(self, key):
            self.client.incr(key)

        def decr(self, key):
            self.client.decr(key)

        def timing(self, key, value):
            self.client.timing(key, value)

        def gauge(self, key):
            # pylint: disable=no-value-for-parameter
            self.client.gauge(key)
开发者ID:tan31989,项目名称:caravel,代码行数:29,代码来源:stats_logger.py

示例2: main

# 需要导入模块: from statsd import StatsClient [as 别名]
# 或者: from statsd.StatsClient import gauge [as 别名]
def main():
  args = parseArguments()

  # initialize statsdclient
  global statsd_client
  statsd_client = StatsClient(host=args.server, port=args.port,
                              prefix=args.source)

  value = None
  try:
    with open(args.value, 'r') as yamlfile:
      server_state = yaml.load(yamlfile)
      value = server_state['code']
  except yaml.YAMLError as ex:
    if hasattr(ex, 'problem_mark'):
      mark = ex.problem_mark
      print "YAML load error at position (%s:%s)" % (mark.line + 1,
                                                     mark.column + 1)
    sys.exit(1)

  print "%s sends metric [%s] with value [%s] to %s:%d" % (
        args.source, args.metric, value, args.server,
        args.port)

  statsd_client.gauge(args.metric, int(value))
  return 0
开发者ID:leonworkshop,项目名称:basin,代码行数:28,代码来源:basin_sendstate.py

示例3: StatsdStatsLogger

# 需要导入模块: from statsd import StatsClient [as 别名]
# 或者: from statsd.StatsClient import gauge [as 别名]
    class StatsdStatsLogger(BaseStatsLogger):
        def __init__(self, host, port, prefix='superset'):
            self.client = StatsClient(host=host, port=port, prefix=prefix)

        def incr(self, key):
            self.client.incr(key)

        def decr(self, key):
            self.client.decr(key)

        def gauge(self, key):
            # pylint: disable=no-value-for-parameter
            self.client.gauge(key)
开发者ID:alanmcruickshank,项目名称:caravel,代码行数:15,代码来源:stats_logger.py

示例4: rtl_433_probe

# 需要导入模块: from statsd import StatsClient [as 别名]
# 或者: from statsd.StatsClient import gauge [as 别名]
def rtl_433_probe():
    statsd = StatsClient(host=STATSD_HOST,
                         port=STATSD_PORT,
                         prefix=STATSD_PREFIX)

    while True:
        line, addr = sock.recvfrom(1024)

        try:
            line = parse_syslog(line)
            data = json.loads(line)

            label = sanitize(data["model"])
            if "channel" in data:
                label += ".CH" + str(data["channel"])

            if "battery" in data:
                if data["battery"] == "OK":
                    statsd.gauge(label + '.battery', 1)
                else:
                    statsd.gauge(label + '.battery', 0)

            if "humidity" in data:
                statsd.gauge(label + '.humidity', data["humidity"])

            statsd.gauge(label + '.temperature', data["temperature_C"])

        except KeyError:
            pass

        except ValueError:
            pass
开发者ID:merbanan,项目名称:rtl_433,代码行数:34,代码来源:rtl_433_statsd_relay.py

示例5: StatsDBackend

# 需要导入模块: from statsd import StatsClient [as 别名]
# 或者: from statsd.StatsClient import gauge [as 别名]
class StatsDBackend(BaseBackend):

    name = 'statsd'

    def __init__(self, config):
        self.config = config
        self.config.setdefault('STATSD_HOST', 'localhost')
        self.config.setdefault('STATSD_PORT', 8125)
        self.config.setdefault('STATSD_PREFIX', None)

        self.statsd = StatsClient(self.config['STATSD_HOST'],
                                  self.config['STATSD_PORT'],
                                  self.config['STATSD_PREFIX'])

    def timing(self, stat_name, delta):
        return self.statsd.timing(stat_name, delta, self.config['STATS_RATE'])

    def incr(self, stat_name, count=1):
        return self.statsd.incr(stat_name, count, self.config['STATS_RATE'])

    def decr(self, stat_name, count=1):
        return self.statsd.decr(stat_name, count, self.config['STATS_RATE'])

    def gauge(self, stat_name, value, delta=False):
        return self.statsd.gauge(stat_name, value, self.config['STATS_RATE'], delta)
开发者ID:gabrielpjordao,项目名称:flask-stats,代码行数:27,代码来源:flask_stats.py

示例6: check_nginx_status

# 需要导入模块: from statsd import StatsClient [as 别名]
# 或者: from statsd.StatsClient import gauge [as 别名]
def check_nginx_status(coll_type, file, server, port, local):
    nginx_type = "nginx_" + coll_type.split('.')[0].strip()

    if file_seek.has_key(nginx_type):
        offset_values = int(file_seek[nginx_type][0])
        file_size = int(file_seek[nginx_type][1])
    else:
        offset_values = 0
        file_size = 0

    logfile = open(file, 'r')

    '''seeklines信息是指从上次关闭文件的位置到此次打开文件的位置所包含的数据'''
    seeklines = seekfile(nginx_type, logfile, offset_values, file_size)
    logfile.close()

    nginx_status={'2XX':0,'3XX':0,'4XX':0,'5XX':0}

    if seeklines == "":
        nginx_status['2XX'] = 0
        nginx_status['3XX'] = 0
        nginx_status['4XX'] = 0
        nginx_status['5XX'] = 0
    else:
        for line in seeklines:
            status_tmp=line.strip().split('')[6]
            if int(status_tmp[:1]) in [2,3,4,5]:
                status = status_tmp[:1]+"XX"

            if nginx_status.has_key(status):
                nginx_status[status] += 1
            else:
                nginx_status[status] = 1

    #print nginx_status
    local_ip = local

    if local_ip:
        graphite_ip = local_ip.replace(".", "_")

    sc = StatsClient(server,port)
    for nginx_status, status_count in nginx_status.items():
        print nginx_status, status_count
        sc.gauge(graphite_ip+".nginx."+coll_type.split('.')[0].strip()+"."+nginx_status, int(status_count))
开发者ID:CursorCX,项目名称:pystatsd-collect,代码行数:46,代码来源:collect_pystatsd.py

示例7: check_fpm_slow

# 需要导入模块: from statsd import StatsClient [as 别名]
# 或者: from statsd.StatsClient import gauge [as 别名]
def check_fpm_slow(coll_type, file, server, port, local):
    fpm_slow_type = "fpm_slow_" + coll_type.split('.')[0].strip()

    if file_seek.has_key(fpm_slow_type):
        offset_values = int(file_seek[fpm_slow_type][0])
        file_size = int(file_seek[fpm_slow_type][1])
    else:
        offset_values = 0
        file_size = 0
    try:
        logfile = open(file, 'r')
        '''seeklines信息是指从上次关闭文件的位置到此次打开文件的位置所包含的数据'''
        seeklines = seekfile(fpm_slow_type, logfile, offset_values, file_size)
        logfile.close()
    except IOError as ioerr:
        print ioerr

    fpm_slow_status = {'slow_num' : 0}

    if seeklines == "":
        fpm_slow_status['slow_num'] = 0
    else:
        for line in seeklines:
            fpm_slow_match = re.match(r'(^\[+\d+-\w+-\d+\s+\d+:\d+:\d+\])\s(.*)',line)
            if fpm_slow_match != None:
                fpm_slow_status['slow_num'] += 1

    #print nginx_status
    local_ip = local

    if local_ip:
        graphite_ip = local_ip.replace(".", "_")

    sc = StatsClient(server,port)
    for fpm_status, fpm_count in fpm_slow_status.items():
        print fpm_status, fpm_count
        sc.gauge(graphite_ip+".fpm_slow."+coll_type.split('.')[0].strip()+"."+fpm_status, int(fpm_count))
开发者ID:CursorCX,项目名称:pystatsd-collect,代码行数:39,代码来源:collect_pystatsd.py

示例8: StatsD

# 需要导入模块: from statsd import StatsClient [as 别名]
# 或者: from statsd.StatsClient import gauge [as 别名]
class StatsD(object):
    def __init__(self, app=None, config=None):
        self.config = None
        self.statsd = None
        if app is not None:
            self.init_app(app)
        else:
            self.app = None

    def init_app(self, app, config=None):
        if config is not None:
            self.config = config
        elif self.config is None:
            self.config = app.config

        self.config.setdefault('STATSD_HOST', 'localhost')
        self.config.setdefault('STATSD_PORT', 8125)
        self.config.setdefault('STATSD_PREFIX', None)

        self.app = app

        self.statsd = StatsClient(self.config['STATSD_HOST'],
            self.config['STATSD_PORT'], self.config['STATSD_PREFIX'])

    def timer(self, *args, **kwargs):
        return self.statsd.timer(*args, **kwargs)

    def timing(self, *args, **kwargs):
        return self.statsd.timing(*args, **kwargs)

    def incr(self, *args, **kwargs):
        return self.statsd.incr(*args, **kwargs)

    def decr(self, *args, **kwargs):
        return self.statsd.decr(*args, **kwargs)

    def gauge(self, *args, **kwargs):
        return self.statsd.gauge(*args, **kwargs)

    def set(self, *args, **kwargs):
        return self.statsd.set(*args, **kwargs)
开发者ID:adsabs,项目名称:flask-statsd,代码行数:43,代码来源:flask_statsd.py

示例9: rtl_433_probe

# 需要导入模块: from statsd import StatsClient [as 别名]
# 或者: from statsd.StatsClient import gauge [as 别名]
def rtl_433_probe():
    statsd_host = "localhost"
    statsd_host = "127.0.0.1"
    statsd_port = 8125
    statsd_prefix = 'rtlsdr'

    statsd = StatsClient(host=statsd_host,
                         port=statsd_port,
                         prefix=statsd_prefix)

    while True:
        line = sys.stdin.readline()
        if not line:
            break
        try:
            data = json.loads(line)

            label = sanitize(data["model"])
            if "channel" in data:
                label += ".CH" + str(data["channel"])

            if "battery" in data:
                if data["battery"] == "OK":
                    statsd.gauge(label + '.battery', 1)
                else:
                    statsd.gauge(label + '.battery', 0)

            if "humidity" in data:
                statsd.gauge(label + '.humidity', data["humidity"])

            statsd.gauge(label + '.temperature', data["temperature_C"])

        except KeyError:
            pass

        except ValueError:
            pass
开发者ID:zuckschwerdt,项目名称:rtl_433_relay,代码行数:39,代码来源:rtl_433_statsd_pipe.py

示例10: StatsD

# 需要导入模块: from statsd import StatsClient [as 别名]
# 或者: from statsd.StatsClient import gauge [as 别名]
class StatsD(object):
    def __init__(self, app=None, config=None):
        self.config = None
        self.statsd = None
        if app is not None:
            self.init_app(app)
        else:
            self.app = None

    def init_app(self, app, config=None):
        if config is not None:
            self.config = config
        elif self.config is None:
            self.config = app.config

        self.config.setdefault("STATSD_HOST", "localhost")
        self.config.setdefault("STATSD_PORT", 8125)
        self.config.setdefault("STATSD_PREFIX", None)

        self.app = app

        self.statsd = StatsClient(
            host=self.config["STATSD_HOST"], port=self.config["STATSD_PORT"], prefix=self.config["STATSD_PREFIX"]
        )

    def timer(self, *args, **kwargs):
        return self.statsd.timer(*args, **kwargs)

    def timing(self, *args, **kwargs):
        return self.statsd.timing(*args, **kwargs)

    def incr(self, *args, **kwargs):
        return self.statsd.incr(*args, **kwargs)

    def decr(self, *args, **kwargs):
        return self.statsd.decr(*args, **kwargs)

    def gauge(self, *args, **kwargs):
        return self.statsd.gauge(*args, **kwargs)
开发者ID:tarzan0820,项目名称:flask-statsd,代码行数:41,代码来源:flask_statsd.py

示例11: str

# 需要导入模块: from statsd import StatsClient [as 别名]
# 或者: from statsd.StatsClient import gauge [as 别名]
    print "Temp storage file doesn't exist yet. Will tweet the current value and save it."

print "Previous number of cups was " + str(cups_old)

#Get current number of cups.
service = Config.get("PyCoffeeD", "url")
r = requests.get(service + "/servings")
assert r.status_code < 400, "Request to PyCoffeeD server failed."
cups_current = float(r.text)
print "Current number of cups is " + str(cups_current)

#Send the current number of cups to StatsD.
url = Config.get("StatsD", "url")
port = Config.get("StatsD", "port")
client = StatsClient(host=url, port=int(port), prefix="coffee.")
client.gauge("cups", value=cups_current, rate=1)

#Tweet the current number of cups, if it's changed significantly since the last tweet.
if (abs(cups_current - cups_old) > 1):
    print ("More than one cup difference between " + str(cups_current) 
        + " and " + str(cups_old) + ". Tweeting an update.")

    consumer_key = Config.get("Twitter", "consumer_key")
    consumer_secret = Config.get("Twitter", "consumer_secret")
    app_name = Config.get("Twitter", "app_name")

    twitter_creds = os.path.expanduser('./twitter_credentials')
    if not os.path.exists(twitter_creds):
        oauth_dance(app_name, consumer_key, consumer_secret,
                    twitter_creds)
开发者ID:kevineder,项目名称:PyCoffeeD,代码行数:32,代码来源:StatsJob.py

示例12: ReplicationLagChecker

# 需要导入模块: from statsd import StatsClient [as 别名]
# 或者: from statsd.StatsClient import gauge [as 别名]
class ReplicationLagChecker(object):

    def __init__(self, args):
        """ initialize the args and setup a stats client """
        self._source_host = args.source_host
        self._target_host = args.target_host
        self._replica_set = args.replica_set
        self._user = args.user
        self._password = args.password
        self._poll_interval = args.interval
        self._lag_key = args.region + '_' + args.replica_set + '_lag'
        # We assume a local collectd installation
        self._stat_client = StatsClient()

    def setup_source_db(self):
        """ setup the source mongo connection which is a replica set """
        conn = MongoReplicaSetClient(host=self._source_host,
                                     replicaSet=self._replica_set,
                                     read_preference=ReadPreference.PRIMARY)
        conn['admin'].authenticate(self._user, self._password)
        return conn

    def setup_target_db(self):
        """ setup the target mongo connection which is a standalone client """
        conn = MongoClient(host=self._target_host)
        conn['admin'].authenticate(self._user, self._password)
        return conn

    def run(self):

        """ Check the latest oplog from source oplog collection
            and the latest oplog from target mongo connector collection
            and compute the lag """
        try:
            source_conn = self.setup_source_db()
            target_conn = self.setup_target_db()
            target_collection = 'oplog' + self._replica_set

            while True:
                try:
                    # Induce an operation on the replication test database
                    db_name = 'ReplTest_' + self._replica_set.upper()
                    source_conn[db_name]['operation'].replace_one({'replica': self._replica_set}, {
                                                                  'replica': self._replica_set, 'ts': int(time.time())}, upsert=True)

                    # Wait a bit for it to replicate
                    time.sleep(10)

                    # check latest oplog of source
                    entry = source_conn['local'][
                        'oplog.rs'].find().sort('$natural', -1).limit(1)
                    source_oplog = entry[0]['ts'].time

                    # get latest oplog from connector target oplog collection
                    entry = target_conn['__mongo_connector'][
                        target_collection].find().sort('_ts', -1).limit(1)
                    target_oplog = entry[0]['_ts'] >> 32

                    lag = source_oplog - target_oplog
                    self._stat_client.gauge(self._lag_key, lag)

                    time.sleep(self._poll_interval)
                except Exception as ex:
                    logger.exception('Connection Failed, retrying..')
                    time.sleep(5)

        except Exception as ex:
            logger.exception('Critical Error, bailing out..')
开发者ID:Elastica,项目名称:mongo-connector,代码行数:70,代码来源:check_replication_lag.py

示例13: PostDB

# 需要导入模块: from statsd import StatsClient [as 别名]
# 或者: from statsd.StatsClient import gauge [as 别名]
class PostDB():

	def __init__(self,db_queue,database_config):
		mysql_endpoint = database_config['mysql_endpoint']
		mysql_user = database_config['mysql_user']
		mysql_port = database_config['mysql_port']
		mysql_dbname = database_config['mysql_dbname']
		mysql_pass = database_config['mysql_pass']
		statsd_ip = database_config['statsd_ip']
		statsd_port = database_config['statsd_port']
		self.opentsdb_url = database_config['opentsdb_url']
		query_tabname = database_config['mysql_table']['query_tab']
		table_tabname = database_config['mysql_table']['table_tab']
		query_scan_tab = database_config['mysql_table']['query_scan_tab']


		self.mysql_engine_string = mysql_endpoint+mysql_user+':'+mysql_pass+'@'+mysql_port+'/'+mysql_dbname
		self.db_queue = db_queue
		self.engine = create_engine(self.mysql_engine_string)
		self.Session = sessionmaker(bind=self.engine)
		self.session = self.Session()
		self.statsd = StatsClient(statsd_ip,statsd_port)
		self.RSQueryMonitor = self.get_query_object(query_tabname,self.engine)
		self.RSTableMonitor = self.get_table_object(table_tabname,self.engine)
		self.RSQueryScan = self.get_scan_object(query_scan_tab,self.engine)
	
	def post_db(self,metric_list):
		logging.info('%s : Waiting for json response on %d', log_identifier, os.getpid())
		#print '%s : Waiting for json response on %d' %(log_identifier, os.getpid())
		for i in range(0,len(metric_list)):
			payload = self.db_queue.get()
			logging.info('%s : JSON response received is %s', log_identifier, payload)
			#print '%s : JSON response received is %s' %(log_identifier, payload)
			for key in payload:
				if key == 'opentsdb':
					r = self.post_opentsdb(payload[key])
				elif key == 'mysql':
					self.post_mysql(payload[key])
				elif key == 'statsd':
					self.post_statsd(payload[key])

	def post_statsd(self,payload):
		for metric in range(0,len(payload)):
			for key in payload[metric]:
				self.statsd.gauge(key, payload[metric][key])

	def post_opentsdb(self,payload):
		r = requests.post(self.opentsdb_url,data=json.dumps(payload))
		logging.info('%s : HTTP response received is %s', log_identifier, r)
		print '%s : HTTP response received is %s' %(log_identifier, r)
		return r

	def post_mysql(self,payload):
		for key in payload:
			if key == 'rs_query_monitor':
				table_rows_list = payload[key]
				for row in table_rows_list:
					table_rows_dict = table_rows_list[row]
					if self.session.query(self.RSQueryMonitor).filter(self.RSQueryMonitor.query_id == table_rows_dict['query_id']).count() == 0:
						self.session.add(self.RSQueryMonitor(query_id=table_rows_dict['query_id'],username=table_rows_dict['username'].strip(),
							workmem=table_rows_dict['workmem'], num_diskhits=table_rows_dict['num_diskhits'], exec_time=table_rows_dict['exec_time'],
							queue_time=table_rows_dict['queue_time'], slot_count=table_rows_dict['slot_count'],
							starttime=table_rows_dict['starttime'],state=table_rows_dict['state'].strip(),queue=table_rows_dict['queue'],
							inner_bcast_count=table_rows_dict['inner_bcast_count'],bcast_rows=table_rows_dict['bcast_rows'],
							last_modified_on=datetime.datetime.utcnow()+ist_delta))
					else:
						row = self.session.query(self.RSQueryMonitor).filter(self.RSQueryMonitor.query_id == table_rows_dict['query_id']).first()
						row.queue = table_rows_dict['username'].strip()
						row.workmem = table_rows_dict['workmem']
						row.num_diskhits = table_rows_dict['num_diskhits'] + row.num_diskhits
						row.exec_time = table_rows_dict['exec_time']
						row.queue_time = table_rows_dict['queue_time']
						row.slot_count = table_rows_dict['slot_count']
						row.starttime = table_rows_dict['starttime']
						row.state = table_rows_dict['state'].strip()
						row.queue = table_rows_dict['queue']
						row.inner_bcast_count = table_rows_dict['inner_bcast_count']
						row.bcast_rows = table_rows_dict['bcast_rows']
						row.last_modified_on = datetime.datetime.utcnow()+ist_delta
				self.session.commit()
				max_lmd = self.session.query(func.max(self.RSQueryMonitor.last_modified_on)).all()[0][0]
				done_rows = self.session.query(self.RSQueryMonitor).filter(~self.RSQueryMonitor.state.in_('Done ')).filter(self.RSQueryMonitor.last_modified_on < max_lmd).all()
				for row in range(0,len(done_rows)):
					done_rows[row].state = 'Done'
				self.session.commit()
			if key == 'rs_table_monitor':
				table_rows_list = payload[key]
				for row in table_rows_list:
					table_rows_dict = table_rows_list[row]
					if self.session.query(self.RSTableMonitor).filter(and_(self.RSTableMonitor.schemaname == table_rows_dict['schemaname'].strip(), self.RSTableMonitor.tablename == table_rows_dict['tablename'].strip())).count() == 0:
						self.session.add(self.RSTableMonitor(schemaname=table_rows_dict['schemaname'].strip(),tablename=table_rows_dict['tablename'].strip(),pct_mem_used=table_rows_dict['pct_mem_used'],
							unsorted_rows=table_rows_dict['unsorted_rows'], statistics=table_rows_dict['statistics'], is_encoded=table_rows_dict['is_encoded'],diststyle=table_rows_dict['diststyle'],
							sortkey1=table_rows_dict['sortkey1'],skew_sortkey1=table_rows_dict['skew_sortkey1'],skew_rows=table_rows_dict['skew_rows'],m1_num_scan=table_rows_dict['m1_num_scan'],
							m1_row_scan=table_rows_dict['m1_row_scan'],m1_avg_time=table_rows_dict['m1_avg_time'],w1_num_scan=table_rows_dict['w1_num_scan'],w1_row_scan=table_rows_dict['w1_row_scan'],
							w1_avg_time=table_rows_dict['w1_avg_time'],d1_num_scan=table_rows_dict['d1_num_scan'],d1_row_scan=table_rows_dict['d1_row_scan'],d1_avg_time=table_rows_dict['d1_avg_time'],
							h6_num_scan=table_rows_dict['h6_num_scan'],h6_row_scan=table_rows_dict['h6_row_scan'], h6_avg_time=table_rows_dict['h6_avg_time'],h3_num_scan=table_rows_dict['h3_num_scan'],
							h3_row_scan=table_rows_dict['h3_row_scan'],h3_avg_time=table_rows_dict['h3_avg_time'],last_modified_on=datetime.datetime.utcnow()+ist_delta))
					else:
						row = self.session.query(self.RSTableMonitor).filter(and_(self.RSTableMonitor.schemaname == table_rows_dict['schemaname'].strip(), self.RSTableMonitor.tablename == table_rows_dict['tablename'].strip()))
						row.pct_mem_used = table_rows_dict['pct_mem_used']
#.........这里部分代码省略.........
开发者ID:myntra,项目名称:RedEye,代码行数:103,代码来源:post_db.py

示例14: Server

# 需要导入模块: from statsd import StatsClient [as 别名]
# 或者: from statsd.StatsClient import gauge [as 别名]
class Server():

	def __init__(self, args):
		# Setup logging - Generate a default rotating file log handler and stream handler
		logFileName = 'connector-statsd.log'
		fhFormatter = logging.Formatter('%(asctime)-25s %(levelname)-7s %(message)s')
		sh = logging.StreamHandler()
		sh.setFormatter(fhFormatter)
		
		self.logger = logging.getLogger("server")
		self.logger.addHandler(sh)
		self.logger.setLevel(logging.DEBUG)
		
		
		self.port = int(os.getenv('VCAP_APP_PORT', '9666'))
		self.host = str(os.getenv('VCAP_APP_HOST', 'localhost'))

		if args.bluemix == True:
			self.options = ibmiotf.application.ParseConfigFromBluemixVCAP()
		else:
			if args.token is not None:
				self.options = {'auth-token': args.token, 'auth-key': args.key}
			else:
				self.options = ibmiotf.application.ParseConfigFile(args.config)
		
		# Bottle
		self._app = Bottle()
		self._route()
		
		# Init IOTF client
		self.client = ibmiotf.application.Client(self.options, logHandlers=[sh])
	
		# Init statsd client
		if args.statsd:
			self.statsdHost = args.statsd
		else: 
			self.statsdHost = "localhost"
		
		self.statsd = StatsClient(self.statsdHost, prefix=self.client.orgId)
		
	
	def _route(self):
		self._app.route('/', method="GET", callback=self._status)
	
	
	def myEventCallback(self, evt):
		try:
			flatData = flattenDict(evt.data, join=lambda a,b:a+'.'+b)
			
			self.logger.debug("%-30s%s" % (evt.device, evt.event + ": " + json.dumps(flatData)))
			
			eventNamespace = evt.deviceType +  "." + evt.deviceId + "." + evt.event
			
			self.statsd.incr("events.meta." + eventNamespace)
			for datapoint in flatData:
				eventDataNamespace = "events.data." + eventNamespace + "." + datapoint[0]
				# Pass through numeric data
				# Convert boolean datapoints to numeric 0|1 representation
				# Throw away everything else (e.g. String data)
				if isinstance(datapoint[1], bool):
					if datapoint[1] == True:
						self.statsd.gauge(eventDataNamespace, 1)
					else:
						self.statsd.gauge(eventDataNamespace, 0)
				elif isinstance(datapoint[1], Number):
					self.statsd.gauge(eventDataNamespace, datapoint[1])
		except Exception as e:
			self.logger.critical("%-30s%s" % (evt.device, evt.event + ": Exception processing event - " + str(e)))
			#self.logger.critical(json.dumps(evt.data))

	def start(self):
		self.client.connect()
		self.client.deviceEventCallback = self.myEventCallback
		self.client.subscribeToDeviceEvents()
		self.logger.info("Serving at %s:%s" % (self.host, self.port))
		self._app.run(host=self.host, port=self.port)
	
	def stop(self):
		self.client.disconnect()
		
	def _status(self):
		return template('status', env_options=os.environ)
开发者ID:ibm-watson-iot,项目名称:connector-statsd,代码行数:84,代码来源:connector-statsd.py

示例15: report_to_graphite

# 需要导入模块: from statsd import StatsClient [as 别名]
# 或者: from statsd.StatsClient import gauge [as 别名]
def report_to_graphite(host, port, prefix, results):
    statsd = StatsClient(host=host, port=port, prefix=prefix, maxudpsize=512)
    for entry in results:
        statsd.gauge(entry['graphite key'], entry['count'])
开发者ID:zbigniewz,项目名称:jenkins-build-failure-analyzer,代码行数:6,代码来源:analyzer.py


注:本文中的statsd.StatsClient.gauge方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。