logginggogorillaloggly

Golang logrus logs available in console but not being sent to loggly


I have a golang project and I'm trying to use loggly logging as explained in their blog at https://www.loggly.com/blog/logging-to-loggly-from-go-with-logrus-and-logrusly/

The problem is that with their example, things are fine but I have a bunch of files and dozens of functions (which handle API calls) and I don't want to go about re-initializing the logger instance every time.

This works perfectly in main.go

log := logrus.New()
hook := logrusly.NewLogglyHook(logglyToken, domain, logrus.WarnLevel, logglyUsername, logglyPassword)
log.Hooks.Add(hook)
log.Info("Welcome")
hook.Flush()

and I'm able to see this message in my loggly account.

But, if I do something like this -

func LogrusLogger(loglevel string, message interface{}){
    log := logrus.New()
    hook := logrusly.NewLogglyHook(logglyToken, domain, logrus.WarnLevel, logglyUsername, logglyPassword)
    log.Hooks.Add(hook)

    log.Info(loglevel, message)
    hook.Flush()
}

then upon calling this function, the logs can be seen in the program console but not in the loggly account specified. Am I calling the hook.Flush() correctly? (Because I'm assuming that's the point where the logs get sent to the loggly server)

Additional info: The first piece of code is in main.go inside the main() function

The second piece of code is in utility.go which has a package utility and I call the function as utility.LogrusLogger(loglevel, message) wherever I want after importing the package utility in that file. I'm pretty sure things are fine as I'm able to see the logs in the program console.


Solution

  • I was able to solve the issue by declaring the following globally

    log := logrus.New()
    hook := logrusly.NewLogglyHook(logglyToken, domain, logrus.WarnLevel, logglyUsername, logglyPassword)
    

    and then using functions like this -

    func LogrusInfo(args ...interface{}) {
        logger.Hooks.Add(hook)
        logger.Info(args...)
        hook.Flush()
    }
    

    Reference: https://stackoverflow.com/a/30261304/4720042