...
1 package logging
2
3 import (
4 "context"
5 "io"
6 "log"
7 )
8
9
10 type Classification string
11
12
13 const (
14 Warn Classification = "WARN"
15 Debug Classification = "DEBUG"
16 )
17
18
19 type Logger interface {
20
21 Logf(classification Classification, format string, v ...interface{})
22 }
23
24
25 type LoggerFunc func(classification Classification, format string, v ...interface{})
26
27
28 func (f LoggerFunc) Logf(classification Classification, format string, v ...interface{}) {
29 f(classification, format, v...)
30 }
31
32
33
34 type ContextLogger interface {
35 WithContext(context.Context) Logger
36 }
37
38
39
40
41 func WithContext(ctx context.Context, logger Logger) Logger {
42 if logger == nil {
43 return Nop{}
44 }
45
46 cl, ok := logger.(ContextLogger)
47 if !ok {
48 return logger
49 }
50
51 return cl.WithContext(ctx)
52 }
53
54
55 type Nop struct{}
56
57
58 func (n Nop) Logf(Classification, string, ...interface{}) {
59 return
60 }
61
62
63
64 type StandardLogger struct {
65 Logger *log.Logger
66 }
67
68
69 func (s StandardLogger) Logf(classification Classification, format string, v ...interface{}) {
70 if len(classification) != 0 {
71 format = string(classification) + " " + format
72 }
73
74 s.Logger.Printf(format, v...)
75 }
76
77
78 func NewStandardLogger(writer io.Writer) *StandardLogger {
79 return &StandardLogger{
80 Logger: log.New(writer, "SDK ", log.LstdFlags),
81 }
82 }
83
View as plain text