Skip to content

Commit

Permalink
feat: add custom marshaler
Browse files Browse the repository at this point in the history
  • Loading branch information
samber committed Feb 11, 2024
1 parent 4010845 commit 608a718
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 7 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ type Option struct {

// optional: customize json payload builder
Converter Converter
// optional: custom marshaler
Marshaler func(v any) ([]byte, error)

// optional: see slog.HandlerOptions
AddSource bool
Expand Down
19 changes: 12 additions & 7 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ type Option struct {

// optional: customize json payload builder
Converter Converter
// optional: custom marshaler
Marshaler func(v any) ([]byte, error)

// optional: see slog.HandlerOptions
AddSource bool
Expand All @@ -36,6 +38,14 @@ func (o Option) NewSyslogHandler() slog.Handler {
panic("missing syslog server connections")
}

if o.Converter == nil {
o.Converter = DefaultConverter
}

if o.Marshaler == nil {
o.Marshaler = json.Marshal
}

return &SyslogHandler{
option: o,
attrs: []slog.Attr{},
Expand All @@ -56,14 +66,9 @@ func (h *SyslogHandler) Enabled(_ context.Context, level slog.Level) bool {
}

func (h *SyslogHandler) Handle(ctx context.Context, record slog.Record) error {
converter := DefaultConverter
if h.option.Converter != nil {
converter = h.option.Converter
}

message := converter(h.option.AddSource, h.option.ReplaceAttr, h.attrs, h.groups, &record)
message := h.option.Converter(h.option.AddSource, h.option.ReplaceAttr, h.attrs, h.groups, &record)

bytes, err := json.Marshal(message)
bytes, err := h.option.Marshaler(message)
if err != nil {
return err
}
Expand Down

0 comments on commit 608a718

Please sign in to comment.