2024-02-08 08:17:53 +03:00
|
|
|
package slog
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-12-22 22:23:00 +03:00
|
|
|
"io"
|
2024-02-08 08:17:53 +03:00
|
|
|
"log/slog"
|
|
|
|
"os"
|
2024-12-07 16:16:45 +03:00
|
|
|
"reflect"
|
2024-03-04 22:54:11 +03:00
|
|
|
"regexp"
|
2024-02-08 08:17:53 +03:00
|
|
|
"runtime"
|
|
|
|
"strconv"
|
2024-02-22 08:57:21 +03:00
|
|
|
"sync"
|
2024-11-24 23:40:54 +03:00
|
|
|
"sync/atomic"
|
2024-12-22 22:23:00 +03:00
|
|
|
"time"
|
2024-02-08 08:17:53 +03:00
|
|
|
|
|
|
|
"go.unistack.org/micro/v3/logger"
|
2024-05-09 16:41:22 +03:00
|
|
|
"go.unistack.org/micro/v3/semconv"
|
2024-02-08 08:17:53 +03:00
|
|
|
"go.unistack.org/micro/v3/tracer"
|
|
|
|
)
|
|
|
|
|
2024-10-12 12:37:43 +03:00
|
|
|
const (
|
|
|
|
badKey = "!BADKEY"
|
|
|
|
// defaultCallerSkipCount used by logger
|
|
|
|
defaultCallerSkipCount = 3
|
2024-12-24 20:36:32 +03:00
|
|
|
timeFormat = "2006-01-02T15:04:05.000000000Z07:00"
|
2024-10-12 12:37:43 +03:00
|
|
|
)
|
|
|
|
|
2024-03-04 22:54:11 +03:00
|
|
|
var reTrace = regexp.MustCompile(`.*/slog/logger\.go.*\n`)
|
|
|
|
|
2024-02-08 08:17:53 +03:00
|
|
|
var (
|
|
|
|
traceValue = slog.StringValue("trace")
|
|
|
|
debugValue = slog.StringValue("debug")
|
|
|
|
infoValue = slog.StringValue("info")
|
|
|
|
warnValue = slog.StringValue("warn")
|
|
|
|
errorValue = slog.StringValue("error")
|
|
|
|
fatalValue = slog.StringValue("fatal")
|
|
|
|
)
|
|
|
|
|
2024-11-24 23:28:15 +03:00
|
|
|
type wrapper struct {
|
|
|
|
h slog.Handler
|
2024-11-24 23:40:54 +03:00
|
|
|
level atomic.Int64
|
2024-11-24 23:28:15 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (h *wrapper) Enabled(ctx context.Context, level slog.Level) bool {
|
2024-11-24 23:40:54 +03:00
|
|
|
return level >= slog.Level(int(h.level.Load()))
|
2024-11-24 23:28:15 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (h *wrapper) Handle(ctx context.Context, rec slog.Record) error {
|
|
|
|
return h.h.Handle(ctx, rec)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *wrapper) WithAttrs(attrs []slog.Attr) slog.Handler {
|
2024-12-06 19:05:27 +03:00
|
|
|
return h.h.WithAttrs(attrs)
|
2024-11-24 23:28:15 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (h *wrapper) WithGroup(name string) slog.Handler {
|
2024-12-06 19:05:27 +03:00
|
|
|
return h.h.WithGroup(name)
|
2024-11-24 23:28:15 +03:00
|
|
|
}
|
|
|
|
|
2024-02-08 08:17:53 +03:00
|
|
|
func (s *slogLogger) renameAttr(_ []string, a slog.Attr) slog.Attr {
|
|
|
|
switch a.Key {
|
|
|
|
case slog.SourceKey:
|
|
|
|
source := a.Value.Any().(*slog.Source)
|
|
|
|
a.Value = slog.StringValue(source.File + ":" + strconv.Itoa(source.Line))
|
2024-03-04 23:58:31 +03:00
|
|
|
a.Key = s.opts.SourceKey
|
2024-02-08 08:17:53 +03:00
|
|
|
case slog.TimeKey:
|
2024-03-04 23:58:31 +03:00
|
|
|
a.Key = s.opts.TimeKey
|
2024-12-24 20:36:32 +03:00
|
|
|
a.Value = slog.StringValue(a.Value.Time().Format(timeFormat))
|
2024-02-08 08:17:53 +03:00
|
|
|
case slog.MessageKey:
|
2024-03-04 23:58:31 +03:00
|
|
|
a.Key = s.opts.MessageKey
|
2024-02-08 08:17:53 +03:00
|
|
|
case slog.LevelKey:
|
|
|
|
level := a.Value.Any().(slog.Level)
|
|
|
|
lvl := slogToLoggerLevel(level)
|
2024-03-04 23:58:31 +03:00
|
|
|
a.Key = s.opts.LevelKey
|
2024-02-08 08:17:53 +03:00
|
|
|
switch {
|
|
|
|
case lvl < logger.DebugLevel:
|
|
|
|
a.Value = traceValue
|
|
|
|
case lvl < logger.InfoLevel:
|
|
|
|
a.Value = debugValue
|
|
|
|
case lvl < logger.WarnLevel:
|
|
|
|
a.Value = infoValue
|
|
|
|
case lvl < logger.ErrorLevel:
|
|
|
|
a.Value = warnValue
|
|
|
|
case lvl < logger.FatalLevel:
|
|
|
|
a.Value = errorValue
|
|
|
|
case lvl >= logger.FatalLevel:
|
|
|
|
a.Value = fatalValue
|
|
|
|
default:
|
|
|
|
a.Value = infoValue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return a
|
|
|
|
}
|
|
|
|
|
|
|
|
type slogLogger struct {
|
2024-11-24 23:28:15 +03:00
|
|
|
handler *wrapper
|
2024-03-04 23:58:31 +03:00
|
|
|
opts logger.Options
|
|
|
|
mu sync.RWMutex
|
2024-02-08 08:17:53 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *slogLogger) Clone(opts ...logger.Option) logger.Logger {
|
2024-02-22 08:57:21 +03:00
|
|
|
s.mu.RLock()
|
2024-02-08 08:17:53 +03:00
|
|
|
options := s.opts
|
2024-03-07 07:43:52 +03:00
|
|
|
s.mu.RUnlock()
|
2024-02-08 08:17:53 +03:00
|
|
|
|
|
|
|
for _, o := range opts {
|
|
|
|
o(&options)
|
|
|
|
}
|
|
|
|
|
2024-11-24 23:28:15 +03:00
|
|
|
if len(options.ContextAttrFuncs) == 0 {
|
|
|
|
options.ContextAttrFuncs = logger.DefaultContextAttrFuncs
|
|
|
|
}
|
2024-02-08 08:17:53 +03:00
|
|
|
|
2024-11-24 23:28:15 +03:00
|
|
|
attrs, _ := s.argsAttrs(options.Fields)
|
|
|
|
l := &slogLogger{
|
2024-11-24 23:40:54 +03:00
|
|
|
handler: &wrapper{h: s.handler.h.WithAttrs(attrs)},
|
2024-11-24 23:28:15 +03:00
|
|
|
opts: options,
|
|
|
|
}
|
2024-11-24 23:40:54 +03:00
|
|
|
l.handler.level.Store(int64(loggerToSlogLevel(options.Level)))
|
2024-02-22 08:57:21 +03:00
|
|
|
|
2024-02-08 08:17:53 +03:00
|
|
|
return l
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *slogLogger) V(level logger.Level) bool {
|
2024-11-24 23:40:54 +03:00
|
|
|
s.mu.Lock()
|
|
|
|
v := s.opts.Level.Enabled(level)
|
|
|
|
s.mu.Unlock()
|
|
|
|
return v
|
2024-02-08 08:17:53 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *slogLogger) Level(level logger.Level) {
|
2024-11-24 23:28:15 +03:00
|
|
|
s.mu.Lock()
|
|
|
|
s.opts.Level = level
|
2024-11-24 23:40:54 +03:00
|
|
|
s.handler.level.Store(int64(loggerToSlogLevel(level)))
|
2024-11-24 23:28:15 +03:00
|
|
|
s.mu.Unlock()
|
2024-02-08 08:17:53 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *slogLogger) Options() logger.Options {
|
|
|
|
return s.opts
|
|
|
|
}
|
|
|
|
|
2024-11-24 15:31:40 +03:00
|
|
|
func (s *slogLogger) Fields(fields ...interface{}) logger.Logger {
|
2024-02-22 08:57:21 +03:00
|
|
|
s.mu.RLock()
|
2024-03-07 07:43:52 +03:00
|
|
|
options := s.opts
|
|
|
|
s.mu.RUnlock()
|
|
|
|
|
|
|
|
l := &slogLogger{opts: options}
|
2024-12-13 01:04:55 +03:00
|
|
|
logger.WithAddFields(fields...)(&l.opts)
|
2024-11-24 23:28:15 +03:00
|
|
|
|
|
|
|
if len(options.ContextAttrFuncs) == 0 {
|
|
|
|
options.ContextAttrFuncs = logger.DefaultContextAttrFuncs
|
|
|
|
}
|
2024-02-08 08:17:53 +03:00
|
|
|
|
2024-11-24 15:31:40 +03:00
|
|
|
attrs, _ := s.argsAttrs(fields)
|
2024-11-24 23:40:54 +03:00
|
|
|
l.handler = &wrapper{h: s.handler.h.WithAttrs(attrs)}
|
|
|
|
l.handler.level.Store(int64(loggerToSlogLevel(l.opts.Level)))
|
2024-02-22 08:57:21 +03:00
|
|
|
|
2024-03-06 00:53:20 +03:00
|
|
|
return l
|
2024-02-08 08:17:53 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *slogLogger) Init(opts ...logger.Option) error {
|
2024-02-22 08:57:21 +03:00
|
|
|
s.mu.Lock()
|
2024-02-08 08:17:53 +03:00
|
|
|
|
2024-03-04 23:58:31 +03:00
|
|
|
for _, o := range opts {
|
|
|
|
o(&s.opts)
|
2024-02-08 08:17:53 +03:00
|
|
|
}
|
|
|
|
|
2024-11-24 23:28:15 +03:00
|
|
|
if len(s.opts.ContextAttrFuncs) == 0 {
|
|
|
|
s.opts.ContextAttrFuncs = logger.DefaultContextAttrFuncs
|
|
|
|
}
|
|
|
|
|
2024-02-08 08:17:53 +03:00
|
|
|
handleOpt := &slog.HandlerOptions{
|
|
|
|
ReplaceAttr: s.renameAttr,
|
2024-11-24 23:28:15 +03:00
|
|
|
Level: loggerToSlogLevel(logger.TraceLevel),
|
2024-03-06 00:53:20 +03:00
|
|
|
AddSource: s.opts.AddSource,
|
2024-02-08 08:17:53 +03:00
|
|
|
}
|
2024-11-24 23:28:15 +03:00
|
|
|
|
|
|
|
attrs, _ := s.argsAttrs(s.opts.Fields)
|
2024-12-07 14:18:25 +03:00
|
|
|
|
|
|
|
var h slog.Handler
|
|
|
|
if s.opts.Context != nil {
|
|
|
|
if v, ok := s.opts.Context.Value(handlerKey{}).(slog.Handler); ok && v != nil {
|
|
|
|
h = v
|
|
|
|
}
|
2024-12-07 16:16:45 +03:00
|
|
|
|
|
|
|
if fn := s.opts.Context.Value(handlerFnKey{}); fn != nil {
|
|
|
|
if rfn := reflect.ValueOf(fn); rfn.Kind() == reflect.Func {
|
|
|
|
if ret := rfn.Call([]reflect.Value{reflect.ValueOf(s.opts.Out), reflect.ValueOf(handleOpt)}); len(ret) == 1 {
|
|
|
|
if iface, ok := ret[0].Interface().(slog.Handler); ok && iface != nil {
|
|
|
|
h = iface
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-12-07 14:18:25 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if h == nil {
|
|
|
|
h = slog.NewJSONHandler(s.opts.Out, handleOpt)
|
|
|
|
}
|
|
|
|
|
|
|
|
s.handler = &wrapper{h: h.WithAttrs(attrs)}
|
2024-11-24 23:40:54 +03:00
|
|
|
s.handler.level.Store(int64(loggerToSlogLevel(s.opts.Level)))
|
2024-02-22 08:57:21 +03:00
|
|
|
s.mu.Unlock()
|
|
|
|
|
2024-02-08 08:17:53 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-10-12 12:37:43 +03:00
|
|
|
func (s *slogLogger) Log(ctx context.Context, lvl logger.Level, msg string, attrs ...interface{}) {
|
|
|
|
s.printLog(ctx, lvl, msg, attrs...)
|
2024-02-08 08:17:53 +03:00
|
|
|
}
|
|
|
|
|
2024-10-12 12:37:43 +03:00
|
|
|
func (s *slogLogger) Info(ctx context.Context, msg string, attrs ...interface{}) {
|
|
|
|
s.printLog(ctx, logger.InfoLevel, msg, attrs...)
|
2024-02-08 08:17:53 +03:00
|
|
|
}
|
|
|
|
|
2024-10-12 12:37:43 +03:00
|
|
|
func (s *slogLogger) Debug(ctx context.Context, msg string, attrs ...interface{}) {
|
|
|
|
s.printLog(ctx, logger.DebugLevel, msg, attrs...)
|
2024-02-08 08:17:53 +03:00
|
|
|
}
|
|
|
|
|
2024-10-12 12:37:43 +03:00
|
|
|
func (s *slogLogger) Trace(ctx context.Context, msg string, attrs ...interface{}) {
|
|
|
|
s.printLog(ctx, logger.TraceLevel, msg, attrs...)
|
2024-02-08 08:17:53 +03:00
|
|
|
}
|
|
|
|
|
2024-10-12 12:37:43 +03:00
|
|
|
func (s *slogLogger) Error(ctx context.Context, msg string, attrs ...interface{}) {
|
|
|
|
s.printLog(ctx, logger.ErrorLevel, msg, attrs...)
|
2024-02-08 08:17:53 +03:00
|
|
|
}
|
|
|
|
|
2024-10-12 12:37:43 +03:00
|
|
|
func (s *slogLogger) Fatal(ctx context.Context, msg string, attrs ...interface{}) {
|
|
|
|
s.printLog(ctx, logger.FatalLevel, msg, attrs...)
|
2024-12-22 22:23:00 +03:00
|
|
|
if closer, ok := s.opts.Out.(io.Closer); ok {
|
|
|
|
closer.Close()
|
|
|
|
}
|
|
|
|
time.Sleep(1 * time.Second)
|
2024-10-12 12:37:43 +03:00
|
|
|
os.Exit(1)
|
|
|
|
}
|
2024-03-06 00:53:20 +03:00
|
|
|
|
2024-10-12 12:37:43 +03:00
|
|
|
func (s *slogLogger) Warn(ctx context.Context, msg string, attrs ...interface{}) {
|
|
|
|
s.printLog(ctx, logger.WarnLevel, msg, attrs...)
|
2024-02-08 08:17:53 +03:00
|
|
|
}
|
|
|
|
|
2024-10-12 12:37:43 +03:00
|
|
|
func (s *slogLogger) Name() string {
|
|
|
|
return s.opts.Name
|
|
|
|
}
|
2024-03-06 00:53:20 +03:00
|
|
|
|
2024-10-12 12:37:43 +03:00
|
|
|
func (s *slogLogger) String() string {
|
|
|
|
return "slog"
|
2024-02-08 08:17:53 +03:00
|
|
|
}
|
|
|
|
|
2024-11-01 00:56:40 +03:00
|
|
|
func (s *slogLogger) printLog(ctx context.Context, lvl logger.Level, msg string, args ...interface{}) {
|
2024-10-12 12:37:43 +03:00
|
|
|
if !s.V(lvl) {
|
2024-02-08 08:17:53 +03:00
|
|
|
return
|
|
|
|
}
|
2024-11-01 00:56:40 +03:00
|
|
|
var argError error
|
2024-03-06 00:53:20 +03:00
|
|
|
|
2024-10-12 12:37:43 +03:00
|
|
|
s.opts.Meter.Counter(semconv.LoggerMessageTotal, "level", lvl.String()).Inc()
|
|
|
|
|
2024-11-01 00:56:40 +03:00
|
|
|
attrs, err := s.argsAttrs(args)
|
|
|
|
if err != nil {
|
|
|
|
argError = err
|
|
|
|
}
|
|
|
|
if argError != nil {
|
|
|
|
if span, ok := tracer.SpanFromContext(ctx); ok {
|
|
|
|
span.SetStatus(tracer.SpanStatusError, argError.Error())
|
|
|
|
}
|
|
|
|
}
|
2024-02-08 08:17:53 +03:00
|
|
|
|
2024-03-06 00:53:20 +03:00
|
|
|
for _, fn := range s.opts.ContextAttrFuncs {
|
2024-11-01 00:56:40 +03:00
|
|
|
ctxAttrs, err := s.argsAttrs(fn(ctx))
|
|
|
|
if err != nil {
|
|
|
|
argError = err
|
|
|
|
}
|
|
|
|
attrs = append(attrs, ctxAttrs...)
|
2024-03-06 00:53:20 +03:00
|
|
|
}
|
2024-11-01 00:56:40 +03:00
|
|
|
if argError != nil {
|
|
|
|
if span, ok := tracer.SpanFromContext(ctx); ok {
|
|
|
|
span.SetStatus(tracer.SpanStatusError, argError.Error())
|
2024-03-06 00:53:20 +03:00
|
|
|
}
|
|
|
|
}
|
2024-10-12 12:37:43 +03:00
|
|
|
|
2024-12-22 22:23:00 +03:00
|
|
|
if (s.opts.AddStacktrace || lvl == logger.FatalLevel) || (s.opts.AddStacktrace && lvl == logger.ErrorLevel) {
|
2024-03-04 22:54:11 +03:00
|
|
|
stackInfo := make([]byte, 1024*1024)
|
|
|
|
if stackSize := runtime.Stack(stackInfo, false); stackSize > 0 {
|
|
|
|
traceLines := reTrace.Split(string(stackInfo[:stackSize]), -1)
|
|
|
|
if len(traceLines) != 0 {
|
2024-10-12 12:37:43 +03:00
|
|
|
attrs = append(attrs, slog.String(s.opts.StacktraceKey, traceLines[len(traceLines)-1]))
|
2024-02-08 08:17:53 +03:00
|
|
|
}
|
|
|
|
}
|
2024-03-06 00:53:20 +03:00
|
|
|
}
|
2024-02-08 08:17:53 +03:00
|
|
|
|
|
|
|
var pcs [1]uintptr
|
2024-10-12 12:37:43 +03:00
|
|
|
runtime.Callers(s.opts.CallerSkipCount, pcs[:]) // skip [Callers, printLog, LogLvlMethod]
|
|
|
|
r := slog.NewRecord(s.opts.TimeFunc(), loggerToSlogLevel(lvl), msg, pcs[0])
|
2024-11-01 00:56:40 +03:00
|
|
|
r.AddAttrs(attrs...)
|
2024-03-07 07:43:52 +03:00
|
|
|
_ = s.handler.Handle(ctx, r)
|
2024-02-08 08:17:53 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewLogger(opts ...logger.Option) logger.Logger {
|
|
|
|
s := &slogLogger{
|
2024-03-04 23:58:31 +03:00
|
|
|
opts: logger.NewOptions(opts...),
|
2024-02-08 08:17:53 +03:00
|
|
|
}
|
2024-10-12 12:37:43 +03:00
|
|
|
s.opts.CallerSkipCount = defaultCallerSkipCount
|
2024-03-04 23:58:31 +03:00
|
|
|
|
2024-02-08 08:17:53 +03:00
|
|
|
return s
|
|
|
|
}
|
|
|
|
|
|
|
|
func loggerToSlogLevel(level logger.Level) slog.Level {
|
|
|
|
switch level {
|
|
|
|
case logger.DebugLevel:
|
|
|
|
return slog.LevelDebug
|
|
|
|
case logger.WarnLevel:
|
|
|
|
return slog.LevelWarn
|
|
|
|
case logger.ErrorLevel:
|
|
|
|
return slog.LevelError
|
|
|
|
case logger.TraceLevel:
|
|
|
|
return slog.LevelDebug - 1
|
|
|
|
case logger.FatalLevel:
|
|
|
|
return slog.LevelError + 1
|
|
|
|
default:
|
|
|
|
return slog.LevelInfo
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func slogToLoggerLevel(level slog.Level) logger.Level {
|
|
|
|
switch level {
|
|
|
|
case slog.LevelDebug:
|
|
|
|
return logger.DebugLevel
|
|
|
|
case slog.LevelWarn:
|
|
|
|
return logger.WarnLevel
|
|
|
|
case slog.LevelError:
|
|
|
|
return logger.ErrorLevel
|
|
|
|
case slog.LevelDebug - 1:
|
|
|
|
return logger.TraceLevel
|
|
|
|
case slog.LevelError + 1:
|
|
|
|
return logger.FatalLevel
|
|
|
|
default:
|
|
|
|
return logger.InfoLevel
|
|
|
|
}
|
|
|
|
}
|
2024-10-12 12:37:43 +03:00
|
|
|
|
2024-11-01 00:56:40 +03:00
|
|
|
func (s *slogLogger) argsAttrs(args []interface{}) ([]slog.Attr, error) {
|
|
|
|
attrs := make([]slog.Attr, 0, len(args))
|
|
|
|
var err error
|
|
|
|
|
|
|
|
for idx := 0; idx < len(args); idx++ {
|
|
|
|
switch arg := args[idx].(type) {
|
|
|
|
case slog.Attr:
|
|
|
|
attrs = append(attrs, arg)
|
|
|
|
case string:
|
|
|
|
if idx+1 < len(args) {
|
|
|
|
attrs = append(attrs, slog.Any(arg, args[idx+1]))
|
2024-12-09 16:23:25 +03:00
|
|
|
idx++
|
2024-11-01 00:56:40 +03:00
|
|
|
} else {
|
|
|
|
attrs = append(attrs, slog.String(badKey, arg))
|
|
|
|
}
|
|
|
|
case error:
|
|
|
|
attrs = append(attrs, slog.String(s.opts.ErrorKey, arg.Error()))
|
|
|
|
err = arg
|
|
|
|
}
|
2024-10-12 12:37:43 +03:00
|
|
|
}
|
|
|
|
|
2024-11-01 00:56:40 +03:00
|
|
|
return attrs, err
|
2024-10-12 12:37:43 +03:00
|
|
|
}
|
2024-12-07 14:18:25 +03:00
|
|
|
|
|
|
|
type handlerKey struct{}
|
|
|
|
|
|
|
|
func WithHandler(h slog.Handler) logger.Option {
|
|
|
|
return logger.SetOption(handlerKey{}, h)
|
|
|
|
}
|
2024-12-07 16:16:45 +03:00
|
|
|
|
|
|
|
type handlerFnKey struct{}
|
|
|
|
|
|
|
|
func WithHandlerFunc(fn any) logger.Option {
|
|
|
|
return logger.SetOption(handlerFnKey{}, fn)
|
|
|
|
}
|