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

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度