Skip to content

Commit

Permalink
slogutil: imp code
Browse files Browse the repository at this point in the history
  • Loading branch information
Mizzick committed Oct 24, 2024
1 parent 89f12e4 commit fe3135c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 11 deletions.
33 changes: 23 additions & 10 deletions logutil/slogutil/jsonhybrid.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package slogutil

import (
"context"
"encoding"
"encoding/json"
"fmt"
"io"
Expand All @@ -28,8 +29,11 @@ type JSONHybridHandler struct {
level slog.Leveler
encoder *json.Encoder
bufTextPool *syncutil.Pool[bufferedTextHandler]
mu *sync.Mutex
textAttrs []slog.Attr

// mu protects encoder.
mu *sync.Mutex

textAttrs []slog.Attr
}

// initLineLenEst is the estimation used to set the initial sizes of log-line
Expand Down Expand Up @@ -80,7 +84,7 @@ func (h *JSONHybridHandler) Handle(ctx context.Context, r slog.Record) (err erro
return fmt.Errorf("handling text for data: %w", err)
}

msg := bufTextHdlr.buffer.String()
msg := byteString(bufTextHdlr.buffer.Bytes())

// Remove newline.
msg = msg[:len(msg)-1]
Expand All @@ -92,18 +96,27 @@ func (h *JSONHybridHandler) Handle(ctx context.Context, r slog.Record) (err erro
return h.encoder.Encode(data)
}

// byteString optimizes memory allocations in [JSONHybridHandler.Handle].
type byteString []byte

// type check
var _ encoding.TextMarshaler = byteString{}

// MarshalText implements the [encoding.TextMarshaler] interface for byteString.
func (b byteString) MarshalText() (res []byte, err error) {
return b, nil
}

// jsonHybridMessage represents the data structure for *JSONHybridHandler.
type jsonHybridMessage = struct {
Severity string `json:"severity"`
Message string `json:"message"`
Severity string `json:"severity"`
Message byteString `json:"message"`
}

// newJSONHybridMessage returns new properly initialized message.
func newJSONHybridMessage(lvl slog.Level, msg string) (m *jsonHybridMessage) {
var severity string
if lvl < slog.LevelError {
severity = "NORMAL"
} else {
func newJSONHybridMessage(lvl slog.Level, msg byteString) (m *jsonHybridMessage) {
severity := "NORMAL"
if lvl >= slog.LevelError {
severity = "ERROR"
}

Expand Down
2 changes: 1 addition & 1 deletion logutil/slogutil/jsonhybrid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,5 +96,5 @@ func BenchmarkJSONHybridHandler_Handle(b *testing.B) {
// goarch: arm64
// pkg: github.com/AdguardTeam/golibs/logutil/slogutil
// cpu: Apple M1 Pro
// BenchmarkJSONHybridHandler_Handle-8 1929268 603.5 ns/op 128 B/op 2 allocs/op
// BenchmarkJSONHybridHandler_Handle-8 1992794 602.4 ns/op 48 B/op 1 allocs/op
}

0 comments on commit fe3135c

Please sign in to comment.