Skip to content

Instantly share code, notes, and snippets.

@alkanna
Last active January 18, 2021 11:12
Show Gist options
  • Save alkanna/ab50cce8c5d95ff630d3fb7e2df5ab6e to your computer and use it in GitHub Desktop.
Save alkanna/ab50cce8c5d95ff630d3fb7e2df5ab6e to your computer and use it in GitHub Desktop.
import (
"os"
"regexp"
log "github.com/sirupsen/logrus"
)
type LogWriter struct{}
var levelRegex *regexp.Regexp
const (
LevelError = "error"
LevelWarning = "warning"
LevelFatal = "fatal"
LevelPanic = "panic"
)
func init() {
var err error
levelRegex, err = regexp.Compile("level=([a-z]+)")
if err != nil {
log.WithError(err).Fatal("Cannot setup log level")
}
}
func (w *LogWriter) detectLogLevel(p []byte) (level string) {
matches := levelRegex.FindStringSubmatch(string(p))
if len(matches) > 1 {
level = matches[1]
}
return
}
func (w *LogWriter) Write(p []byte) (n int, err error) {
level := w.detectLogLevel(p)
if level == LevelError || level == LevelWarning || level == LevelFatal || level == LevelPanic {
return os.Stderr.Write(p)
}
return os.Stdout.Write(p)
}
func main() {
log.SetOutput(&LogWriter{})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment