• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python statsd.StatsClient类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: StatsDBackend

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,代码行数:25,代码来源:flask_stats.py


示例2: main

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,代码行数:26,代码来源:basin_sendstate.py


示例3: _Statsd

class _Statsd(object):
    def __init__(self, config):
        if config.get('datadog', True):
            initialize(statsd_host=config['host'],
                       statsd_port=config['port'],
                       prefix=config['prefix'])
            self.datadog = True
            self._statsd = statsd
        else:
            self.datadog = False
            self._statsd = StatsClient(config['host'],
                                       config['port'],
                                       config['prefix'])

    def incr(self, metric, count=1, rate=1, **kw):
        if self.datadog:
            return self._statsd.increment(metric, value=count,
                                          sample_rate=rate, **kw)
        else:
            return self._statsd.incr(metric, count=count, rate=rate)

    def timer(self, metric, rate=1, **kw):
        if self.datadog:
            return self._statsd.timed(metric, sample_rate=rate, **kw)
        else:
            return self._statsd.timer(metric, rate=rate)
开发者ID:armenzg,项目名称:absearch,代码行数:26,代码来源:server.py


示例4: FlaskStat

class FlaskStat(object):

    _xstat_title = None
    _xstat_host = None
    _xstat_port = None

    _stat_client = None

    def __init__(self, app=None):
        super(FlaskStat, self).__init__()

        if app:
            self.init_app(app)

    def init_app(self, app):
        from flask import request, g
        """
        绑定app
        """
        self._xstat_title = app.config.get('XSTAT_TITLE')
        self._xstat_host = app.config.get('XSTAT_HOST')
        self._xstat_port = app.config.get('XSTAT_PORT') or constants.XSTAT_PORT
        self._stat_client = StatsClient(host=self._xstat_host, port=self._xstat_port)

        @app.before_request
        @catch_exc
        def prepare_stat():
            if not request.endpoint:
                return

            g.xstat_timers = []
            g.xstat_timers.append(
                self._stat_client.timer('.'.join([
                    self._xstat_title,
                    'endpoint',
                    request.endpoint,
                    ])
                )
            )

            g.xstat_timers.append(
                self._stat_client.timer('.'.join([
                    self._xstat_title,
                    'all',
                    ])
                )
            )

            for stat in g.xstat_timers:
                stat.start()

        @app.teardown_request
        @catch_exc
        def send_stat(exc):
            if not hasattr(g, 'xstat_timers'):
                return

            for stat in g.xstat_timers:
                stat.stop()
开发者ID:bihicheng,项目名称:xstat,代码行数:59,代码来源:flask_stat.py


示例5: _udp_client

def _udp_client(prefix=None, addr=None, port=None, ipv6=False):
    if not addr:
        addr = ADDR[0]
    if not port:
        port = ADDR[1]
    sc = StatsClient(host=addr, port=port, prefix=prefix, ipv6=ipv6)
    sc._sock = mock.Mock()
    return sc
开发者ID:haron,项目名称:pystatsd,代码行数:8,代码来源:tests.py


示例6: send_stats

def send_stats(last_timestamp, last_message_count, json_filename):
	with open(json_filename) as data_file:
		data = json.load(data_file)

	current_timestamp = data["now"]
	current_message_count = data["messages"]

	secs = False
	msgs = False

	if last_timestamp is False:
		print "Starting up, first pass...."
	elif current_message_count < last_message_count:
		print "Looks like dump1090 restarted, message count reset (%d)" % current_message_count
	else:
		secs = current_timestamp - last_timestamp
		msgs = current_message_count - last_message_count
		
		print "{0} sec\t{1} messages\t{2} messages per sec avg".format(secs, msgs, (msgs / secs))

	last_timestamp = current_timestamp
	last_message_count = current_message_count
	threading.Timer(INTERVAL, send_stats, [last_timestamp, last_message_count, json_filename]).start()

	aircrafts_5s = []
	aircrafts_10s = []
	aircrafts_30s = []
	aircrafts_60s = []

	for aircraft in data["aircraft"]:
		if aircraft["seen"] < 5:
			aircrafts_5s.append(aircraft["hex"])
		if aircraft["seen"] < 10:
			aircrafts_10s.append(aircraft["hex"])
		if aircraft["seen"] < 30:
			aircrafts_30s.append(aircraft["hex"])
		if aircraft["seen"] < 60:
			aircrafts_60s.append(aircraft["hex"])

	print "\t5s:{0}\t10s:{1}\t30s:{2}\t60s:{3}".format(len(aircrafts_5s), len(aircrafts_10s), len(aircrafts_30s), len(aircrafts_60s))

	radio_name = sys.argv[1]

	if secs:
		client = StatsClient(STATSD_HOST)
		client.incr("radios.%s.message_rate" % radio_name, msgs)

		pipe = client.pipeline()
		c = 0
		max_msg_size = 20
		for hex in aircrafts_10s:
			pipe.set("radios.%s.aircraft" % radio_name, hex)
			c = c + 1
			if c == max_msg_size:
				pipe.send()
				c = 0
		if c != max_msg_size:
			pipe.send()
