Skip to content

Commit

Permalink
Return written size when message was sent without error (rs#190)
Browse files Browse the repository at this point in the history
- Fixes ErrShortWrite error if used with io.MultiWriter
  • Loading branch information
IljaN authored and rs committed Jan 15, 2020
1 parent 65ed30b commit 505b18d
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
7 changes: 7 additions & 0 deletions journald/journald.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,9 @@ func (w journalWriter) Write(p []byte) (n int, err error) {
err = fmt.Errorf("cannot connect to journalD")
return
}

var event map[string]interface{}
origPLen := len(p)
p = cbor.DecodeIfBinaryToBytes(p)
d := json.NewDecoder(bytes.NewReader(p))
d.UseNumber()
Expand Down Expand Up @@ -114,5 +116,10 @@ func (w journalWriter) Write(p []byte) (n int, err error) {
}
args["JSON"] = string(p)
err = journal.Send(msg, jPrio, args)

if err == nil {
n = origPLen
}

return
}
43 changes: 42 additions & 1 deletion journald/journald_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@

package journald_test

import "github.com/rs/zerolog"
import (
"bytes"
"github.com/rs/zerolog"
"io"
"testing"
)
import "github.com/rs/zerolog/journald"

func ExampleNewJournalDWriter() {
Expand Down Expand Up @@ -42,3 +47,39 @@ Thu 2018-04-26 22:30:20.768136 PDT [s=3284d695bde946e4b5017c77a399237f;i=329f0;b
_PID=27103
_SOURCE_REALTIME_TIMESTAMP=1524807020768136
*/

func TestWriteReturnsNoOfWrittenBytes(t *testing.T) {
input := []byte(`{"level":"info","time":1570912626,"message":"Starting..."}`)
wr := journald.NewJournalDWriter()
want := len(input)
got, err := wr.Write(input)

if err != nil {
t.Errorf("Unexpected error %v", err)
}

if want != got {
t.Errorf("Expected %d bytes to be written got %d", want, got)
}
}

func TestMultiWrite(t *testing.T) {
var (
w1 = new(bytes.Buffer)
w2 = new(bytes.Buffer)
w3 = journald.NewJournalDWriter()
)

zerolog.ErrorHandler = func(err error) {
if err == io.ErrShortWrite {
t.Errorf("Unexpected ShortWriteError")
t.FailNow()
}
}

log := zerolog.New(io.MultiWriter(w1, w2, w3)).With().Logger()

for i := 0; i < 10; i++ {
log.Info().Msg("Tick!")
}
}

0 comments on commit 505b18d

Please sign in to comment.