sshpoke/internal/api/rest/middleware/log/adapter.go

81 lines
1.6 KiB
Go

package log
import (
"io"
"strings"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type writerLogger struct {
log *zap.SugaredLogger
level zapcore.Level
}
func AsWriter(log *zap.SugaredLogger, level zapcore.Level) io.Writer {
return &writerLogger{log: log, level: level}
}
func (w *writerLogger) Write(p []byte) (n int, err error) {
switch w.level {
case zapcore.DebugLevel:
for _, line := range strings.Split(string(p), "\n") {
line = strings.TrimSpace(line)
if line == "" {
return
}
w.log.Debug(line)
}
case zapcore.InfoLevel:
for _, line := range strings.Split(string(p), "\n") {
line = strings.TrimSpace(line)
if line == "" {
return
}
w.log.Info(line)
}
case zapcore.WarnLevel:
for _, line := range strings.Split(string(p), "\n") {
line = strings.TrimSpace(line)
if line == "" {
return
}
w.log.Warn(line)
}
case zapcore.ErrorLevel:
for _, line := range strings.Split(string(p), "\n") {
line = strings.TrimSpace(line)
if line == "" {
return
}
w.log.Error(line)
}
case zapcore.DPanicLevel:
for _, line := range strings.Split(string(p), "\n") {
line = strings.TrimSpace(line)
if line == "" {
return
}
w.log.DPanic(line)
}
case zapcore.PanicLevel:
for _, line := range strings.Split(string(p), "\n") {
line = strings.TrimSpace(line)
if line == "" {
return
}
w.log.Panic(line)
}
case zapcore.FatalLevel:
for _, line := range strings.Split(string(p), "\n") {
line = strings.TrimSpace(line)
if line == "" {
return
}
w.log.Fatal(line)
}
}
return len(p), nil
}