开发者ID:dsilvers,项目名称:dump1090-statsd,代码行数:58,代码来源:aircraft-to-statsd.py


示例7: MapleStat

class MapleStat(object):

    _xstat_title = None
    _xstat_host = None
    _xstat_port = None

    _stat_client = None

    def __init__(self, app=None, config=None):
        super(MapleStat, self).__init__()

        if app:
            self.init_app(app, config)

    def init_app(self, app, config):
        """
        绑定app
        """
        self._xstat_title = config.get('XSTAT_TITLE')
        self._xstat_host = config.get('XSTAT_HOST')
        self._xstat_port = config.get('XSTAT_PORT') or constants.XSTAT_PORT
        self._stat_client = StatsClient(host=self._xstat_host, port=self._xstat_port)

        @app.before_request
        @catch_exc
        def prepare_stat(request):
            if not request.endpoint:
                return

            request.xstat_timers = []
            request.xstat_timers.append(
                self._stat_client.timer('.'.join([
                    self._xstat_title,
                    'endpoint',
                    request.endpoint,
                    ])
                )
            )

            request.xstat_timers.append(
                self._stat_client.timer('.'.join([
                    self._xstat_title,
                    'all',
                    ])
                )
            )

            for stat in request.xstat_timers:
                stat.start()

        @app.after_request
        @catch_exc
        def send_stat(request, exc):
            if not hasattr(request, 'xstat_timers'):
                return

            for stat in request.xstat_timers:
                stat.stop()
开发者ID:bihicheng,项目名称:xstat,代码行数:58,代码来源:maple_stat.py


示例8: DjangoStat

class DjangoStat(MiddlewareMixin):
    _xstat_title = None
    _xstat_host = None
    _xstat_port = None

    _stat_client = None

    def __init__(self, *args, **kwargs):
        from django.conf import settings

        super(DjangoStat, self).__init__(*args, **kwargs)

        self._xstat_title = getattr(settings, 'XSTAT_TITLE', None)
        self._xstat_host = getattr(settings, 'XSTAT_HOST', None)
        self._xstat_port = getattr(settings, 'XSTAT_PORT', None) or constants.XSTAT_PORT

        self._stat_client = StatsClient(host=self._xstat_host, port=self._xstat_port)

    @catch_exc
    def process_view(self, request, view_func, view_args, view_kwargs):
        """
        request.resolver_match.url_name 在process_view才可以取到
        :return:
        """
        request.xstat_timers = []
        request.xstat_timers.append(
            self._stat_client.timer('.'.join([
                self._xstat_title,
                'endpoint',
                request.resolver_match.url_name,
                ])
            )
        )

        request.xstat_timers.append(
            self._stat_client.timer('.'.join([
                self._xstat_title,
                'all',
                ])
            )
        )

        for stat in request.xstat_timers:
            stat.start()

    @catch_exc
    def process_response(self, request, response):
        """
        无论是否抛出异常,都会执行这一步
        """
        if not hasattr(request, 'xstat_timers'):
            return response

        for stat in request.xstat_timers:
            stat.stop()

        return response
开发者ID:dantezhu,项目名称:xstat,代码行数:57,代码来源:django_stat.py


示例9: _udp_client

def _udp_client(prefix=None, addr=None, port=None, ipv6=False):
    if not addr:
        addr = ADDR[0]
    if not port:
        port = ADDR[1]
    sc = StatsClient(host=addr, port=port, prefix=prefix, ipv6=ipv6)
    sc._pool = fake_socket_pool()
    sc._sock = sc._pool.get()
    return sc
开发者ID:woodsaj,项目名称:pystatsd,代码行数:9,代码来源:tests.py


示例10: time_stack_list

def time_stack_list(username, password, tenant, auth_url, heat_url, region,
                    statsd_server):
    keystone = keystone_client(username=username, password=password,
                               tenant_name=tenant, auth_url=auth_url)
    token = keystone.auth_token
    heat = heat_client('1', endpoint=heat_url, region_name=region, token=token)
    statsd = StatsClient(host=statsd_server)

    with statsd.timer('uptime.{}'.format(region)):
        list(heat.stacks.list())
开发者ID:rackerlabs,项目名称:heat-uptime,代码行数:10,代码来源:uptime.py


示例11: test_disabled_client

def test_disabled_client():
    """ Assert that a cliend with disabled=True does not send any data to
    statsd.
    """
    sc = StatsClient(host=ADDR[0], port=ADDR[1], disable=True)
    sc._sock = mock.Mock()

    sc.incr('foo')

    eq_(sc._sock.call_count, 0)
开发者ID:tiriplicamihai,项目名称:pystatsd,代码行数:10,代码来源:tests.py


示例12: rtl_433_probe

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,代码行数:32,代码来源:rtl_433_statsd_relay.py


示例13: StaticticStatsD

class StaticticStatsD(object):
    """
    Send stats to statsd.
    """
    def __init__(self, hostname, host, port, prefix=None):
        self.client = StatsClient(host, port, prefix=prefix)
        self.hostname = hostname

    def incr(self, metric, value=1, prefix=None):
        """
        Increment 'metric' counter with 'value'.
        """
        if prefix is not None:
            metric = '%s.%s' % (prefix, metric)

        self.client.incr(metric, value)

        # separate metric for hostname
        if self.hostname is not None:
            metric = '%s.%s' % (self.hostname, metric)
            self.client.incr(metric, value)

    def timing(self, metric, value, prefix=None):
        """
        Send 'metric' timing.
        """
        if prefix is not None:
            metric = '%s.%s' % (prefix, metric)

        self.client.timing(metric, value)

        # separate metric for hostname
        if self.hostname is not None:
            metric = '%s.%s' % (self.hostname, metric)
            self.client.timing(metric, value)
开发者ID:dreadatour,项目名称:gossip,代码行数:35,代码来源:stats.py


示例14: StatsdStatsLogger

    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,代码行数:27,代码来源:stats_logger.py


示例15: setUp

	def setUp(self):

		sqsregioninfo = SQSRegionInfo(name='localhost_region', endpoint='localhost')
		self.connection = sqsregioninfo.connect(
			port=8001,
			aws_access_key_id='id',
			aws_secret_access_key='secret',
			is_secure=False
		)

		self.queue = self.connection.create_queue('test_queue')

		client = StatsClient(host='localhost', port=8125, prefix=None, maxudpsize=512)

		self.statsd = client.pipeline()
开发者ID:ralfas,项目名称:turok,代码行数:15,代码来源:test_fetch.py


示例16: __init__

 def __init__(self):
     self.statsd = StatsClient(
         host=STATSD_HOST,
         port=STATSD_PORT,
         prefix=STATSD_PREFIX,
         maxudpsize=512)
     self.last_vals = self.get_stats()
     sleep(5)
开发者ID:relix42,项目名称:monitoy,代码行数:8,代码来源:per_ip.py


示例17: __init__

    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'])
开发者ID:gabrielpjordao,项目名称:flask-stats,代码行数:9,代码来源:flask_stats.py


示例18: check_nginx_status

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,代码行数:44,代码来源:collect_pystatsd.py


示例19: __init__

    def __init__(self, *args, **kwargs):
        from django.conf import settings

        super(DjangoStat, self).__init__(*args, **kwargs)

        self._xstat_title = getattr(settings, 'XSTAT_TITLE', None)
        self._xstat_host = getattr(settings, 'XSTAT_HOST', None)
        self._xstat_port = getattr(settings, 'XSTAT_PORT', None) or constants.XSTAT_PORT

        self._stat_client = StatsClient(host=self._xstat_host, port=self._xstat_port)
开发者ID:dantezhu,项目名称:xstat,代码行数:10,代码来源:django_stat.py


示例20: __init__

 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()
开发者ID:Elastica,项目名称:mongo-connector,代码行数:11,代码来源:check_replication_lag.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python statsd.gauge函数代码示例发布时间:2022-05-27
下一篇:
Python views.render_json函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap