Skip to content

Commit

Permalink
test: comment out slogtest.Run
Browse files Browse the repository at this point in the history
Signed-off-by: knqyf263 <[email protected]>
  • Loading branch information
knqyf263 committed Apr 8, 2024
1 parent d355d7c commit 295a6e9
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 16 deletions.
2 changes: 1 addition & 1 deletion pkg/log/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func WithContextAttrs(ctx context.Context, attrs ...slog.Attr) context.Context {
}

func contextualAttrs(ctx context.Context) []slog.Attr {
if attrs, ok := ctx.Value(prefixKey{}).([]slog.Attr); ok {
if attrs, ok := ctx.Value(attrKey{}).([]slog.Attr); ok {
return attrs
}
return nil
Expand Down
21 changes: 14 additions & 7 deletions pkg/log/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,15 +129,15 @@ func (h *ColorHandler) appendAttr(buf []byte, a slog.Attr, groups []string) []by
return buf
}

func (h *ColorHandler) Handle(_ context.Context, r slog.Record) error {
func (h *ColorHandler) Handle(ctx context.Context, r slog.Record) error {
bufp := allocBuf()
buf := *bufp
defer func() {
*bufp = buf
freeBuf(bufp)
}()

buf = h.handle(buf, r)
buf = h.handle(ctx, buf, r)

h.mu.Lock()
defer h.mu.Unlock()
Expand All @@ -149,7 +149,7 @@ func (h *ColorHandler) Handle(_ context.Context, r slog.Record) error {
return nil
}

func (h *ColorHandler) handle(buf []byte, r slog.Record) []byte {
func (h *ColorHandler) handle(ctx context.Context, buf []byte, r slog.Record) []byte {
colorize := color.New()
switch r.Level {
case slog.LevelDebug:
Expand All @@ -175,20 +175,27 @@ func (h *ColorHandler) handle(buf []byte, r slog.Record) []byte {
buf = append(buf, '\t')

// Message
buf = append(buf, r.Message...)
buf = append(buf, contextualPrefix(ctx)+r.Message...)
if r.Level == LevelFatal {
// Show the error and return early.
format := lo.Ternary(h.opts.Level == slog.LevelDebug, "\n - %+v\n", "\t%v\n")
return fmt.Appendf(buf, format, h.Err(r))
}

// Attrs
if len(h.preformatted) > 0 || r.NumAttrs() > 0 {
var preformatted []byte
for _, a := range contextualAttrs(ctx) {
preformatted = h.appendAttr(preformatted, a, h.groups)
preformatted = append(preformatted, ' ')
}
preformatted = append(preformatted, h.preformatted...)

if len(preformatted) > 0 || r.NumAttrs() > 0 {
buf = append(buf, '\t')
}

if len(h.preformatted) > 0 {
buf = append(buf, h.preformatted...)
if len(preformatted) > 0 {
buf = append(buf, preformatted...)
}
r.Attrs(func(a slog.Attr) bool {
buf = h.appendAttr(buf, a, h.groups)
Expand Down
40 changes: 40 additions & 0 deletions pkg/log/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package log_test

import (
"bytes"
"context"
"errors"
"fmt"
"github.com/aquasecurity/trivy/pkg/log"
Expand Down Expand Up @@ -93,6 +94,44 @@ func TestWithAttrsAndWithGroup(t *testing.T) {
})
}

func TestContext(t *testing.T) {
t.Run("with context prefix", func(t *testing.T) {
var buf bytes.Buffer
baseLogger := log.New(log.NewHandler(&buf, &log.Options{Level: slog.LevelInfo}))

// Test logging with WithContextPrefix
ctx := context.Background()
ctx = log.WithContextPrefix(ctx, "prefix1")

logger := baseLogger.With("key1", "value1").WithGroup("group1")
logger.InfoContext(ctx, "info message", "key2", true)

got := buf.String()
wantLines := []string{
`INFO [prefix1] info message key1="value1" group1.key2=true`,
}
compareLines(t, got, wantLines)
})

t.Run("with context attrs", func(t *testing.T) {
var buf bytes.Buffer
baseLogger := log.New(log.NewHandler(&buf, &log.Options{Level: slog.LevelInfo}))

// Test logging with WithContextAttrs
ctx := context.Background()
ctx = log.WithContextAttrs(ctx, log.String("key1", "value1"))

logger := baseLogger.WithGroup("group1")
logger.InfoContext(ctx, "info message", "key2", true)

got := buf.String()
wantLines := []string{
`INFO info message group1.key1="value1" group1.key2=true`,
}
compareLines(t, got, wantLines)
})
}

func compareLines(t *testing.T, got string, wantLines []string) {
// Strip color codes from the output.
got = stripColorCodes(got)
Expand Down Expand Up @@ -126,6 +165,7 @@ func stripColorCodes(s string) string {
return s
}

// TODO: slogtest.Run was added in Go 1.22. Waiting for https://github.com/aquasecurity/trivy/pull/6075.
func TestSlogtest(t *testing.T) {
var buf bytes.Buffer
newHandler := func(*testing.T) slog.Handler {
Expand Down
12 changes: 4 additions & 8 deletions pkg/log/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,26 +81,22 @@ func (l *Logger) Log(ctx context.Context, level slog.Level, msg string, args ...
func (l *Logger) Debug(msg string, args ...any) { l.inner.Debug(l.prefix+msg, args...) }
func (l *Logger) Debugf(format string, args ...any) { l.Debug(fmt.Sprintf(format, args...)) }
func (l *Logger) DebugContext(ctx context.Context, msg string, args ...any) {
args = append([]any{contextualAttrs(ctx)}, args...)
l.inner.DebugContext(ctx, contextualPrefix(ctx)+msg, args...)
l.inner.DebugContext(ctx, msg, args...)
}
func (l *Logger) Info(msg string, args ...any) { l.inner.Info(l.prefix+msg, args...) }
func (l *Logger) Infof(format string, args ...any) { l.Info(fmt.Sprintf(format, args...)) }
func (l *Logger) InfoContext(ctx context.Context, msg string, args ...any) {
args = append([]any{contextualAttrs(ctx)}, args...)
l.inner.InfoContext(ctx, contextualPrefix(ctx)+msg, args...)
l.inner.InfoContext(ctx, msg, args...)
}
func (l *Logger) Warn(msg string, args ...any) { l.inner.Warn(l.prefix+msg, args...) }
func (l *Logger) Warnf(format string, args ...any) { l.Warn(fmt.Sprintf(format, args...)) }
func (l *Logger) WarnContext(ctx context.Context, msg string, args ...any) {
args = append([]any{contextualAttrs(ctx)}, args...)
l.inner.WarnContext(ctx, contextualPrefix(ctx)+msg, args...)
l.inner.WarnContext(ctx, msg, args...)
}
func (l *Logger) Error(msg string, args ...any) { l.inner.Error(l.prefix+msg, args...) }
func (l *Logger) Errorf(format string, args ...any) { l.Error(fmt.Sprintf(format, args...)) }
func (l *Logger) ErrorContext(ctx context.Context, msg string, args ...any) {
args = append([]any{contextualAttrs(ctx)}, args...)
l.inner.ErrorContext(ctx, contextualPrefix(ctx)+msg, args...)
l.inner.ErrorContext(ctx, msg, args...)
}

func (l *Logger) Write(p []byte) (n int, err error) {
Expand Down

0 comments on commit 295a6e9

Please sign in to comment.