Skip to content

Commit 0072bc4

Browse files
committed
Add zapio.Writer
This adds a new zapio package that provides a `Writer`. The writer implements `io.WriteCloser` and `zapcore.WriteSyncer`. It works by splitting the input on newlines, flushing to the logger as new lines are encountered, and buffering input otherwise. So for example, if write "foobar\n" is split across multiple Write calls "foo" and "bar\n", instead of emitting two separate logs for "foo" and "bar", the Writer will buffer the input until the newline is encountered and write a single log for "foobar". Resolves #929
1 parent aa3e73e commit 0072bc4

File tree

2 files changed

+266
-0
lines changed

2 files changed

+266
-0
lines changed

zapio/writer.go

+108
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
// Copyright (c) 2021 Uber Technologies, Inc.
2+
//
3+
// Permission is hereby granted, free of charge, to any person obtaining a copy
4+
// of this software and associated documentation files (the "Software"), to deal
5+
// in the Software without restriction, including without limitation the rights
6+
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7+
// copies of the Software, and to permit persons to whom the Software is
8+
// furnished to do so, subject to the following conditions:
9+
//
10+
// The above copyright notice and this permission notice shall be included in
11+
// all copies or substantial portions of the Software.
12+
//
13+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15+
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16+
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17+
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18+
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19+
// THE SOFTWARE.
20+
21+
package zapio
22+
23+
import (
24+
"bytes"
25+
"io"
26+
27+
"go.uber.org/zap"
28+
"go.uber.org/zap/zapcore"
29+
)
30+
31+
// Writer is an io.Writer that writes to the provided Zap logger, splitting log
32+
// messages on line boundaries.
33+
//
34+
// Writer must be closed when finished to flush buffered data to the logger.
35+
type Writer struct {
36+
Log *zap.Logger // log to write to
37+
Level zapcore.Level // log level to write at
38+
39+
buff bytes.Buffer
40+
}
41+
42+
var (
43+
_ zapcore.WriteSyncer = (*Writer)(nil)
44+
_ io.Closer = (*Writer)(nil)
45+
)
46+
47+
// Write writes the provided bytes to the underlying logger at the configured
48+
// log level and returns the length of the bytes.
49+
func (w *Writer) Write(bs []byte) (n int, err error) {
50+
// Skip all checks if the level isn't enabled.
51+
if !w.Log.Core().Enabled(w.Level) {
52+
return len(bs), nil
53+
}
54+
55+
n = len(bs)
56+
for len(bs) > 0 {
57+
bs = w.writeLine(bs)
58+
}
59+
60+
return n, nil
61+
}
62+
63+
// writeLine writes a single line from the input, returning the remaining,
64+
// unconsumed bytes.
65+
func (w *Writer) writeLine(line []byte) (remaining []byte) {
66+
idx := bytes.IndexByte(line, '\n')
67+
if idx < 0 {
68+
// If there are no newlines, buffer the entire string.
69+
w.buff.Write(line)
70+
return nil
71+
}
72+
73+
// Split on the newline, buffer and flush the left.
74+
line, remaining = line[:idx], line[idx+1:]
75+
w.buff.Write(line)
76+
77+
// Log empty messages in the middle of the stream so that we don't lose
78+
// information when the user writes "foo\n\nbar".
79+
w.flush(true /* allowEmpty */)
80+
81+
return remaining
82+
}
83+
84+
// Close closes the writer, flushing any buffered data in the process.
85+
func (w *Writer) Close() error {
86+
return w.Sync()
87+
}
88+
89+
// Sync flushes the buffered data from the writer, even if it doesn't end with
90+
// a newline.
91+
func (w *Writer) Sync() error {
92+
// Don't allow empty messages on explicit Sync calls or on Close
93+
// because we don't want an extraneous empty message at the end of the
94+
// stream -- it's common for files to end with a newline.
95+
w.flush(false /* allowEmpty */)
96+
return nil
97+
}
98+
99+
// flush flushes the buffered data to the logger, allowing empty messages only
100+
// if the bool is set.
101+
func (w *Writer) flush(allowEmpty bool) {
102+
if allowEmpty || w.buff.Len() > 0 {
103+
if ce := w.Log.Check(w.Level, w.buff.String()); ce != nil {
104+
ce.Write()
105+
}
106+
}
107+
w.buff.Reset()
108+
}

zapio/writer_test.go

