Return written size when message was sent without error (#190)

- Fixes ErrShortWrite error if used with io.MultiWriter
This commit is contained in:
Ilja Neumann 2020-01-15 22:01:51 +01:00 committed by Olivier Poitrey
parent 65ed30bfb0
commit 505b18daf2
2 changed files with 49 additions and 1 deletions

View File

@ -73,7 +73,9 @@ func (w journalWriter) Write(p []byte) (n int, err error) {
err = fmt.Errorf("cannot connect to journalD") err = fmt.Errorf("cannot connect to journalD")
return return
} }
var event map[string]interface{} var event map[string]interface{}
origPLen := len(p)
p = cbor.DecodeIfBinaryToBytes(p) p = cbor.DecodeIfBinaryToBytes(p)
d := json.NewDecoder(bytes.NewReader(p)) d := json.NewDecoder(bytes.NewReader(p))
d.UseNumber() d.UseNumber()
@ -114,5 +116,10 @@ func (w journalWriter) Write(p []byte) (n int, err error) {
} }
args["JSON"] = string(p) args["JSON"] = string(p)
err = journal.Send(msg, jPrio, args) err = journal.Send(msg, jPrio, args)
if err == nil {
n = origPLen
}
return return
} }

View File

@ -2,7 +2,12 @@
package journald_test package journald_test
import "github.com/rs/zerolog" import (
"bytes"
"github.com/rs/zerolog"
"io"
"testing"
)
import "github.com/rs/zerolog/journald" import "github.com/rs/zerolog/journald"
func ExampleNewJournalDWriter() { func ExampleNewJournalDWriter() {
@ -42,3 +47,39 @@ Thu 2018-04-26 22:30:20.768136 PDT [s=3284d695bde946e4b5017c77a399237f;i=329f0;b
_PID=27103 _PID=27103
_SOURCE_REALTIME_TIMESTAMP=1524807020768136 _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!")
}
}