Created
September 15, 2023 18:26
-
-
Save till/ad6cdd91a95f30ebd9fe14548d13bd7a to your computer and use it in GitHub Desktop.
logrus hooks, and how they work
This file contains 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
package main | |
import ( | |
"fmt" | |
"io" | |
"os" | |
"github.com/sirupsen/logrus" | |
) | |
type LokiHook struct{} | |
func (h *LokiHook) Fire(e *logrus.Entry) error { | |
fmt.Println("🔥 !!! - " + e.Message) | |
return nil | |
} | |
func (h *LokiHook) Levels() []logrus.Level { | |
return []logrus.Level{ | |
logrus.DebugLevel, | |
} | |
} | |
type UsualHook struct { | |
Writer io.Writer | |
} | |
func (h *UsualHook) Fire(entry *logrus.Entry) error { | |
line, err := entry.String() | |
if err != nil { | |
return err | |
} | |
_, err = h.Writer.Write([]byte(line)) | |
return err | |
} | |
func (h *UsualHook) Levels() []logrus.Level { | |
return []logrus.Level{ | |
logrus.InfoLevel, | |
logrus.WarnLevel, | |
logrus.ErrorLevel, | |
logrus.FatalLevel, | |
logrus.PanicLevel, | |
} | |
} | |
func main() { | |
h := &LokiHook{} | |
u := &UsualHook{ | |
Writer: os.Stdout, | |
} | |
log := logrus.New() | |
log.SetOutput(io.Discard) | |
// log.SetFormatter(&logrus.TextFormatter{}) | |
// log.SetReportCaller(true) | |
log.SetLevel(logrus.DebugLevel) | |
log.AddHook(h) | |
log.AddHook(u) | |
log.Info("Hello") | |
log.Debug("Hook?") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment