doushao1087 2016-09-12 06:15
浏览 169
已采纳

Golang Logrus日志可在控制台中使用,但不会发送到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.

  • 写回答

1条回答 默认 最新

  • doufei8250 2016-09-29 04:48
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 eclipse连接sap后代码跑出来空白
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi