Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make With fields surrounding with [] #4

Merged
merged 4 commits into from
Mar 5, 2019
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion log.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func InitLogger(cfg *Config, opts ...zap.Option) (*zap.Logger, *ZapProperties, e
if err != nil {
return nil, nil, err
}
core := zapcore.NewCore(newZapTextEncoder(cfg), output, level)
core := NewTextCore(newZapTextEncoder(cfg).(*textEncoder), output, level)
opts = append(opts, cfg.buildOptions(output)...)
lg := zap.New(core, opts...)
r := &ZapProperties{
Expand Down
30 changes: 20 additions & 10 deletions zap_log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,13 +77,21 @@ func (v *verifyLogger) AssertContains(substr string) {
}
}

func (v *verifyLogger) With(fields ...zap.Field) verifyLogger {
newLg := v.Logger.With(fields...)
return verifyLogger{
Logger: newLg,
w: v.w,
}
}

func newZapTestLogger(cfg *Config, c *C) verifyLogger {
writer := newTestingWriter(c)
opt := cfg.buildOptions(writer)
level := zap.NewAtomicLevel()
err := level.UnmarshalText([]byte(cfg.Level))
c.Assert(err, IsNil)
lg := zap.New(zapcore.NewCore(newZapTextEncoder(cfg), writer, level), opt...)
lg := zap.New(NewTextCore(newZapTextEncoder(cfg).(*textEncoder), writer, level), opt...)
return verifyLogger{
Logger: lg,
w: writer,
Expand Down Expand Up @@ -122,6 +130,7 @@ func (t *testZapLogSuite) TestLog(c *C) {
"Counter", math.NaN(),
"Score", math.Inf(1),
)
lg.With(zap.String("connID", "1"), zap.String("traceID", "dse1121")).Info("new connection")
lg.Info("Testing typs",
zap.String("filed1", "noquote"),
zap.String("filed2", "in quote"),
Expand Down Expand Up @@ -153,15 +162,16 @@ func (t *testZapLogSuite) TestLog(c *C) {
zap.Duration("duration", 10*time.Second),
)
lg.AssertMessage(
`[INFO] [zap_log_test.go:98] ["failed to fetch URL"] [url=http://example.com] [attempt=3] [backoff=1s]`,
`[INFO] [zap_log_test.go:103] ["failed to \"fetch\" [URL]: http://example.com"]`,
`[DEBUG] [zap_log_test.go:104] ["Slow query"] [sql="SELECT * FROM TABLE\n\tWHERE ID=\"abc\""] [duration=1.3s] ["process keys"=1500]`,
`[INFO] [zap_log_test.go:110] [Welcome]`,
`[INFO] [zap_log_test.go:111] ["Welcome TiDB"]`,
`[INFO] [zap_log_test.go:112] [欢迎]`,
`[INFO] [zap_log_test.go:113] ["欢迎来到 TiDB"]`,
`[WARN] [zap_log_test.go:114] [Type] [Counter=NaN] [Score=+Inf]`,
`[INFO] [zap_log_test.go:118] ["Testing typs"] [filed1=noquote] `+
`[INFO] [zap_log_test.go:113] ["failed to fetch URL"] [url=http://example.com] [attempt=3] [backoff=1s]`,
`[INFO] [zap_log_test.go:118] ["failed to \"fetch\" [URL]: http://example.com"]`,
`[DEBUG] [zap_log_test.go:119] ["Slow query"] [sql="SELECT * FROM TABLE\n\tWHERE ID=\"abc\""] [duration=1.3s] ["process keys"=1500]`,
`[INFO] [zap_log_test.go:125] [Welcome]`,
`[INFO] [zap_log_test.go:126] ["Welcome TiDB"]`,
`[INFO] [zap_log_test.go:127] [欢迎]`,
`[INFO] [zap_log_test.go:128] ["欢迎来到 TiDB"]`,
`[WARN] [zap_log_test.go:129] [Type] [Counter=NaN] [Score=+Inf]`,
`[INFO] [zap_log_test.go:133] ["new connection"] [connID=1] [traceID=dse1121]`,
`[INFO] [zap_log_test.go:134] ["Testing typs"] [filed1=noquote] `+
`[filed2="in quote"] [urls="[http://mock1.com:2347,http://mock2.com:2432]"] `+
`[urls-peer="[t1,\"t2 fine\"]"] ["store ids"="[1,4,5]"] [object="{username=user1}"] `+
`[object2="{username=\"user 2\"}"] [binary="YWIxMjM="] ["is processed"=true] `+
Expand Down
77 changes: 77 additions & 0 deletions zap_text_core.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// Copyright 2019 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.

package log

import "go.uber.org/zap/zapcore"

// NewTextCore creates a Core that writes logs to a WriteSyncer.
func NewTextCore(enc *textEncoder, ws zapcore.WriteSyncer, enab zapcore.LevelEnabler) zapcore.Core {
return &textIOCore{
LevelEnabler: enab,
enc: enc,
out: ws,
}
}

// textIOCore is a copy of zapcore.ioCore that only accept *textEncoder
// it can be removed after https://github.com/uber-go/zap/pull/685 be merged
type textIOCore struct {
zapcore.LevelEnabler
enc *textEncoder
out zapcore.WriteSyncer
}

func (c *textIOCore) With(fields []zapcore.Field) zapcore.Core {
clone := c.clone()
// it's different to ioCore, here call textEncoder#addFields to fix https://github.com/pingcap/log/issues/3
clone.enc.addFields(fields)
return clone
}

func (c *textIOCore) Check(ent zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry {
if c.Enabled(ent.Level) {
return ce.AddCore(ent, c)
}
return ce
}

func (c *textIOCore) Write(ent zapcore.Entry, fields []zapcore.Field) error {
buf, err := c.enc.EncodeEntry(ent, fields)
if err != nil {
return err
}
_, err = c.out.Write(buf.Bytes())
buf.Free()
if err != nil {
return err
}
if ent.Level > zapcore.ErrorLevel {
// Since we may be crashing the program, sync the output. Ignore Sync
// errors, pending a clean solution to issue #370.
c.Sync()
}
return nil
}

func (c *textIOCore) Sync() error {
return c.out.Sync()
}

func (c *textIOCore) clone() *textIOCore {
return &textIOCore{
LevelEnabler: c.LevelEnabler,
enc: c.enc.Clone().(*textEncoder),
out: c.out,
}
}
6 changes: 3 additions & 3 deletions zap_text_encoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -431,10 +431,10 @@ func (enc *textEncoder) EncodeEntry(ent zapcore.Entry, fields []zapcore.Field) (
final.endQuoteFiled()
}
if enc.buf.Len() > 0 {
final.addElementSeparator()
final.buf.AppendByte(' ')
final.buf.Write(enc.buf.Bytes())
}
addFields(final, fields)
final.addFields(fields)
final.closeOpenNamespaces()
if ent.Stack != "" && final.StacktraceKey != "" {
final.beginQuoteFiled()
Expand Down Expand Up @@ -599,7 +599,7 @@ func (enc *textEncoder) tryAddRuneError(r rune, size int) bool {
return false
}

func addFields(enc *textEncoder, fields []zapcore.Field) {
func (enc *textEncoder) addFields(fields []zapcore.Field) {
for i := range fields {
enc.beginQuoteFiled()
fields[i].AddTo(enc)
Expand Down