Skip to content

Commit

Permalink
NewXRayLogger now see the environment variable AWS_XRAY_LOG_LEVEL.
Browse files Browse the repository at this point in the history
  • Loading branch information
shogo82148 committed Sep 22, 2023
1 parent 67e1311 commit d4c0172
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
3 changes: 3 additions & 0 deletions xray/xraylog/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ const (

// LogLevelError is error level.
LogLevelError

// LogLevelSilent disables the log of the xray tracer.
LogLevelSilent
)

func (ll LogLevel) String() string {
Expand Down
43 changes: 41 additions & 2 deletions xray/xrayslog/xrayslog.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,37 @@ import (
"context"
"fmt"
"log/slog"
"os"
"runtime"
"strings"
"time"

"github.com/shogo82148/aws-xray-yasdk-go/xray"
"github.com/shogo82148/aws-xray-yasdk-go/xray/xraylog"
)

func getLogLevelFromEnv() xraylog.LogLevel {
level := xraylog.LogLevelInfo
if os.Getenv("AWS_XRAY_DEBUG_MODE") != "" {
level = xraylog.LogLevelDebug
} else if env := os.Getenv("AWS_XRAY_LOG_LEVEL"); env != "" {
env = strings.ToLower(env)
switch env {
case "debug":
level = xraylog.LogLevelDebug
case "info":
level = xraylog.LogLevelInfo
case "warn":
level = xraylog.LogLevelWarn
case "error":
level = xraylog.LogLevelError
case "silent":
return xraylog.LogLevelSilent
}
}
return level
}

var _ slog.Handler = (*handler)(nil)

type handler struct {
Expand Down Expand Up @@ -85,16 +109,31 @@ func NewHandler(parent slog.Handler, traceIDKey string) slog.Handler {
}

type xrayLogger struct {
h slog.Handler
h slog.Handler
minLevel xraylog.LogLevel
}

// NewXRayLogger returns a new [xraylog.Logger] such that each call to its Output method dispatches a Record to the specified handler.
// The logger acts as a bridge from the older xraylog API to newer structured logging handlers.
// The log level is determined by the environment variable AWS_XRAY_LOG_LEVEL.
func NewXRayLogger(h slog.Handler) xraylog.Logger {
return &xrayLogger{h}
return NewXRayLoggerWithMinLevel(h, getLogLevelFromEnv())
}

// NewXRayLoggerWithMinLevel returns a new [xraylog.Logger] such that each call to its Output method dispatches a Record to the specified handler.
// The logger acts as a bridge from the older xraylog API to newer structured logging handlers.
func NewXRayLoggerWithMinLevel(h slog.Handler, minLogLevel xraylog.LogLevel) xraylog.Logger {
if minLogLevel == xraylog.LogLevelSilent {
return xraylog.NullLogger{}
}
return &xrayLogger{h, minLogLevel}
}

func (l *xrayLogger) Log(ctx context.Context, level xraylog.LogLevel, msg fmt.Stringer) {
if level < l.minLevel {
return
}

lv := xraylogLevelToSlog(level)
if !l.h.Enabled(ctx, lv) {
return
Expand Down

0 comments on commit d4c0172

Please sign in to comment.