Package list golang-github-go-kit-kit / 0ce5681
Merge pull request #429 from go-kit/log-docs Enhance package log docs. Chris Hines authored 4 years ago GitHub committed 4 years ago
2 changed file(s) with 61 addition(s) and 3 deletion(s). Raw diff Collapse all Expand all
8989 // handled atomically within the wrapped logger, but it typically serializes
9090 // both the formatting and output logic. Use a SyncLogger if the formatting
9191 // logger may perform multiple writes per log event.
92 //
93 // Error Handling
94 //
95 // This package relies on the practice of wrapping or decorating loggers with
96 // other loggers to provide composable pieces of functionality. It also means
97 // that Logger.Log must return an error because some
98 // implementations—especially those that output log data to an io.Writer—may
99 // encounter errors that cannot be handled locally. This in turn means that
100 // Loggers that wrap other loggers should return errors from the wrapped
101 // logger up the stack.
102 //
103 // Fortunately, the decorator pattern also provides a way to avoid the
104 // necessity to check for errors every time an application calls Logger.Log.
105 // An application required to panic whenever its Logger encounters
106 // an error could initialize its logger as follows.
107 //
108 // fmtlogger := log.NewLogfmtLogger(log.NewSyncWriter(os.Stdout))
109 // logger := log.LoggerFunc(func(keyvals ...interface{}) error {
110 // if err := fmtlogger.Log(keyvals...); err != nil {
111 // panic(err)
112 // }
113 // return nil
114 // })
92115 package log
00 package log_test
11
22 import (
3 "math/rand"
34 "os"
5 "sync"
46 "time"
57
68 "github.com/go-kit/kit/log"
9597 logger.Log("call", "third")
9698
9799 // Output:
98 // time=2015-02-03T10:00:01Z caller=example_test.go:91 call=first
99 // time=2015-02-03T10:00:02Z caller=example_test.go:92 call=second
100 // time=2015-02-03T10:00:03Z caller=example_test.go:96 call=third
100 // time=2015-02-03T10:00:01Z caller=example_test.go:93 call=first
101 // time=2015-02-03T10:00:02Z caller=example_test.go:94 call=second
102 // time=2015-02-03T10:00:03Z caller=example_test.go:98 call=third
101103 }
104
105 func Example_syncWriter() {
106 w := log.NewSyncWriter(os.Stdout)
107 logger := log.NewLogfmtLogger(w)
108
109 type Task struct {
110 ID int
111 }
112
113 var wg sync.WaitGroup
114
115 RunTask := func(task Task, logger log.Logger) {
116 logger.Log("taskID", task.ID, "event", "starting task")
117
118 time.Sleep(time.Duration(rand.Intn(200)) * time.Millisecond)
119
120 logger.Log("taskID", task.ID, "event", "task complete")
121 wg.Done()
122 }
123
124 wg.Add(2)
125
126 go RunTask(Task{ID: 1}, logger)
127 go RunTask(Task{ID: 2}, logger)
128
129 wg.Wait()
130
131 // Unordered output:
132 // taskID=1 event="starting task"
133 // taskID=2 event="starting task"
134 // taskID=1 event="task complete"
135 // taskID=2 event="task complete"
136 }