Add an example for tracing global variable with hook

This commit is contained in:
David Bariod
2018-10-15 21:20:03 +02:00
parent 4582136994
commit f2ab87f230
3 changed files with 40 additions and 0 deletions
+37
View File
@@ -0,0 +1,37 @@
package logrus_test
import (
"github.com/sirupsen/logrus"
"os"
)
var (
mystring string
)
type GlobalHook struct {
}
func (h *GlobalHook) Levels() []logrus.Level {
return logrus.AllLevels
}
func (h *GlobalHook) Fire(e *logrus.Entry) error {
e.Data["mystring"] = mystring
return nil
}
func Example() {
l := logrus.New()
l.Out = os.Stdout
l.Formatter = &logrus.TextFormatter{DisableTimestamp: true}
l.Formatter.(*logrus.TextFormatter).DisableTimestamp = true
l.AddHook(&GlobalHook{})
mystring = "first value"
l.Info("first log")
mystring = "another value"
l.Info("second log")
// Output:
// level=info msg="first log" mystring="first value"
// level=info msg="second log" mystring="another value"
}