11"""Entry point for collector sub module."""
2- import random
3- import time
2+ import inflection
3+ import logging
44
5- from prometheus_client .core import GaugeMetricFamily
5+ from importlib import import_module
6+ from prometheus_client .core import REGISTRY
67
78
89class CollectorConfig (object ):
@@ -16,6 +17,7 @@ def __init__(self, **kwargs):
1617 :raises Exception: Raises an exception if credentials are not well configured.
1718 """
1819 self .exporter_name = kwargs .pop ('exporter_name' , None )
20+ self .collectors = kwargs .pop ('collectors' , [])
1921 self .credentials = kwargs .pop ('credentials' , None )
2022
2123 # do some fancy checks on configuration parameters
@@ -27,23 +29,25 @@ def __init__(self, **kwargs):
2729 raise Exception ('Credential is not fully configured.' )
2830
2931
30- class MyCollector (object ):
31- """A sample collector .
32+ class Collector (object ):
33+ """Base class to load collectors .
3234
33- It does not really do much. It only runs a method and return the time it runs as a gauge metric.
35+ All collectors have to be placed inside the directory `collector`. You have to follow the naming convention:
36+
37+ 1. Place the collector code in a <name>.py file (e.g. `my.py`)
38+ 2. Within the file <name>.py` a class <Name>Collector (e.g. `MyController`) needs to be defined.
39+ This is the main collector class which will be imported, instantiate and registered automatically.
3440 """
3541
3642 def __init__ (self , config : CollectorConfig ):
37- """Instanciate a MyCollector object."""
38- pass
39-
40- def collect (self ):
41- """Collect the metrics."""
42- self .timer = time .perf_counter ()
43- _run_process ()
44- runtime = time .perf_counter () - self .timer
45- yield GaugeMetricFamily ('my_process_runtime' , 'Time a process runs in seconds' , value = runtime )
46-
47- def _run_process ():
48- """Sample function to ran a command for metrics."""
49- time .sleep (random .random ()) # nosec
43+ for c in config .collectors :
44+ try :
45+ collector_module = import_module ("p3exporter.collector.{}" .format (c ), package = None )
46+ collector_class = getattr (collector_module , "{0}Collector" .format (inflection .camelize (c )))
47+ collector = collector_class (config )
48+ REGISTRY .register (collector )
49+ logging .info ("Collector '{0}' was loaded and registred sucessfully" .format (c ))
50+ except ModuleNotFoundError as e :
51+ logging .warning ("Collector '{0}' not loaded: {1}" .format (c , e .msg ))
52+ except AttributeError as e :
53+ logging .warning ("Collector '{0}' not loaded: {1}" .format (c , e ))
0 commit comments