Skip to content

Commit

Permalink
Use module/log as log.
Browse files Browse the repository at this point in the history
  • Loading branch information
googollee committed Jul 29, 2024
1 parent 02dc8d2 commit 0ace15e
Showing 1 changed file with 16 additions and 52 deletions.
68 changes: 16 additions & 52 deletions log.go
Original file line number Diff line number Diff line change
@@ -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()

Expand Down

0 comments on commit 0ace15e

Please sign in to comment.