Skip to content

Commit

Permalink
Merge pull request #5 from krystal/add-writesyncers-option
Browse files Browse the repository at this point in the history
feat(options): add WriteSyncers option allowing use of multiple writers
  • Loading branch information
snovichkov authored Feb 18, 2023
2 parents 38924e4 + dc1209b commit f5dd0b1
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
24 changes: 23 additions & 1 deletion gelf.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,9 @@ var (
// chunkedMagicBytes chunked message magic bytes.
// See http://docs.graylog.org/en/2.4/pages/gelf.html.
chunkedMagicBytes = []byte{0x1e, 0x0f}

// Ensure *writer implements zapcore.WriteSyncer.
_ zapcore.WriteSyncer = (*writer)(nil)
)

// NewCore zap core constructor.
Expand Down Expand Up @@ -140,9 +143,15 @@ func NewCore(options ...Option) (_ zapcore.Core, err error) {
return nil, err
}

var ws zapcore.WriteSyncer = w
if len(conf.writeSyncers) > 0 {
var writers = append([]zapcore.WriteSyncer{w}, conf.writeSyncers...)
ws = zapcore.NewMultiWriteSyncer(writers...)
}

var core = zapcore.NewCore(
zapcore.NewJSONEncoder(conf.encoder),
zapcore.AddSync(w),
ws,
conf.enabler,
)

Expand Down Expand Up @@ -274,6 +283,14 @@ func EncodeName(value zapcore.NameEncoder) Option {
})
}

// WriteSyncers sets additional zapcore.WriteSyncers on the core.
func WriteSyncers(value ...zapcore.WriteSyncer) Option {
return optionFunc(func(conf *optionConf) error {
conf.writeSyncers = append(conf.writeSyncers, value...)
return nil
})
}

// NewReflectedEncoder set zapcore.EncoderConfig NewReflectedEncoder property.
func NewReflectedEncoder(value func(io.Writer) zapcore.ReflectedEncoder) Option {
return optionFunc(func(conf *optionConf) error {
Expand Down Expand Up @@ -380,6 +397,11 @@ func (w *writer) Write(buf []byte) (n int, err error) {
return n, nil
}

// Sync is a no-op, but required to implement the zapcore.WriteSyncer interface.
func (w *writer) Sync() error {
return nil
}

// Close implementation of io.WriteCloser.
func (*writeCloser) Close() error {
return nil
Expand Down
10 changes: 10 additions & 0 deletions gelf_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package gelf_test
import (
"encoding/json"
"io"
"os"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -147,6 +148,15 @@ func TestEncodeName(t *testing.T) {
assert.Implements(t, (*zapcore.Core)(nil), core, "Expect zapcore.Core")
}

func TestWriteSyncers(t *testing.T) {
var core, err = gelf.NewCore(
gelf.WriteSyncers(os.Stderr),
)

assert.Nil(t, err, "Unexpected error")
assert.Implements(t, (*zapcore.Core)(nil), core, "Expect zapcore.Core")
}

func TestNewReflectedEncoder(t *testing.T) {
var newEncoder = func(writer io.Writer) zapcore.ReflectedEncoder {
return json.NewEncoder(writer)
Expand Down

0 comments on commit f5dd0b1

Please sign in to comment.