Last active
January 18, 2021 11:12
-
-
Save alkanna/ab50cce8c5d95ff630d3fb7e2df5ab6e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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