當前位置: 首頁>>代碼示例>>Python>>正文


Python prometheus_client.Counter方法代碼示例

本文整理匯總了Python中prometheus_client.Counter方法的典型用法代碼示例。如果您正苦於以下問題:Python prometheus_client.Counter方法的具體用法?Python prometheus_client.Counter怎麽用?Python prometheus_client.Counter使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在prometheus_client的用法示例。


在下文中一共展示了prometheus_client.Counter方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: create_metric

# 需要導入模塊: import prometheus_client [as 別名]
# 或者: from prometheus_client import Counter [as 別名]
def create_metric(self):
        # record app conf
        self.conf_info = Info('celery_conf_info','APP_CONF')
        self.conf_info_c = CollectorRegistry()

        # monitor worker info
        self.workers_info = Info('celery_workers_info', 'WORKER_INFO')
        self.workers_info_c = CollectorRegistry()

        # monitor worker info real-time
        self.workers_state = Gauge('celery_workers_state', 'WORKER_STATE', ['worker'])
        self.workers_state_c = CollectorRegistry()
        self.workers_processed = Gauge('celery_processed_tasks_total', 'WORKER_TASKS_PROCESSED', ['worker'])
        self.workers_processed_c = CollectorRegistry()
        self.workers_active = Gauge('celery_active_tasks_total', 'WORKER_TASKS_ACTIVE', ['worker'])
        self.workers_active_c = CollectorRegistry()

        # monitor tasks info
        self.tasks_counter = Counter('celery_tasks_total', 'TASK_COUNT_INFO', ['worker','task','result'])
        self.tasks_counter_c = CollectorRegistry()
        self.tasks_runtime = Summary('celery_tasks_seconds', 'TASK_RUNTIME', ['worker', 'task'])
        self.tasks_runtime_c = CollectorRegistry()
        self.tasks_info = Info('celery_tasks_info', 'TASK_INFO')
        self.tasks_info_c = CollectorRegistry() 
開發者ID:adrianyoung,項目名稱:CrawlerMonitor,代碼行數:26,代碼來源:monitor.py

示例2: start_http_server

# 需要導入模塊: import prometheus_client [as 別名]
# 或者: from prometheus_client import Counter [as 別名]
def start_http_server(config, port, address=''):
    """
    Start a HTTP API server for Proxmox VE prometheus collector.
    """

    duration = Summary(
        'pve_collection_duration_seconds',
        'Duration of collections by the PVE exporter',
        ['module'],
    )
    errors = Counter(
        'pve_request_errors_total',
        'Errors in requests to PVE exporter',
        ['module'],
    )

    # Initialize metrics.
    for module in config.keys():
        # pylint: disable=no-member
        errors.labels(module)
        # pylint: disable=no-member
        duration.labels(module)

    app = PveExporterApplication(config, duration, errors)
    run_simple(address, port, app, threaded=True) 
開發者ID:prometheus-pve,項目名稱:prometheus-pve-exporter,代碼行數:27,代碼來源:http.py

示例3: __init__

# 需要導入模塊: import prometheus_client [as 別名]
# 或者: from prometheus_client import Counter [as 別名]
def __init__(self, data_manager, config):
        self.config = config
        self.data_manager = data_manager
        self.http_server = prometheus_client.start_http_server(
            self.config.prometheus_port,
            addr=self.config.prometheus_addr
        )
        self.updated_containers_counter = prometheus_client.Counter(
            'containers_updated',
            'Count of containers updated',
            ['socket', 'container']
        )
        self.monitored_containers_gauge = prometheus_client.Gauge(
            'containers_being_monitored',
            'Gauge of containers being monitored',
            ['socket']
        )
        self.updated_all_containers_gauge = prometheus_client.Gauge(
            'all_containers_updated',
            'Count of total updated',
            ['socket']
        )
        self.logger = getLogger() 
開發者ID:pyouroboros,項目名稱:ouroboros,代碼行數:25,代碼來源:dataexporters.py

示例4: counter

