generated from xmidt-org/.go-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
logger.go
54 lines (44 loc) · 1.18 KB
/
logger.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package main
import (
"bytes"
"errors"
"fmt"
"io"
"net/http"
"go.uber.org/fx"
)
// Logger is the logging interface expected by dms. Loggers in
// various packages, such as go.uber.org/fx, implement this interface.
type Logger interface {
Printf(string, ...interface{})
}
// WriterLogger is a Logger that sends its output to a given io.Writer.
type WriterLogger struct {
Writer io.Writer
}
func (wl WriterLogger) Printf(format string, args ...interface{}) {
var o bytes.Buffer
fmt.Fprintf(&o, format+"\n", args...)
// ensure a single write for each printf
_, err := wl.Writer.Write(o.Bytes())
if err != nil {
panic(err)
}
}
// DiscardLogger is a Logger that ignores all output.
type DiscardLogger struct{}
func (dl DiscardLogger) Printf(string, ...interface{}) {}
func provideLogger(w io.Writer) fx.Option {
return fx.Provide(
func() Logger {
return WriterLogger{Writer: w}
},
)
}
// logServerError logs an error if and only if err is not http.ErrServerClosed.
// This function is intended to report any unexpected error from http.Error.Serve.
func logServerError(l Logger, err error) {
if !errors.Is(err, http.ErrServerClosed) {
l.Printf("HTTP server error: %s", err)
}
}