【问题标题】:golang how to write logrus error to supervisord stderr_logfile automatticallygolang如何自动将logrus错误写入supervisord stderr_logfile
【发布时间】:2020-08-30 20:00:42
【问题描述】:

我正在使用 supervisord 来运行我的 golang 应用程序。我的supervisord conf看起来像

[program:go_web]
command=go-web-app
autostart=true
autorestart=true
startsecs=3
stdout_logfile=/var/log/app.log
stderr_logfile=/var/log/app_error.log

我的 logrus 设置看起来:

package main

import (
    "github.com/sirupsen/logrus"
    log "github.com/sirupsen/logrus"
)

func main() {
    log.SetFormatter(&logrus.TextFormatter{
        ForceColors: true,
    })
    log.Info("this is an info")
    log.Error("this is an error")
}

但是我发现两者都登录到我的错误日志/var/log/app_error.log

INFO[0000] this is an info
ERRO[0000] this is an error

如何自动将信息记录到我的应用程序日志/var/log/app.log 并将错误记录到错误日志var/log/app_error.log

谢谢

【问题讨论】:

标签: go supervisord logrus


【解决方案1】:
  • 您可以创建一个实现Writer 接口的struct,并将您的条件逻辑放在那里,即根据日志级别将日志写入何处。
type OutputSplitter struct{}

func (splitter *OutputSplitter) Write(p []byte) (n int, err error) {
    // your logs filter logic here. For ex:
    if bytes.Contains(p, []byte("level=error")) {
        return os.Stderr.Write(p)
    }
    return os.Stdout.Write(p)
}

然后使用该结构通过 logrus 写入日志。

logrus.SetOutput(&OutputSplitter{})

【讨论】:

    【解决方案2】:

    我为这个问题找到了一个钩子实现:https://github.com/sirupsen/logrus/tree/master/hooks/writer

    package main
    
    import (
        "io/ioutil"
        "os"
    
        log "github.com/sirupsen/logrus"
        "github.com/sirupsen/logrus/hooks/writer"
    )
    
    func main() {
        log.SetOutput(ioutil.Discard) // Send all logs to nowhere by default
    
        log.AddHook(&writer.Hook{ // Send logs with level higher than warning to stderr
            Writer: os.Stderr,
            LogLevels: []log.Level{
                log.PanicLevel,
                log.FatalLevel,
                log.ErrorLevel,
                log.WarnLevel,
            },
        })
        log.AddHook(&writer.Hook{ // Send info and debug logs to stdout
            Writer: os.Stdout,
            LogLevels: []log.Level{
                log.InfoLevel,
                log.DebugLevel,
            },
        })
        log.Info("This will go to stdout") 
        log.Warn("This will go to stderr")
    }
    

    【讨论】:

      猜你喜欢
      • 2020-05-19
      • 1970-01-01
      • 1970-01-01
      • 2015-09-20
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 2014-08-27
      相关资源
      最近更新 更多