2021-08-06 11:52:04 +03:00
|
|
|
package logger
|
|
|
|
|
|
|
|
import (
|
2021-08-06 13:45:11 +03:00
|
|
|
"bytes"
|
2021-08-06 11:52:04 +03:00
|
|
|
"log"
|
|
|
|
)
|
|
|
|
|
|
|
|
type stdLogger struct {
|
|
|
|
l Logger
|
|
|
|
level Level
|
|
|
|
}
|
|
|
|
|
2022-01-10 16:47:37 +03:00
|
|
|
// NewStdLogger returns new *log.Logger baked by logger.Logger implementation
|
2021-08-06 11:52:04 +03:00
|
|
|
func NewStdLogger(l Logger, level Level) *log.Logger {
|
2023-10-15 23:55:16 +03:00
|
|
|
return log.New(&stdLogger{l: l.Clone(WithCallerSkipCount(l.Options().CallerSkipCount + 1)), level: level}, "" /* prefix */, 0 /* flags */)
|
2021-08-06 11:52:04 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (sl *stdLogger) Write(p []byte) (int, error) {
|
2021-08-06 13:45:11 +03:00
|
|
|
p = bytes.TrimSpace(p)
|
2021-08-06 11:52:04 +03:00
|
|
|
sl.l.Log(sl.l.Options().Context, sl.level, string(p))
|
|
|
|
return len(p), nil
|
|
|
|
}
|
2021-08-06 13:45:11 +03:00
|
|
|
|
2022-01-10 16:47:37 +03:00
|
|
|
// RedirectStdLogger replace *log.Logger with logger.Logger implementation
|
2021-08-06 13:45:11 +03:00
|
|
|
func RedirectStdLogger(l Logger, level Level) func() {
|
|
|
|
flags := log.Flags()
|
|
|
|
prefix := log.Prefix()
|
|
|
|
writer := log.Writer()
|
|
|
|
log.SetFlags(0)
|
|
|
|
log.SetPrefix("")
|
|
|
|
log.SetOutput(&stdLogger{l: l, level: level})
|
|
|
|
return func() {
|
|
|
|
log.SetFlags(flags)
|
|
|
|
log.SetPrefix(prefix)
|
|
|
|
log.SetOutput(writer)
|
|
|
|
}
|
|
|
|
}
|