Skip to content

Commit

Permalink
rebased
Browse files Browse the repository at this point in the history
Signed-off-by: Jordan Rash <[email protected]>
  • Loading branch information
jordan-rash committed Jan 14, 2025
1 parent 4876753 commit 89488ce
Show file tree
Hide file tree
Showing 7 changed files with 47 additions and 12 deletions.
4 changes: 2 additions & 2 deletions examples/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ require (
github.com/nats-io/nkeys v0.4.7 // indirect
github.com/nats-io/nuid v1.0.1 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
golang.org/x/crypto v0.31.0 // indirect
golang.org/x/sys v0.28.0 // indirect
golang.org/x/crypto v0.22.0 // indirect
golang.org/x/sys v0.26.0 // indirect
golang.org/x/time v0.5.0 // indirect
)
8 changes: 4 additions & 4 deletions examples/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,12 @@ github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30=
golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M=
golang.org/x/sys v0.0.0-20190130150945-aca44879d564/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo=
golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
Expand Down
10 changes: 8 additions & 2 deletions examples/simple/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@ import (
)

func main() {
logger := slog.New(handler.NewHandler(handler.WithJSON()))
logger := slog.New(handler.NewHandler(handler.WithJSON(), handler.WithPid()))
logger.Info("test info")
logger.Debug("test debug")
logger.Info("test info", slog.String("key", "value"))
logger.WithGroup("mygroup").Info("test info", slog.String("key", "value"))

logger = slog.New(handler.NewHandler(handler.WithLogLevel(slog.LevelDebug), handler.WithColor()))
logger = slog.New(handler.NewHandler(handler.WithLogLevel(slog.LevelDebug), handler.WithColor(), handler.WithPid()))
logger.Info("test info")
logger.Debug("test debug")
logger.Warn("test info", slog.String("key", "value"))
Expand Down Expand Up @@ -66,4 +66,10 @@ func main() {
))
logger.Error("error")
logger.Log(context.Background(), handler.LevelFatal, "fatal")

logger = slog.New(handler.NewHandler(
handler.WithLogLevel(slog.LevelError),
handler.WithPid(),
))
logger.Error("error")
}
13 changes: 11 additions & 2 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (

type Handler struct {
json bool
pid bool
shortLevels bool
out []io.Writer
err []io.Writer
Expand All @@ -42,6 +43,7 @@ type HandlerOption func(*Handler)

func NewHandler(opts ...HandlerOption) *Handler {
nh := &Handler{
pid: false,
attrs: []slog.Attr{},
out: []io.Writer{os.Stdout},
err: []io.Writer{os.Stderr},
Expand Down Expand Up @@ -158,9 +160,14 @@ func (n *Handler) Handle(ctx context.Context, record slog.Record) error {
recordLevel = level()
}

var pid string
if n.pid {
pid = strconv.Itoa(os.Getpid())
}

if !n.json {
if len(attrs) == 0 {
printerf(outLoc(), textFormat(), recordLevel, record.Time.Format(n.timeFormat), record.Message)
printerf(outLoc(), pid, textFormat(), recordLevel, record.Time.Format(n.timeFormat), record.Message)
} else {
attsString := strings.Builder{}
for i, a := range attrs {
Expand All @@ -170,7 +177,7 @@ func (n *Handler) Handle(ctx context.Context, record slog.Record) error {
}
}
output := strings.TrimSpace(textFormat()) + " " + attsString.String() + "\n"
printerf(outLoc(), output, recordLevel, record.Time.Format(n.timeFormat), record.Message)
printerf(outLoc(), pid, output, recordLevel, record.Time.Format(n.timeFormat), record.Message)
}
} else {
a_map := make(map[string]any)
Expand All @@ -184,6 +191,7 @@ func (n *Handler) Handle(ctx context.Context, record slog.Record) error {
Message: record.Message,
Group: n.group,
Attrs: a_map,
Pid: pid,
}

l_raw, _ := json.Marshal(l)
Expand Down Expand Up @@ -329,4 +337,5 @@ type jsonLog struct {
Message string `json:"message"`
Group string `json:"group,omitempty"`
Attrs map[string]any `json:"attrs,omitempty"`
Pid string `json:"pid,omitempty"`
}
10 changes: 10 additions & 0 deletions handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"io"
"log/slog"
"os"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -203,10 +204,19 @@ func TestFromConfig(t *testing.T) {

config_logger, err := handler.NewHandlerFromConfig(logger_config, []io.Writer{&stdout}, nil)
assert.Nil(t, err)

slog.New(config_logger).Info("test")
assert.Equal(t, fmt.Sprintf("copyme | [INFO] %s - test foo=bar\n", now), stdout.String())
}

func TestLogWithPid(t *testing.T) {
var stdout bytes.Buffer
now := time.Now().Format(time.TimeOnly)
logger := slog.New(handler.NewHandler(handler.WithStdOut(&stdout), handler.WithPid()))
logger.Info("test")
assert.Equal(t, fmt.Sprintf("[%d] [INFO] %s - test\n", os.Getpid(), now), stdout.String())
}

func BenchmarkHandlers(b *testing.B) {
var stdout bytes.Buffer
bt := []struct {
Expand Down
6 changes: 6 additions & 0 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ func WithJSON() HandlerOption {
}
}

func WithPid() HandlerOption {
return func(h *Handler) {
h.pid = true
}
}

func WithStdOut(out ...io.Writer) HandlerOption {
return func(h *Handler) {
h.out = out
Expand Down
8 changes: 6 additions & 2 deletions print.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,12 @@ func printer(src []io.Writer, data ...any) {
}
}

func printerf(src []io.Writer, format string, data ...any) {
func printerf(src []io.Writer, pid string, format string, data ...any) {
for _, s := range src {
fmt.Fprintf(s, format, data...)
if pid == "" {
fmt.Fprintf(s, format, data...)
} else {
fmt.Fprintf(s, "["+pid+"] "+format, data...)
}
}
}

0 comments on commit 89488ce

Please sign in to comment.