Debian Codegraph @

example_test.go

raw symbols SCIP
1 package logg_test
2
3 import (
4 "bytes"
5 "fmt"
6 "strings"
7 "time"
8
9 "github.com/bep/logg"
10 "github.com/bep/logg/handlers/text"
11 )
12
13 func Example() {
14 var buff bytes.Buffer
15 // Create a new logger.
16 l := logg.New(
17 logg.Options{
18 Level: logg.LevelInfo,
19 Handler: text.New(&buff, text.Options{Separator: " "}),
20 },
21 )
22 // Create a new log context.
23 infoLogger := l.WithLevel(logg.LevelInfo)
24
25 // Logg some user activity.
26 userLogger := infoLogger.WithField("user", "foo").WithField("id", "123")
27 userLogger.Log(logg.String("logged in"))
28 userLogger.WithField("file", "jokes.txt").Log(logg.String("uploaded"))
29 userLogger.WithField("file", "morejokes.txt").Log(logg.String("uploaded"))
30
31 fmt.Print(buff.String())
32
33 // Output:
34 // INFO logged in user=foo id=123
35 // INFO uploaded user=foo id=123 file=jokes.txt
36 // INFO uploaded user=foo id=123 file=morejokes.txt
37 }
38
39 func Example_lazy_evaluation() {
40 var buff bytes.Buffer
41 // Create a new logger.
42 l := logg.New(
43 logg.Options{
44 Level: logg.LevelError,
45 Handler: text.New(&buff, text.Options{Separator: "|"}),
46 },
47 )
48
49 errorLogger := l.WithLevel(logg.LevelError)
50
51 // Info is below the logger's level, so
52 // nothing will be printed.
53 infoLogger := l.WithLevel(logg.LevelInfo)
54
55 // Simulate a busy loop.
56 for range 999 {
57 ctx := infoLogger.WithFields(
58 logg.NewFieldsFunc(
59 // This func will never be invoked with the current logger's level.
60 func() logg.Fields {
61 return logg.Fields{
62 {"field", strings.Repeat("x", 9999)},
63 }
64
65 }),
66 )
67 ctx.Log(logg.StringFunc(
68 // This func will never be invoked with the current logger's level.
69 func() string {
70 return "log message: " + strings.Repeat("x", 9999)
71 },
72 ))
73
74 }
75
76 errorLogger.WithDuration(32 * time.Second).Log(logg.String("something took too long"))
77
78 fmt.Print(buff.String())
79
80 // Output:
81 // ERROR|something took too long|duration=32000
82
83 }