1

I want to use logrus hooks in golang project to send logs on MQTT topic, I have a message broker "tls://wwww-xxx.yyyyy.zzzzzzzzzzz", I'm using below code from this doc to test it with my broker, this code runs without any error and also I can see logs in console but no logs sent on topic.

package main

import (
    "github.com/sirupsen/logrus"

    "github.com/shirou/logrusmqtt"
)

func main() {
    log := logrus.New()

    p := logrusmqtt.MQTTHookParams{
        Hostname:   "wwww-xxx.yyyyy.zzzzzzzzzzz",
        Topic:      "logrusmqtt/log",
        Port:       8883,
        CAFilepath: "/vvv/www/xxxxx/yyyyy/zzzzz-zzzzz/ca.crt",
    }

    hook, err := logrusmqtt.NewMQTTHook(p, logrus.DebugLevel)
    if err != nil {
        panic(err)
    }
    log.Hooks.Add(hook)

    log.Info("Info message")

    log.WithFields(logrus.Fields{
        "name": "joe",
        "age":  42,
    }).Error("Error Message with fields")
}

I subscribed for topic using mosquitto (below command) to verify if messages being sent

mosquitto_sub -h wwww-xxx.yyyyy.zzzzzzzzzzz -p 8883 -t logrusmqtt/log/# --cafile /vvv/www/xxxxx/yyyyy/zzzzz-zzzzz/ca.crt -d

And just to be sure broker is working properly, I sent a test message using command line and it's working, subscriber receives test message.

mosquitto_pub -h wwww-xxx.yyyyy.zzzzzzzzzzz -p 8883 -m "Pub test message" -t logrusmqtt/log --cafile /vvv/www/xxxxx/yyyyy/zzzzz-zzzzz/ca.crt -d

But it doesn't work with logrus hook. Any help is appreciated.

Shri
  • 351
  • 3
  • 16
  • 1
    Try to add a `time.Sleep(time.Second*5)` at the end. Maybe the application ends before sending any action? – slsy Sep 22 '22 at 19:57
  • 1
    The plugin you are using [does not wait](https://github.com/shirou/logrusmqtt/blob/master/hook.go#L65) for the connection to come up (calling `token.Error()` like this is fairly pointless; `token.Wait()` needs to be called first). So I'd say @slsy is right (the MQTT publish happens asynchronously). – Brits Sep 22 '22 at 21:13
  • 1
    I raised an issue after making the above comment and it's [already been addressed](https://github.com/shirou/logrusmqtt/pull/4) (however the `Publish` is still async so if you exit immediately it may not have been transmitted). – Brits Sep 23 '22 at 04:13
  • Great, #slsy was right, after updating package with @Brits's fix, it's working now. – Shri Sep 23 '22 at 08:49

0 Answers0