+158
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
// Copyright (c) 2021 Uber Technologies, Inc.
2+
//
3+
// Permission is hereby granted, free of charge, to any person obtaining a copy
4+
// of this software and associated documentation files (the "Software"), to deal
5+
// in the Software without restriction, including without limitation the rights
6+
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7+
// copies of the Software, and to permit persons to whom the Software is
8+
// furnished to do so, subject to the following conditions:
9+
//
10+
// The above copyright notice and this permission notice shall be included in
11+
// all copies or substantial portions of the Software.
12+
//
13+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15+
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16+
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17+
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18+
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19+
// THE SOFTWARE.
20+
21+
package zapio
22+
23+
import (
24+
"io"
25+
"testing"
26+
27+
"github.com/stretchr/testify/assert"
28+
"github.com/stretchr/testify/require"
29+
"go.uber.org/zap"
30+
"go.uber.org/zap/zapcore"
31+
"go.uber.org/zap/zaptest/observer"
32+
)
33+
34+
func TestWriter(t *testing.T) {
35+
t.Parallel()
36+
37+
tests := []struct {
38+
desc string
39+
level zapcore.Level // defaults to info
40+
writes []string
41+
want []zapcore.Entry
42+
}{
43+
{
44+
desc: "simple",
45+
writes: []string{
46+
"foo\n",
47+
"bar\n",
48+
"baz\n",
49+
},
50+
want: []zapcore.Entry{
51+
{Level: zap.InfoLevel, Message: "foo"},
52+
{Level: zap.InfoLevel, Message: "bar"},
53+
{Level: zap.InfoLevel, Message: "baz"},
54+
},
55+
},
56+
{
57+
desc: "level too low",
58+
level: zap.DebugLevel,
59+
writes: []string{
60+
"foo\n",
61+
"bar\n",
62+
},
63+
want: []zapcore.Entry{},
64+
},
65+
{
66+
desc: "multiple newlines in a message",
67+
level: zap.WarnLevel,
68+
writes: []string{
69+
"foo\nbar\n",
70+
"baz\n",
71+
"qux\nquux\n",
72+
},
73+
want: []zapcore.Entry{
74+
{Level: zap.WarnLevel, Message: "foo"},
75+
{Level: zap.WarnLevel, Message: "bar"},
76+
{Level: zap.WarnLevel, Message: "baz"},
77+
{Level: zap.WarnLevel, Message: "qux"},
78+
{Level: zap.WarnLevel, Message: "quux"},
79+
},
80+
},
81+
{
82+
desc: "message split across multiple writes",
83+
level: zap.ErrorLevel,
84+
writes: []string{
85+
"foo",
86+
"bar\nbaz",
87+
"qux",
88+
},
89+
want: []zapcore.Entry{
90+
{Level: zap.ErrorLevel, Message: "foobar"},
91+
{Level: zap.ErrorLevel, Message: "bazqux"},
92+
},
93+
},
94+
{
95+
desc: "blank lines in the middle",
96+
writes: []string{
97+
"foo\n\nbar\nbaz",
98+
},
99+
want: []zapcore.Entry{
100+
{Level: zap.InfoLevel, Message: "foo"},
101+
{Level: zap.InfoLevel, Message: ""},
102+
{Level: zap.InfoLevel, Message: "bar"},
103+
{Level: zap.InfoLevel, Message: "baz"},
104+
},
105+
},
106+
{
107+
desc: "blank line at the end",
108+
writes: []string{
109+
"foo\nbar\nbaz\n",
110+
},
111+
want: []zapcore.Entry{
112+
{Level: zap.InfoLevel, Message: "foo"},
113+
{Level: zap.InfoLevel, Message: "bar"},
114+
{Level: zap.InfoLevel, Message: "baz"},
115+
},
116+
},
117+
{
118+
desc: "multiple blank line at the end",
119+
writes: []string{
120+
"foo\nbar\nbaz\n\n",
121+
},
122+
want: []zapcore.Entry{
123+
{Level: zap.InfoLevel, Message: "foo"},
124+
{Level: zap.InfoLevel, Message: "bar"},
125+
{Level: zap.InfoLevel, Message: "baz"},
126+
{Level: zap.InfoLevel, Message: ""},
127+
},
128+
},
129+
}
130+
131+
for _, tt := range tests {
132+
tt := tt // for t.Parallel
133+
t.Run(tt.desc, func(t *testing.T) {
134+
t.Parallel()
135+
136+
core, observed := observer.New(zap.InfoLevel)
137+
138+
w := Writer{
139+
Log: zap.New(core),
140+
Level: tt.level,
141+
}
142+
143+
for _, s := range tt.writes {
144+
_, err := io.WriteString(&w, s)
145+
require.NoError(t, err, "Writer.Write failed.")
146+
}
147+
148+
assert.NoError(t, w.Close(), "Writer.Close failed.")
149+
150+
// Turn []observer.LoggedEntry => []zapcore.Entry
151+
got := make([]zapcore.Entry, observed.Len())
152+
for i, ent := range observed.AllUntimed() {
153+
got[i] = ent.Entry
154+
}
155+
assert.Equal(t, tt.want, got, "Logged entries do not match.")
156+
})
157+
}
158+
}

0 commit comments

Comments
 (0)