0

I am using supervisord to run my golang app. My supervisord conf looks like

[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

and my logrus setup looks:

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")
}

However I found both log in my error log /var/log/app_error.log

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

How can I make info logging to my app log /var/log/app.log and error logging to error log var/log/app_error.log automatically.

Thanks

user2002692
  • 971
  • 2
  • 17
  • 34

2 Answers2

0
  • You can create a struct that implements the Writer interface, and put your conditioned logic there, i.e where the logs should be written to based on log level.
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)
}

And then use that struct to write logs by logrus.

logrus.SetOutput(&OutputSplitter{})
0

I found a hook implementation for this issue: 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")
}
user2002692
  • 971
  • 2
  • 17
  • 34