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

Add a slightly slower, but less verbose, logger #147

Closed
wants to merge 24 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
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
147 changes: 147 additions & 0 deletions benchmarks/zap_sugar_bench_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package benchmarks

import (
"testing"
"time"

"github.com/uber-go/zap"
"github.com/uber-go/zap/zwrap"
)

func fakeSugarFields() []interface{} {
return []interface{}{
errExample,
"int", 1,
"int64", 2,
"float", 3.0,
"string", "four!",
"stringer", zap.DebugLevel,
"bool", true,
"time", time.Unix(0, 0),
"duration", time.Second,
"another string", "done!",
}
}

var newCoreLoggerDefaults = []zap.Option{
zap.ErrorLevel,
zap.DiscardOutput,
}

func newCoreLogger(options ...zap.Option) zap.Logger {
options = append(newCoreLoggerDefaults, options...)
return zap.New(zap.NewJSONEncoder(), options...)
}

func newSugarLogger(options ...zap.Option) zap.Sugar {
return zap.NewSugar(newCoreLogger(options...))
}

func BenchmarkZapSugarDisabledLevelsWithoutFields(b *testing.B) {
logger := newSugarLogger()
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
logger.Info("Should be discarded.")
}
})
}

func BenchmarkZapSugarDisabledLevelsAccumulatedContext(b *testing.B) {
context := fakeFields()
logger := newSugarLogger(zap.Fields(context...))
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
logger.Info("Should be discarded.")
}
})
}

func BenchmarkZapSugarDisabledLevelsAddingFields(b *testing.B) {
logger := newSugarLogger()
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
logger.Info("Should be discarded.", fakeSugarFields()...)
}
})
}

func BenchmarkZapSugarAddingFields(b *testing.B) {
logger := newSugarLogger()
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
logger.Info("Go fast.", fakeSugarFields()...)
}
})
}

func BenchmarkZapSugarWithAccumulatedContext(b *testing.B) {
logger := newSugarLogger().With(fakeSugarFields()...)
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
logger.Info("Go really fast.")
}
})
}

func BenchmarkZapSugarWithoutFields(b *testing.B) {
logger := newSugarLogger()
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
logger.Info("Go fast.")
}
})
}

func BenchmarkZapSugarSampleWithoutFields(b *testing.B) {
messages := fakeMessages(1000)
core := newCoreLogger()
logger := zap.NewSugar(zwrap.Sample(core, time.Second, 10, 10000))
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
i := 0
for pb.Next() {
i++
logger.Info(messages[i%1000])
}
})
}

func BenchmarkZapSugarSampleAddingFields(b *testing.B) {
messages := fakeMessages(1000)
core := newCoreLogger()
logger := zap.NewSugar(zwrap.Sample(core, time.Second, 10, 10000))
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
i := 0
for pb.Next() {
i++
logger.Info(messages[i%1000], fakeSugarFields()...)
}
})
}
200 changes: 200 additions & 0 deletions sugar.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package zap

import (
"errors"
"fmt"
"time"
)

// Sugar is a wrapper around core logger with less verbose API
type Sugar interface {
// Level returns the minimum enabled log level
Level() Level

// SetLevel changes the level of this logger, as well as all its ancestors
// and descendants. This makes it easy to change the log level at runtime
// without restarting your application.
SetLevel(Level)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same comment here

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as above

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed


// With creates a child logger, and optionally add some context to that
// logger
With(...interface{}) Sugar

// Log a message at the given level. Messages include any context that's
// accumulated on the logger, as well as any fields added at the log site.
Log(Level, string, ...interface{})
Debug(string, ...interface{})
Info(string, ...interface{})
Warn(string, ...interface{})
Error(string, ...interface{})
Panic(string, ...interface{})
Fatal(string, ...interface{})

// DFatal logs at the Fatal level if the logger is in development mode (via
// the Development option), otherwise it logs at the Error level.
DFatal(string, ...interface{})
}

type sugar struct {
core Logger
}

func (s *sugar) internalError(msg string) {
s.core.(*logger).internalError(msg)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There should be no casts from Logger to *logger, as that will panic if the user passes some sort of wrapped logger (e.g., like one returned from sampling).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

internalErroris not declared for Logger interface. I'm not sure if there is another way to access it. Even if I re-implement this method on Sugar, ErrorOutput is still not declared on LoggerInterface. What do you suggest?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Feel free to defer this with a TODO, and we can circle back to it, since this will require some thinking about.

For now, make the internal error just do s.core.Error("Logger error", zap.String("message", msg)) or something.

As a separate PR, we need to think about either exposing the error output, or trying to cast the passed in logger to something that implements an internalError method, and if it's not implemented doing the log to the normal error stream.

}

// NewSugar is a constructor for Sugar
func NewSugar(core Logger) Sugar {
return &sugar{core}
}

func (s *sugar) Level() Level {
return s.core.Level()
}

func (s *sugar) SetLevel(lvl Level) {
s.core.SetLevel(lvl)
}

func (s *sugar) With(args ...interface{}) Sugar {
fields, err := getSugarFields(args...)
if err != nil {
s.internalError(err.Error())
}
return NewSugar(s.core.With(fields...))
}