# 需要導入模塊: import prometheus_client [as 別名]
# 或者: from prometheus_client import Counter [as 別名]
def counter(self, name, description, labels=None, **kwargs):
        """
        Use a Counter to track the total number of invocations of the method.

        :param name: the name of the metric
        :param description: the description of the metric
        :param labels: a dictionary of `{labelname: callable_or_value}` for labels
        :param kwargs: additional keyword arguments for creating the Counter
        """

        return self._track(
            Counter,
            lambda metric, time: metric.inc(),
            kwargs, name, description, labels,
            registry=self.registry
        ) 
開發者ID:rycus86,項目名稱:prometheus_flask_exporter,代碼行數:18,代碼來源:__init__.py

示例5: __init__

# 需要導入模塊: import prometheus_client [as 別名]
# 或者: from prometheus_client import Counter [as 別名]
def __init__(self) -> None:
        self.registry = prometheus_client.CollectorRegistry()
        _labels = ["project", "smpp_command", "state", "response_code"]
        self.counter = prometheus_client.Counter(
            name="number_of_messages",
            documentation="number of messages processed by naz.",
            labelnames=_labels,
            registry=self.registry,
        )
        self._LOOP: typing.Union[None, asyncio.events.AbstractEventLoop] = None
        self.thread_name_prefix = "naz_benchmarks_hook_pool"

        # go to prometheus dashboard(http://localhost:9000/) & you can run queries like:
        # 1. container_memory_rss{name="naz_cli", container_label_com_docker_compose_service="naz_cli"}
        # 2. container_memory_rss{name=~"naz_cli|message_producer"}
        # 3. number_of_messages_total{project="naz_benchmarks"}
        # 4. rate(number_of_messages_total{smpp_command="submit_sm",state="request"}[30s])  # msg sending over the past 30seconds 
開發者ID:komuw,項目名稱:naz,代碼行數:19,代碼來源:my_hook.py

示例6: __init__

# 需要導入模塊: import prometheus_client [as 別名]
# 或者: from prometheus_client import Counter [as 別名]
def __init__(self, conn, args):
        self.conn = conn
        self.args = args
        self.ha_enabled = get_env("INFRABOX_HA_ENABLED")
        self.monitoring_enabled = get_env("INFRABOX_MONITORING_ENABLED")
        self.namespace = get_env("INFRABOX_GENERAL_SYSTEM_NAMESPACE")
        self.check_interval = int(get_env('INFRABOX_HA_CHECK_INTERVAL'))
        self.active_timeout = get_env('INFRABOX_HA_ACTIVE_TIMEOUT')
        self.cluster_name = get_env('INFRABOX_CLUSTER_NAME')
        self.logger = get_logger("checker")
        self.root_url = get_env("INFRABOX_ROOT_URL")
        self.is_cluster_healthy = True
        self.retry_times = 0
        self.max_retry_times = 3
        self.infrabox_api_call_errors = Counter(
            'infrabox_api_errors_total', 
            'Errors in requests to InfraBox API')
        self.storage_checker_errors = Counter(
            'storage_checker_errors_total', 
            'Errors uploding/downloading files to/from storage')
        self.infrabox_dashboard_access_errors = Counter(
            'infrabox_dashboard_access_errors_total', 
            'Errors acessing dashboard')
        self.slack = CheckerSlackHook.get_from_env(self.logger) 
開發者ID:SAP,項目名稱:InfraBox,代碼行數:26,代碼來源:checker.py

示例7: test_prometheus_counter

# 需要導入模塊: import prometheus_client [as 別名]
# 或者: from prometheus_client import Counter [as 別名]
def test_prometheus_counter():
    @solid(required_resource_keys={'prometheus'})
    def prometheus_solid(context):
        c = Counter(
            'some_counter_seconds',
            'Description of this counter',
            registry=context.resources.prometheus.registry,
        )
        c.inc()
        c.inc(1.6)
        recorded = context.resources.prometheus.registry.get_sample_value(
            'some_counter_seconds_total'
        )
        assert abs(2.6 - recorded) < EPS

    assert execute_solid(prometheus_solid, run_config=ENV, mode_def=MODE).success 
