Merge pull request #889 from sirupsen/default_field_hook

Add an example hook which adds default fields
This commit is contained in:
David Bariod 2019-01-17 09:42:32 +01:00 committed by GitHub
commit 11dad09cee
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 31 additions and 1 deletions

View File

@ -0,0 +1,30 @@
package logrus_test
import (
"github.com/sirupsen/logrus"
"os"
)
type DefaultFieldHook struct {
GetValue func() string
}
func (h *DefaultFieldHook) Levels() []logrus.Level {
return logrus.AllLevels
}
func (h *DefaultFieldHook) Fire(e *logrus.Entry) error {
e.Data["aDefaultField"] = h.GetValue()
return nil
}
func ExampleDefaultField() {
l := logrus.New()
l.Out = os.Stdout
l.Formatter = &logrus.TextFormatter{DisableTimestamp: true, DisableColors: true}
l.AddHook(&DefaultFieldHook{GetValue: func() string { return "with its default value" }})
l.Info("first log")
// Output:
// level=info msg="first log" aDefaultField="with its default value"
}

View File

@ -21,7 +21,7 @@ func (h *GlobalHook) Fire(e *logrus.Entry) error {
return nil return nil
} }
func Example() { func ExampleGlobalVariableHook() {
l := logrus.New() l := logrus.New()
l.Out = os.Stdout l.Out = os.Stdout
l.Formatter = &logrus.TextFormatter{DisableTimestamp: true, DisableColors: true} l.Formatter = &logrus.TextFormatter{DisableTimestamp: true, DisableColors: true}