1 package log_test
2
3 import (
4 "math/rand"
5 "os"
6 "sync"
7 "time"
8
9 "github.com/go-kit/kit/log"
10 )
11
12 func Example_basic() {
13 logger := log.NewLogfmtLogger(os.Stdout)
14
15 type Task struct {
16 ID int
17 }
18
19 RunTask := func(task Task, logger log.Logger) {
20 logger.Log("taskID", task.ID, "event", "starting task")
21
22 logger.Log("taskID", task.ID, "event", "task complete")
23 }
24
25 RunTask(Task{ID: 1}, logger)
26
27
28
29
30 }
31
32 func Example_contextual() {
33 logger := log.NewLogfmtLogger(os.Stdout)
34
35 type Task struct {
36 ID int
37 Cmd string
38 }
39
40 taskHelper := func(cmd string, logger log.Logger) {
41
42 logger.Log("cmd", cmd, "dur", 42*time.Millisecond)
43 }
44
45 RunTask := func(task Task, logger log.Logger) {
46 logger = log.With(logger, "taskID", task.ID)
47 logger.Log("event", "starting task")
48
49 taskHelper(task.Cmd, logger)
50
51 logger.Log("event", "task complete")
52 }
53
54 RunTask(Task{ID: 1, Cmd: "echo Hello, world!"}, logger)
55
56
57
58
59
60 }
61
62 func Example_valuer() {
63 logger := log.NewLogfmtLogger(os.Stdout)
64
65 count := 0
66 counter := func() interface{} {
67 count++
68 return count
69 }
70
71 logger = log.With(logger, "count", log.Valuer(counter))
72
73 logger.Log("call", "first")
74 logger.Log("call", "second")
75
76
77
78
79 }
80
81 func Example_debugInfo() {
82 logger := log.NewLogfmtLogger(os.Stdout)
83
84
85 baseTime := time.Date(2015, time.February, 3, 10, 0, 0, 0, time.UTC)
86 mockTime := func() time.Time {
87 baseTime = baseTime.Add(time.Second)
88 return baseTime
89 }
90
91 logger = log.With(logger, "time", log.Timestamp(mockTime), "caller", log.DefaultCaller)
92
93 logger.Log("call", "first")
94 logger.Log("call", "second")
95
96
97
98 logger.Log("call", "third")
99
100
101
102
103
104 }
105
106 func Example_syncWriter() {
107 w := log.NewSyncWriter(os.Stdout)
108 logger := log.NewLogfmtLogger(w)
109
110 type Task struct {
111 ID int
112 }
113
114 var wg sync.WaitGroup
115
116 RunTask := func(task Task, logger log.Logger) {
117 logger.Log("taskID", task.ID, "event", "starting task")
118
119 time.Sleep(time.Duration(rand.Intn(200)) * time.Millisecond)
120
121 logger.Log("taskID", task.ID, "event", "task complete")
122 wg.Done()
123 }
124
125 wg.Add(2)
126
127 go RunTask(Task{ID: 1}, logger)
128 go RunTask(Task{ID: 2}, logger)
129
130 wg.Wait()
131
132
133
134
135
136
137 }
138
View as plain text