Files
Christoph Petrausch 126e13428b Use go.uber.org/zap for logging
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.
2020-10-29 20:58:28 +01:00

31 lines
944 B
Go

package mqttclient
import (
"github.com/eclipse/paho.mqtt.golang"
"go.uber.org/zap"
)
type SubscribeOptions struct {
Topic string
QoS byte
OnMessageReceived mqtt.MessageHandler
Logger *zap.Logger
}
func Subscribe(connectionOptions *mqtt.ClientOptions, subscribeOptions SubscribeOptions) error {
connectionOptions.OnConnect = func(client mqtt.Client) {
logger := subscribeOptions.Logger
logger.Info("Connected to MQTT Broker")
logger.Info("Will subscribe to topic", zap.String("topic", subscribeOptions.Topic))
if token := client.Subscribe(subscribeOptions.Topic, subscribeOptions.QoS, subscribeOptions.OnMessageReceived); token.Wait() && token.Error() != nil {
logger.Error("Could not subscribe", zap.Error(token.Error()))
}
}
client := mqtt.NewClient(connectionOptions)
if token := client.Connect(); token.Wait() && token.Error() != nil {
return token.Error()
}
return nil
}