-
Notifications
You must be signed in to change notification settings - Fork 22
/
s.go
47 lines (38 loc) · 988 Bytes
/
s.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
package slog
import (
"context"
"log"
"strings"
)
// Stdlib creates a standard library logger from the given logger.
//
// All logs will be logged at the level set by the logger and the
// given ctx will be passed to the logger's Log method, thereby
// logging all fields and tracing info in the context.
//
// You can redirect the stdlib default logger with log.SetOutput
// to the Writer on the logger returned by this function.
// See the example.
func Stdlib(ctx context.Context, l Logger, level Level) *log.Logger {
l.skip += 2
l = l.Named("stdlib")
w := &stdlogWriter{
ctx: ctx,
l: l,
level: level,
}
return log.New(w, "", 0)
}
type stdlogWriter struct {
ctx context.Context
l Logger
level Level
}
func (w stdlogWriter) Write(p []byte) (n int, err error) {
msg := string(p)
// stdlib includes a trailing newline on the msg that
// we do not want.
msg = strings.TrimSuffix(msg, "\n")
w.l.log(w.ctx, w.level, msg, nil)
return len(p), nil
}