0

我正在使用 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

谢谢

4

2 回答 2

0

我为这个问题找到了一个钩子实现: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-08-31T13:55:56.490 回答
0
  • 您可以创建一个struct实现该接口的Writer接口,并将您的条件逻辑放在那里,即根据日志级别应将日志写入何处。
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{})
于 2020-08-30T20:24:37.397 回答