開發者ID:dagster-io,項目名稱:dagster,代碼行數:18,代碼來源:test_resources.py

示例8: get_prometheus_counter

# 需要導入模塊: import prometheus_client [as 別名]
# 或者: from prometheus_client import Counter [as 別名]
def get_prometheus_counter(self):
        registry = self.get_prometheus_registry()
        if not registry or not prometheus_client:
            return
        counter = getattr(registry, '_openstacksdk_counter', None)
        if not counter:
            counter = prometheus_client.Counter(
                'openstack_http_requests',
                'Number of HTTP requests made to an OpenStack service',
                labelnames=[
                    'method', 'endpoint', 'service_type', 'status_code'
                ],
                registry=registry,
            )
            registry._openstacksdk_counter = counter
        return counter 
開發者ID:openstack,項目名稱:openstacksdk,代碼行數:18,代碼來源:cloud_region.py

示例9: validate_metrics

# 需要導入模塊: import prometheus_client [as 別名]
# 或者: from prometheus_client import Counter [as 別名]
def validate_metrics(self, metric_name, help_text, increments):
        """
        WSGI app serves the metrics from the provided registry.
        """
        c = Counter(metric_name, help_text, registry=self.registry)
        for _ in range(increments):
            c.inc()
        # Create and run WSGI app
        app = make_wsgi_app(self.registry)
        outputs = app(self.environ, self.capture)
        # Assert outputs
        self.assertEqual(len(outputs), 1)
        output = outputs[0].decode('utf8')
        # Status code
        self.assertEqual(self.captured_status, "200 OK")
        # Headers
        self.assertEqual(len(self.captured_headers), 1)
        self.assertEqual(self.captured_headers[0], ("Content-Type", CONTENT_TYPE_LATEST))
        # Body
        self.assertIn("# HELP " + metric_name + "_total " + help_text + "\n", output)
        self.assertIn("# TYPE " + metric_name + "_total counter\n", output)
        self.assertIn(metric_name + "_total " + str(increments) + ".0\n", output) 
開發者ID:prometheus,項目名稱:client_python,代碼行數:24,代碼來源:test_wsgi.py

示例10: test_reports_metrics

# 需要導入模塊: import prometheus_client [as 別名]
# 或者: from prometheus_client import Counter [as 別名]
def test_reports_metrics(self):
        """
        ``MetricsResource`` serves the metrics from the provided registry.
        """
        c = Counter('cc', 'A counter', registry=self.registry)
        c.inc()

        root = Resource()
        root.putChild(b'metrics', MetricsResource(registry=self.registry))
        server = reactor.listenTCP(0, Site(root))
        self.addCleanup(server.stopListening)

        agent = Agent(reactor)
        port = server.getHost().port
        url = "http://localhost:{port}/metrics".format(port=port)
        d = agent.request(b"GET", url.encode("ascii"))

        d.addCallback(readBody)
        d.addCallback(self.assertEqual, generate_latest(self.registry))

        return d 
開發者ID:prometheus,項目名稱:client_python,代碼行數:23,代碼來源:test_twisted.py

示例11: expose_metrics

# 需要導入模塊: import prometheus_client [as 別名]
# 或者: from prometheus_client import Counter [as 別名]
def expose_metrics(metrics, cluster_name=""):
    """Adaptor to notify prometheus of Cassandra's metrics change."""
    metrics_adp = {}

    def counter_adaptor(cpt, fn):
        def inner(*args, **kwargs):
            cpt.inc()
            fn(*args, **kwargs)

        return inner

    for attr in dir(metrics):
        if attr.startswith("on_"):
            metric_name = "bg_cassandra_" + cluster_name + "_" + attr[3:]
            cpt = prometheus_client.Counter(metric_name, "")
            metrics_adp[metric_name] = cpt
            setattr(metrics, attr, counter_adaptor(cpt, attr))

    return metrics_adp 
