From 0ace15eb5b2b0190767c4743129b1574211d4010 Mon Sep 17 00:00:00 2001 From: Googol Lee Date: Mon, 29 Jul 2024 11:47:47 +0200 Subject: [PATCH] Use module/log as log. --- log.go | 68 ++++++++++++++-------------------------------------------- 1 file changed, 16 insertions(+), 52 deletions(-) diff --git a/log.go b/log.go index 849e25a..ab2078d 100644 --- a/log.go +++ b/log.go @@ -1,67 +1,31 @@ package espresso import ( - "context" - "log/slog" - "os" - - "github.com/googollee/module" + "github.com/googollee/module/log" ) var ( - LogModule = module.New[*slog.Logger]() - LogText = LogModule.ProvideWithFunc(func(ctx context.Context) (*slog.Logger, error) { - handler := slog.NewTextHandler(os.Stderr, nil) - return slog.New(handler), nil - }) - LogJSON = LogModule.ProvideWithFunc(func(ctx context.Context) (*slog.Logger, error) { - handler := slog.NewJSONHandler(os.Stderr, nil) - return slog.New(handler), nil - }) + LogModule = log.Module + LogText = log.TextLogger + LogJSON = log.JSONLogger + + DEBUG = log.DEBUG + WARN = log.WARN + INFO = log.INFO + ERROR = log.ERROR ) -func DEBUG(ctx context.Context, msg string, args ...any) { - logger := LogModule.Value(ctx) - if logger == nil { - return - } - - logger.DebugContext(ctx, msg, args...) -} - -func INFO(ctx context.Context, msg string, args ...any) { - logger := LogModule.Value(ctx) - if logger == nil { - return - } - - logger.InfoContext(ctx, msg, args...) -} - -func WARN(ctx context.Context, msg string, args ...any) { - logger := LogModule.Value(ctx) - if logger == nil { - return - } - - logger.WarnContext(ctx, msg, args...) -} - -func ERROR(ctx context.Context, msg string, args ...any) { - logger := LogModule.Value(ctx) - if logger == nil { - return - } - - logger.ErrorContext(ctx, msg, args...) -} - func logHandling(ctx Context) error { method := ctx.Request().Method path := ctx.Request().URL.String() - INFO(ctx, "receive http", "method", method, "path", path) - defer INFO(ctx, "finish http", "method", method, "path", path) + slog := LogModule.Value(ctx) + if slog != nil { + ctx = ctx.WithParent(LogModule.With(ctx, slog.With("method", method, "path", path))) + } + + INFO(ctx, "receive http") + defer INFO(ctx, "finish http") ctx.Next()