mirror of
https://github.com/hikhvar/mqtt2prometheus.git
synced 2026-08-23 21:16:15 +00:00
As mentioned in https://github.com/hikhvar/mqtt2prometheus/issues/23, we do not use any logging framework at all. This was fine for getting the exporter startet. However, with inreasing load the logging must be configureable. This PR is a start to replace all instances of "log.Printf" with the zap logger. The current configuration parameters are the log level and the log format (console, json). We might expose the log configuration to the config file. But I think this is overkill for the current state of the exporter.
69 lines
1.6 KiB
Go
69 lines
1.6 KiB
Go
package metrics
|
|
|
|
import (
|
|
"time"
|
|
|
|
"github.com/hikhvar/mqtt2prometheus/pkg/config"
|
|
gocache "github.com/patrickmn/go-cache"
|
|
"github.com/prometheus/client_golang/prometheus"
|
|
)
|
|
|
|
const DefaultTimeout = 0
|
|
|
|
type Collector interface {
|
|
prometheus.Collector
|
|
Observe(deviceID string, collection MetricCollection)
|
|
}
|
|
|
|
type MemoryCachedCollector struct {
|
|
cache *gocache.Cache
|
|
descriptions []*prometheus.Desc
|
|
}
|
|
|
|
type Metric struct {
|
|
Description *prometheus.Desc
|
|
Value float64
|
|
ValueType prometheus.ValueType
|
|
IngestTime time.Time
|
|
Topic string
|
|
}
|
|
|
|
type MetricCollection []Metric
|
|
|
|
func NewCollector(defaultTimeout time.Duration, possibleMetrics []config.MetricConfig) Collector {
|
|
var descs []*prometheus.Desc
|
|
for _, m := range possibleMetrics {
|
|
descs = append(descs, m.PrometheusDescription())
|
|
}
|
|
return &MemoryCachedCollector{
|
|
cache: gocache.New(defaultTimeout, defaultTimeout*10),
|
|
descriptions: descs,
|
|
}
|
|
}
|
|
|
|
func (c *MemoryCachedCollector) Observe(deviceID string, collection MetricCollection) {
|
|
c.cache.Set(deviceID, collection, DefaultTimeout)
|
|
}
|
|
|
|
func (c *MemoryCachedCollector) Describe(ch chan<- *prometheus.Desc) {
|
|
for i := range c.descriptions {
|
|
ch <- c.descriptions[i]
|
|
}
|
|
}
|
|
|
|
func (c *MemoryCachedCollector) Collect(mc chan<- prometheus.Metric) {
|
|
for device, metricsRaw := range c.cache.Items() {
|
|
metrics := metricsRaw.Object.(MetricCollection)
|
|
for _, metric := range metrics {
|
|
m := prometheus.MustNewConstMetric(
|
|
metric.Description,
|
|
metric.ValueType,
|
|
metric.Value,
|
|
device,
|
|
metric.Topic,
|
|
)
|
|
mc <- prometheus.NewMetricWithTimestamp(metric.IngestTime, m)
|
|
}
|
|
}
|
|
}
|