開發者ID:criteo,項目名稱:biggraphite,代碼行數:21,代碼來源:cassandra.py

示例12: counter_inc

# 需要導入模塊: import prometheus_client [as 別名]
# 或者: from prometheus_client import Counter [as 別名]
def counter_inc(name, step=1, description="", **kwargs):
    global metrics

    if not enabled:
        return True

    try:
        if name not in metrics:
            metrics[name] = Counter(name, description, list(kwargs.keys()))

        if kwargs:
            metrics[name].labels(**kwargs).inc(step)
        else:
            metrics[name].inc(step)

    except Exception as err:
        logger.warn("adding metric failed - exception: " + str(err))

    return True 
開發者ID:anchore,項目名稱:anchore-engine,代碼行數:21,代碼來源:metrics.py

示例13: poll_mock

# 需要導入模塊: import prometheus_client [as 別名]
# 或者: from prometheus_client import Counter [as 別名]
def poll_mock():
    registry = CollectorRegistry()
    g1 = Gauge('metric1', 'processor usage', ['matched_label', 'node', 'flavor'], registry=registry)
    g1.labels(matched_label="foobar", node="host1", flavor="test").set(99.9)
    g2 = Gauge('metric2', 'memory usage', ['matched_label', 'node', 'timestamp'], registry=registry)
    g2.labels(matched_label="foobar", node="host2", timestamp="123").set(12.2)
    c1 = Counter('counter1', 'hits', ['node'], registry=registry)
    c1.labels(node="host2").inc(42)
    g3 = Gauge('metric3', 'memory usage', ['matched_label', 'node', 'timestamp'], registry=registry)
    g3.labels(matched_label="foobar", node="host2", timestamp="456").set(float('inf'))

    poll_mock_patch = mock.patch(
        'requests.get',
        return_value=mock.MagicMock(
            status_code=200,
            iter_lines=lambda **kwargs: ensure_unicode(generate_latest(registry)).split("\n"),
            headers={'Content-Type': "text/plain"},
        ),
    )
    with poll_mock_patch:
        yield 
開發者ID:DataDog,項目名稱:integrations-core,代碼行數:23,代碼來源:conftest.py

示例14: init

# 需要導入模塊: import prometheus_client [as 別名]
# 或者: from prometheus_client import Counter [as 別名]
def init(app, latency_buckets=None, multiprocess_mode='all',
         memcollect_enabled=True, metrics_list=None):
    app.metrics['RQS_COUNT'] = Counter(
        'sanic_request_count',
        'Sanic Request Count',
        ['method', 'endpoint', 'http_status']
    )

    hist_kwargs = {}
    if latency_buckets is not None:
        hist_kwargs = {'buckets': latency_buckets}
    app.metrics['RQS_LATENCY'] = Histogram(
        'sanic_request_latency_sec',
        'Sanic Request Latency Histogram',
        ['method', 'endpoint', 'http_status'],
        **hist_kwargs
    )

    if memcollect_enabled:
        app.metrics['PROC_RSS_MEM_BYTES'] = Gauge(
            'sanic_mem_rss_bytes',
            'Resident memory used by process running Sanic',
            multiprocess_mode=multiprocess_mode
        )
        app.metrics['PROC_RSS_MEM_PERC'] = Gauge(
            'sanic_mem_rss_perc',
            'A per cent of total physical memory used by ' +
            'the process running Sanic',
            multiprocess_mode=multiprocess_mode
        )

    if metrics_list:
        for name, pm_metric in metrics_list:
            app.metrics[name] = pm_metric 
開發者ID:dkruchinin,項目名稱:sanic-prometheus,代碼行數:36,代碼來源:metrics.py

示例15: set_counter

# 需要導入模塊: import prometheus_client [as 別名]
# 或者: from prometheus_client import Counter [as 別名]
def set_counter(name, *args, **kwargs):
    metrics[name] = Counter(name, *args, **kwargs) 
開發者ID:desec-io,項目名稱:desec-stack,代碼行數:4,代碼來源:metrics.py


注:本文中的prometheus_client.Counter方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。