func getSugarFields(args ...interface{}) ([]Field, error) {
var (
noErrArgs []interface{}

ii int
key string
value interface{}
)
fields := make([]Field, 0, len(args)/2)

if len(args) == 0 {
return fields, nil
}

switch err := args[0].(type) {
case error:
fields = append(fields, Error(err))
noErrArgs = args[1:]
default:
noErrArgs = args
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd prefer to remove this block; treating the first of the variadic arguments differently from the rest is a little too much magic for me.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So how do you suggest treating errors then? Alternative approach is expecting an error in any position and would involve even more magic.


if (len(noErrArgs) % 2) != 0 {
return nil, errors.New("invalid number of arguments")
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of returning an error, let's add a field to the log output describing the issue. In that case, we should ignore the last argument and include it in the error:

fields = append(fields, zap.String("numLogArgsError", fmt.Sprintf("odd number of arguments passed to logger, ignoring last arg: %v", args[len(args)-1])))`

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure I implemented it the way you expected, but please see b819160

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Latest commit makes sugar logger handle internal errors in the same way core logger does.


for ii, value = range noErrArgs {
if (ii % 2) == 0 {
switch value.(type) {
case string:
key = value.(string)
default:
return nil, errors.New("field name must be string")

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just my $0.02- Loggers usually don't throw/return errors and rather gulp them down to the log files. Instead of returning error for this function, you want to just add a string field with a tiny message "unparsable argument" or something. It should be on the devs to notice an fix the logging format later in the game.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed, please see b819160

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Latest commit makes sugar logger handle internal errors in the same way core logger does.

}
} else {
// TODO: Add LogMarshaler support, it once been here, but
// had to be removed because type switch won't catch
// this intarface properly for some mystical reason.
switch v := value.(type) {
case error:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure about this special casing for error. I think it's a little surprising, complicates the code, and will possibly cause unexpected errors.

For example, if some struct happens to satisfy the error interface (E.g., Thrift exceptions), then they will never be able to use it as a value.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure either but I don't see much options here. Also I think this wrapper supposed to be merely syntax sugar. It's not supposed to satisfy all possible requirements and just have to be "ok for most uses".

I'm open to any ideas about handling errors, but as for now this is the only working and (mostly) magic free implementation I can think of.

return nil, errors.New("error can only be the first argument")
case bool:
fields = append(fields, Bool(key, v))
case float64:
fields = append(fields, Float64(key, v))
case int:
fields = append(fields, Int(key, v))
case int64:
fields = append(fields, Int64(key, v))
case uint:
fields = append(fields, Uint(key, v))
case uint64:
fields = append(fields, Uint64(key, v))
case string:
fields = append(fields, String(key, v))
case time.Time:
fields = append(fields, Time(key, v))
case time.Duration:
fields = append(fields, Duration(key, v))
case fmt.Stringer:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fmt.Stringer should come after LogMarshaler -- if the type knows how to serialize itself, I think we should prefer that.

Please add a unit test to ensure that's the case as well.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I removed LogMarshaler altogether. As I mentioned in previous comments, type switch fails to catch structs implementing this interface for some reason.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you explain more about the type switch not catching this -- I think keeping log marshaler is a good idea, and it should work,

fields = append(fields, Stringer(key, v))
default:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is missing support for the error type.

in the existing zap logger, logging an error writes a key named "error". with the field count being used here, we have to decide if we want to support:

sugar.With("k1", 42, errors.New("this automatically goes into 'error'))`

or

sugar.With("k1", errors.New("nothing automatic"), "k2", errors.New("field is an errorType still"))

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suggest sugar logger should accept optional error value as the first of variadic arguments. E.g.:

sugar.Warn("message", errors.New("this is a error"), "a", "b")
{"level":"warn","msg":"message","err":"this is a error","a":"b"}

Motivation behind my suggestion is that having more then one errors in single log message is probably pretty rare requirement which don't need to be covered by syntax sugar.

Copy link
Contributor

@akshayjshah akshayjshah Sep 28, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(amended after looking more closely)

I'd prefer not to do this, since the common (non-error) case will then require passing a nil it makes our treatment of the first of the variadic arguments a bit too magical.

I'd prefer an API in which callers need to pass both the key and the value for errors: sugar.With("error", err). We'll need to add a case like this:

case error:
    fields = append(fields, String(key, value.(error).Error()))

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I missed this earlier, but it seems like both @akshayjshah and I think we should remove the first variadic argument can be error.

As for the checking the case error, I'd consider only allowing that for a field named "error", just in case someone wants to log a type that happens to implement error but they acutally want the object logged.

fields = append(fields, Object(key, value))
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this approach, if a type has String, there's no way to serialize the fields using the JSON marshaller.

}
}
}
return fields, nil
}

func (s *sugar) Log(lvl Level, msg string, args ...interface{}) {
var (
fields []Field
err error
)
if cm := s.core.Check(lvl, msg); cm.OK() {
Copy link
Contributor

@akshayjshah akshayjshah Sep 28, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Awesome - thanks for being careful to use the checked message API!

Since we're updating getSugarFields so that it won't need to return an error, let's not have this method (or any of the Info, Debug, Error, etc. method) return errors either.

fields, err = getSugarFields(args...)
if err != nil {
s.internalError(err.Error())
}
cm.Write(fields...)
}
}

func (s *sugar) Debug(msg string, args ...interface{}) {
s.Log(DebugLevel, msg, args...)
}

func (s *sugar) Info(msg string, args ...interface{}) {
s.Log(InfoLevel, msg, args...)
}

func (s *sugar) Warn(msg string, args ...interface{}) {
s.Log(WarnLevel, msg, args...)
}

func (s *sugar) Error(msg string, args ...interface{}) {
s.Log(ErrorLevel, msg, args...)
}

func (s *sugar) Panic(msg string, args ...interface{}) {
s.Log(PanicLevel, msg, args...)
}

func (s *sugar) Fatal(msg string, args ...interface{}) {
s.Log(FatalLevel, msg, args...)
}

func (s *sugar) DFatal(msg string, args ...interface{}) {
fields, err := getSugarFields(args...)
if err != nil {
s.internalError(err.Error())
}
s.core.DFatal(msg, fields...)
}
Loading