Backend for improving test logging (#1022)

* Create TLogger, bringing leveled logging to tests

Inspired heavily by go-logr, brings leveled logging to tests while
using the highly reliable zap logger backend to fulfill writing to
multiple log files.

Now that metrics logger has been removed, SetupLoggingFlags() is redundant. Moved to test/logging

* Cleanup TLogger and document

Add TLogger.Collect() to support collecting outcomes (either positive
strings or error types) which will be processed in a subtest upon
completion of the currently-running (sub-)test.

StructuredError prints its output in a more-readable form now.

Call-site should now work for .Log/.Logf-using functions.

Use cancel from NewTLogger instead of t.CleanUp()

Use a zapcore SpewEncoder when writing to testing.T

Means even non-json-encodable structs will get printed to the test log
output, while preserving encodable structured output for other log files.

Removed timestamp from printing to t.Log

* Fix the automatically-detected issues

Spelling, codegen, some coverage (coverage of memory_encoder.go should
not be necessary but the coverage tool is broken and needs to be fixed).

* Increase unit test coverage slightly and fix tiny comment

* Set attribute the way the coverage program wants

* Cleanup based on notes

* Comment cleanup and privitize var

* Mistake; left purposely-failing tests enabled

* Reduce long lines

* Consolidate cleanup code; make variable expressive

* Cleanup and bugfix

Failing functions now tested by having an internal constructor
option to skip calls to t.Fail()/t.FailNow().

Fixed some bugs with internal method errorWithRuntimeCheck and added
tests for it.

Address minor typos from comments.

* Tiny name/optimization fixes
This commit is contained in:
coryrc 2020-02-19 13:57:05 -08:00 committed by GitHub
parent 5d8a01d12c
commit a81f50a34e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
22 changed files with 2172 additions and 223 deletions

27
Gopkg.lock generated
View File

@ -148,6 +148,22 @@
revision = "0ca9ea5df5451ffdf184b4428c902747c2c11cd7"
version = "v1.0.0"
[[projects]]
digest = "1:53becd66889185091b58ea3fc49294996f2179fb05a89702f4de7d15e581b509"
name = "github.com/go-logr/logr"
packages = ["."]
pruneopts = "NUT"
revision = "9fb12b3b21c5415d16ac18dc5cd42c1cfdd40c4e"
version = "v0.1.0"
[[projects]]
digest = "1:340497a512995aa69c0add901d79a2096b3449d35a44a6f1f1115091a9f8c687"
name = "github.com/go-logr/zapr"
packages = ["."]
pruneopts = "NUT"
revision = "03f06a783fbb7dfaf3f629c7825480e43a7105e6"
version = "v0.1.1"
[[projects]]
digest = "1:53151cc4366e3945282d4b783fd41f35222cabbc75601e68d8133648c63498d1"
name = "github.com/gobuffalo/envy"
@ -1279,12 +1295,12 @@
revision = "e17681d19d3ac4837a019ece36c2a0ec31ffe985"
[[projects]]
digest = "1:43099cc4ed575c40f80277c7ba7168df37d0c663bdc4f541325430bd175cce8a"
digest = "1:c0693cb981f43d82a767a3217b7640a4bdb341731d3814b38602f4e5dc4f01b3"
name = "k8s.io/klog"
packages = ["."]
pruneopts = "NUT"
revision = "d98d8acdac006fb39831f1b25640813fef9c314f"
version = "v0.3.3"
revision = "2ca9ad30301bf30a8a6e0fa2110db6b8df699a91"
version = "v1.0.0"
[[projects]]
branch = "master"
@ -1355,8 +1371,9 @@
"github.com/davecgh/go-spew/spew",
"github.com/evanphx/json-patch",
"github.com/ghodss/yaml",
"github.com/go-logr/logr",
"github.com/go-logr/zapr",
"github.com/gogo/protobuf/proto",
"github.com/golang/glog",
"github.com/golang/protobuf/jsonpb",
"github.com/golang/protobuf/proto",
"github.com/google/go-cmp/cmp",
@ -1388,7 +1405,9 @@
"go.opencensus.io/stats/view",
"go.opencensus.io/tag",
"go.opencensus.io/trace",
"go.uber.org/multierr",
"go.uber.org/zap",
"go.uber.org/zap/buffer",
"go.uber.org/zap/zapcore",
"go.uber.org/zap/zaptest",
"golang.org/x/net/context",

View File

@ -13,6 +13,8 @@ required = [
"knative.dev/test-infra/scripts",
"knative.dev/test-infra/tools/dep-collector",
"github.com/gogo/protobuf/proto",
"github.com/go-logr/logr",
"github.com/go-logr/zapr",
]
[[constraint]]

View File

@ -22,15 +22,12 @@ package test
import (
"bytes"
"flag"
"fmt"
"os"
"os/user"
"path"
"sync"
"text/template"
_ "github.com/golang/glog" // Needed if glog and klog are to coexist
"k8s.io/klog"
"knative.dev/pkg/test/logging"
)
@ -53,7 +50,6 @@ type EnvironmentFlags struct {
Kubeconfig string // Path to kubeconfig (defaults to ./kube/config)
Namespace string // K8s namespace (blank by default, to be overwritten by test suite)
IngressEndpoint string // Host to use for ingress endpoint
LogVerbose bool // Enable verbose logging
ImageTemplate string // Template to build the image reference (defaults to {{.Repository}}/{{.Name}}:{{.Tag}})
DockerRepo string // Docker repo (defaults to $KO_DOCKER_REPO)
Tag string // Tag for test images
@ -83,9 +79,6 @@ func initializeFlags() *EnvironmentFlags {
flag.StringVar(&f.IngressEndpoint, "ingressendpoint", "", "Provide a static endpoint url to the ingress server used during tests.")
flag.BoolVar(&f.LogVerbose, "logverbose", false,
"Set this flag to true if you would like to see verbose logging.")
flag.StringVar(&f.ImageTemplate, "imagetemplate", "{{.Repository}}/{{.Name}}:{{.Tag}}",
"Provide a template to generate the reference to an image from the test. Defaults to `{{.Repository}}/{{.Name}}:{{.Tag}}`.")
@ -95,45 +88,12 @@ func initializeFlags() *EnvironmentFlags {
flag.StringVar(&f.Tag, "tag", "latest", "Provide the version tag for the test images.")
klog.InitFlags(klogFlags)
flag.Set("v", klogDefaultLogLevel)
flag.Set("alsologtostderr", "true")
return &f
}
func printFlags() {
fmt.Print("Test Flags: {")
flag.CommandLine.VisitAll(func(f *flag.Flag) {
fmt.Printf("'%s': '%s', ", f.Name, f.Value.String())
})
fmt.Println("}")
}
// SetupLoggingFlags initializes the logging libraries at runtime
// TODO(coryrc): Remove once other repos are moved to call logging.InitializeLogger() directly
func SetupLoggingFlags() {
flagsSetupOnce.Do(func() {
// Sync the glog flags to klog
flag.CommandLine.VisitAll(func(f1 *flag.Flag) {
f2 := klogFlags.Lookup(f1.Name)
if f2 != nil {
value := f1.Value.String()
f2.Value.Set(value)
}
})
if Flags.LogVerbose {
// If klog verbosity is not set to a non-default value (via "-args -v=X"),
if flag.CommandLine.Lookup("v").Value.String() == klogDefaultLogLevel {
// set up verbosity for klog so round_trippers.go prints:
// URL, request headers, response headers, and partial response body
// See levels in vendor/k8s.io/client-go/transport/round_trippers.go:DebugWrappers for other options
klogFlags.Set("v", "8")
flag.Set("v", "8") // This is for glog, since glog=>klog sync is one-time
}
printFlags()
}
logging.InitializeLogger(Flags.LogVerbose)
})
logging.InitializeLogger()
}
// ImagePath is a helper function to transform an image name into an image reference that can be pulled.

View File

@ -1,88 +0,0 @@
/*
Copyright 2019 The Knative Authors
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,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package test
import (
"flag"
"sync"
"testing"
)
func TestE2eFlags(t *testing.T) {
v := flag.Lookup("v")
if v == nil {
printFlags()
t.Fatal("Could not find 'v' flag; klog was not init-ed")
}
if v.Value.String() != klogDefaultLogLevel {
t.Fatalf("Either '%s' was passed in for v or v is not being initialized properly. The former is a test limitation, but the latter is an actual problem", v.Value.String())
}
flagsAreUninitialized := false
flagsSetupOnce.Do(func() {
flagsAreUninitialized = true
})
if !flagsAreUninitialized {
t.Error("SetupLoggingFlags should not have been called at package initialization stage")
}
flagTests := []struct {
testCase string
logVerbose bool
nonDefaultV string
expectedV string
}{
{
testCase: "Check default case with logverbose off",
logVerbose: false,
nonDefaultV: "",
expectedV: klogDefaultLogLevel,
},
{
testCase: "Check default case with logverbose on",
logVerbose: true,
nonDefaultV: "",
expectedV: "8",
},
{
testCase: "Check default case with logverbose on and v set to non-default value",
logVerbose: true,
nonDefaultV: "5",
expectedV: "5",
},
}
alsologtostderr := flag.Lookup("alsologtostderr").Value.String()
if "true" != alsologtostderr {
t.Errorf("alsologtostderr = '%s', want: 'true'\n", alsologtostderr)
}
for _, tc := range flagTests {
t.Run(tc.testCase, func(t *testing.T) {
flagsSetupOnce = &sync.Once{}
Flags.LogVerbose = tc.logVerbose
if tc.nonDefaultV != "" {
flag.Set("v", tc.nonDefaultV)
}
SetupLoggingFlags()
v := klogFlags.Lookup("v").Value.String()
if tc.expectedV != v {
t.Errorf("v = '%s', want: '%s'\n", v, tc.expectedV)
}
})
}
}

1
test/logging/.gitattributes vendored Normal file
View File

@ -0,0 +1 @@
memory_encoder.go coverage-excluded=true

49
test/logging/doc.go Normal file
View File

@ -0,0 +1,49 @@
/*
Copyright 2020 The Knative Authors
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,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Package logging assists setting up test logging and using leveled logging in tests.
The TLogger is designed to assist the test writer in creating more useful tests and
collecting log data in multiple streams, optimizing for human readability in one and
machine readability in another. It's designed to mimic the testing.T object rather closely and
use Zap logging semantics, both things already in use in Knative, to minimize the time developers
need to spend learning the tool.
Inspired by and uses go-logr.
Advantages
The TLogger enhances test design through subtle nudges and affordances:
* It encourages only logging with .V(), giving the writer a nudge to think about how important it is,
but without requiring them to fit it in a narrowly-defined category.
* Reduces boilerplate of carrying around context for errors in several different variables,
using .WithValues(), which results in more consistent and reusable code across the tests.
Porting
To port code from using testing.T to logging.TLogger, the interfaces knative.dev/pkg/test.T and
knative.dev/pkg/test.TLegacy have been created. All library functions should be refactored to use
one interface and all .Log() calls rewritten to use structured format, which works with testing and
TLogger. If a library function needs test functions not available even in test.TLegacy,
it's probably badly written.
Then any test can be incrementally rewritten to use TLogger, as it coexists with testing.T without issue.
*/
package logging

91
test/logging/error.go Normal file
View File

@ -0,0 +1,91 @@
/*
Copyright 2020 The Knative Authors
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,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package logging
import (
"fmt"
"github.com/davecgh/go-spew/spew"
)
// StructuredError is an error which can hold arbitrary key-value arguments.
//
// TODO(coryrc): The Structured Error is experimental and likely to be removed, but is currently in use in a refactored test.
type StructuredError interface {
error
GetValues() []interface{}
WithValues(...interface{}) StructuredError
DisableValuePrinting()
EnableValuePrinting()
}
type structuredError struct {
msg string
keysAndValues []interface{}
print bool
}
func keysAndValuesToSpewedMap(args ...interface{}) map[string]string {
m := make(map[string]string, len(args)/2)
for i := 0; i < len(args); i += 2 {
key, val := args[i], args[i+1]
if keyStr, ok := key.(string); ok {
m[keyStr] = spew.Sdump(val)
}
}
return m
}
// Implement `error` interface
func (e structuredError) Error() string {
// TODO(coryrc): accept zap.Field entries?
if e.print {
// %v for fmt.Sprintf does print keys sorted
return fmt.Sprintf("Error: %s\nContext:\n%v", e.msg, keysAndValuesToSpewedMap(e.keysAndValues...))
} else {
return e.msg
}
}
// GetValues gives you the structured key values in a plist
func (e structuredError) GetValues() []interface{} {
return e.keysAndValues
}
// DisableValuePrinting disables printing out the keys and values from the Error() method
func (e *structuredError) DisableValuePrinting() {
e.print = false
}
// EnableValuePrinting enables printing out the keys and values from the Error() method
func (e *structuredError) EnableValuePrinting() {
e.print = true
}
// Create a StructuredError. Gives a little better logging when given to a TLogger.
// This may prove to not be useful if users use the logger's WithValues() better.
func Error(msg string, keysAndValues ...interface{}) *structuredError {
return &structuredError{msg, keysAndValues, true}
}
// WithValues operates just like TLogger's WithValues but stores them in the error object.
func (e *structuredError) WithValues(keysAndValues ...interface{}) StructuredError {
newKAV := make([]interface{}, 0, len(keysAndValues)+len(e.keysAndValues))
newKAV = append(newKAV, e.keysAndValues...)
newKAV = append(newKAV, keysAndValues...)
return &structuredError{e.msg, newKAV, e.print}
}

View File

@ -0,0 +1,70 @@
/*
Copyright 2020 The Knative Authors
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,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package logging_test
import (
"testing"
"knative.dev/pkg/test/logging"
)
type testStruct struct {
D string
e float64
}
var (
someStruct testStruct
couldBeErr error
)
func init() { someStruct = testStruct{"hello", 42.0} }
// godoc limitation; this would be named Test*(), of course
func Example(legacy *testing.T) {
// Get our TLogger and ready the cleanup function
t, cancel := logging.NewTLogger(legacy)
defer cancel()
// For the most part, you can pretend t is really a *testing.T
// But you get better results by treating it as a leveled logger
// with the same semantics as Infow() in Zap (keys & values alternating after the main argument).
// Logging is leveled from 0-10; see https://github.com/go-logr/logr#how-do-i-choose-my-v-levels
// In our tests currently, levels are sort-of used as follows:
// 1: Describe broadly what the test is doing
// 2: What specific action is occurring
// 5: Trace level; print everything you could predict could be useful in diagnosing stubborn failures
// 8: Just print anything leftover
// Levels 5-9 also instruct the Kubernetes client library to print increasing amounts of data around control plane requests.
t.V(1).Info("We're just presenting some log statements")
t.V(2).Info("Don't forget about this struct", "SomeStruct", someStruct)
t.V(5).Info("We just did a couple little steps, going to try something else")
t.V(8).Info("What else is left?", "LifeTheUniverseAndEverything", 42, "Really anything", t)
// Please use t.V(x).Info and avoid t.Logf to get structured logging
// You get easier-to-read logs too!
// When checking an error and you want to fail the test,
// use one of the following:
t.ErrorIfErr(couldBeErr, "Message about error", "key1", "value1", "key2", "value2", "keyYouGetTheIdea", 0)
t.FatalIfErr(couldBeErr, "Message about why the test will now abort")
// If failing the test, but you don't have an error object:
t.Error("Message about failure", "keysAnd", "Values")
t.Fatal("Message why failing now", "SupportKeysAndValues", true)
}

76
test/logging/logger.go Normal file
View File

@ -0,0 +1,76 @@
// Copyright 2020 The Knative Authors
// Copyright (c) 2017 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.
// Copying testingWriter from zaptest and allowing it to be disabled
package logging
import (
"bytes"
"errors"
"testing"
)
// testingWriter is a WriteSyncer that writes to the given testing.TB.
type testingWriter struct {
t *testing.T
// If true, the test will be marked as failed if this testingWriter is
// ever used.
markFailed bool
}
func newTestingWriter(t *testing.T) testingWriter {
return testingWriter{t: t}
}
// WithMarkFailed returns a copy of this testingWriter with markFailed set to
// the provided value.
func (w testingWriter) WithMarkFailed(v bool) testingWriter {
w.markFailed = v
return w
}
func (w testingWriter) Write(p []byte) (n int, err error) {
if w.t == nil {
return 0, errors.New("Write to buffer after test function completed")
}
n = len(p)
// Strip trailing newline because t.Log always adds one.
p = bytes.TrimRight(p, "\n")
// Note: t.Log is safe for concurrent use.
w.t.Logf("%s", p)
if w.markFailed {
w.t.Fail()
}
return n, nil
}
func (w testingWriter) Sync() error {
return nil
}
func (w *testingWriter) Disable() {
w.t = nil
}

View File

@ -21,15 +21,17 @@ package logging
import (
"context"
"fmt"
"flag"
"os"
"strings"
"sync"
"time"
"github.com/davecgh/go-spew/spew"
"go.opencensus.io/stats/view"
"go.opencensus.io/trace"
"go.uber.org/zap"
"knative.dev/pkg/logging"
"go.uber.org/zap/zapcore"
)
const (
@ -44,8 +46,6 @@ const (
// FormatLogger is a printf style function for logging in tests.
type FormatLogger func(template string, args ...interface{})
var logger *zap.SugaredLogger
var exporter *zapMetricExporter
// zapMetricExporter is a stats and trace exporter that logs the
@ -80,29 +80,22 @@ func (e *zapMetricExporter) ExportSpan(vd *trace.SpanData) {
}
}
func newLogger(logLevel string) *zap.SugaredLogger {
configJSONTemplate := `{
"level": "%s",
"encoding": "console",
"outputPaths": ["stdout"],
"errorOutputPaths": ["stderr"],
"encoderConfig": {
"timeKey": "ts",
"messageKey": "message",
"levelKey": "level",
"nameKey": "logger",
"callerKey": "caller",
"messageKey": "msg",
"stacktraceKey": "stacktrace",
"lineEnding": "",
"levelEncoder": "",
"timeEncoder": "iso8601",
"durationEncoder": "",
"callerEncoder": ""
}
}`
configJSON := fmt.Sprintf(configJSONTemplate, logLevel)
l, _ := logging.NewLogger(string(configJSON), logLevel, zap.AddCallerSkip(1))
const (
logrZapDebugLevel = 3
)
func zapLevelFromLogrLevel(logrLevel int) zapcore.Level {
// Zap levels are -1, 0, 1, 2,... corresponding to DebugLevel, InfoLevel, WarnLevel, ErrorLevel,...
// zapr library just does zapLevel := -1*logrLevel; which means:
// 1. Info level is only active at 0 (versus 2 in klog being generally equivalent to Info)
// 2. Only verbosity of 0 and 1 map to valid Zap levels
// According to https://github.com/uber-go/zap/issues/713 custom levels (i.e. < -1) aren't guaranteed to work, so not using them (for now).
l := zap.InfoLevel
if logrLevel >= logrZapDebugLevel {
l = zap.DebugLevel
}
return l
}
@ -115,9 +108,9 @@ func InitializeMetricExporter(context string) {
trace.UnregisterExporter(exporter)
}
logger := logger.Named(context)
l := logger.Named(context).Sugar()
exporter = &zapMetricExporter{logger: logger}
exporter = &zapMetricExporter{logger: l}
view.RegisterExporter(exporter)
trace.RegisterExporter(exporter)
@ -125,12 +118,54 @@ func InitializeMetricExporter(context string) {
trace.ApplyConfig(trace.Config{DefaultSampler: trace.AlwaysSample()})
}
// InitializeLogger initializes the base logger
func InitializeLogger(logVerbose bool) {
logLevel := "info"
if logVerbose {
logLevel = "debug"
}
logger = newLogger(logLevel)
func printFlags() {
flagList := make([]interface{}, 0)
flag.CommandLine.VisitAll(func(f *flag.Flag) {
flagList = append(flagList, f.Name, f.Value.String())
})
logger.Sugar().Debugw("Test Flags", flagList...)
}
var (
zapCore zapcore.Core
logger *zap.Logger
verbosity int // Amount of log verbosity
loggerInitializeOnce = &sync.Once{}
)
// InitializeLogger initializes logging for Knative tests.
// It should be called prior to executing tests but after command-line flags have been processed.
// Recommend doing it in a TestMain().
func InitializeLogger() {
loggerInitializeOnce.Do(func() {
humanEncoder := zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig())
// Output streams
// TODO(coryrc): also open a log file if in Prow?
stdOut := zapcore.Lock(os.Stdout)
// Level function helper
zapLevel := zapLevelFromLogrLevel(verbosity)
isPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl >= zapLevel
})
// Assemble the output streams
zapCore = zapcore.NewTee(
// TODO(coryrc): log JSON output somewhere?
zapcore.NewCore(humanEncoder, stdOut, isPriority),
)
logger = zap.New(zapCore)
zap.ReplaceGlobals(logger) // Gets used by klog/glog proxy libraries
if verbosity > 2 {
printFlags()
}
})
}
func init() {
flag.IntVar(&verbosity, "verbosity", 2,
"Amount of verbosity, 0-10. See https://github.com/go-logr/logr#how-do-i-choose-my-v-levels and https://github.com/kubernetes/community/blob/master/contributors/devel/sig-instrumentation/logging.md")
}

View File

@ -0,0 +1,163 @@
/*
Copyright 2020 The Knative Authors
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,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package logging
import (
"errors"
"reflect"
"testing"
)
type abcf struct {
A int
b string
C *de
F func()
}
type de struct {
D string
e float64
}
var someStruct abcf
func init() {
someStruct = abcf{
A: 42,
b: "some string",
C: &de{
D: "hello world",
e: 72.3,
},
F: InitializeLogger,
}
}
func TestTLogger(legacy *testing.T) {
verbosity = 5
InitializeLogger()
t, cancel := NewTLogger(legacy)
defer cancel()
var blank interface{}
blank = &someStruct
t.V(6).Info("Should not be printed")
t.V(4).Info("Should be printed!")
t.Run("A-Nice-Subtest", func(ts *TLogger) {
ts.V(0).Info("This is pretty important; everyone needs to see it!",
"some pointer", blank,
"some number", 42.0)
t.Run("A-Nested-Subtest", func(ts *TLogger) {
ts.Parallel()
ts.V(1).Info("I am visible!")
ts.V(6).Info("I am invisible!")
t.Collect("collected_non_error", "I'm not an error!")
})
t.Run("A-2nd-Nested-Subtest", func(ts *TLogger) {
ts.Parallel()
ts.V(1).Info("I am visible!")
ts.V(6).Info("I am also invisible!")
})
})
t.Run("Skipped", func(ts *TLogger) {
ts.SkipNow()
})
t.ErrorIfErr(nil, "I won't fail because no error!")
t.FatalIfErr(nil, "I won't fail because no error!")
t = t.WithName("LongerName")
t = t.WithValues("persistentKey", "persistentValue")
t.Logf("Sadly still have to support %s", "LogF")
}
func TestTLoggerFailing(legacy *testing.T) {
t, cancel := NewTLogger(legacy)
defer cancel()
t.dontFail = true
t.Run("Failing1", func(ts *TLogger) {
t.V(0).Info("dontFail values", "t", t.dontFail, "ts", ts.dontFail)
t.Collect("collected_error", errors.New("collected"))
ts.Error("I am an error", "hello", "world")
})
t.Run("Failing2", func(ts *TLogger) {
ts.Fatal("I am a fatal error", "hello", "world")
})
}
type errorWithRuntimeCheckValues struct {
testName string
inputs []interface{}
expectedError error
expectedString string
expectedInterfaces []interface{}
}
func TestTLoggerInternals(legacy *testing.T) {
verbosity = 2
InitializeLogger()
t, cancel := NewTLogger(legacy)
defer cancel()
tests := []errorWithRuntimeCheckValues{
{"empty", nil, nil, "", nil},
{"string with valid single key-value pair", []interface{}{"greetings!", "hello", "world"}, nil, "greetings!", []interface{}{"hello", "world"}},
{"junk inputs", []interface{}{42}, nil, "unstructured error", t.interfacesToFields(42)},
}
for _, tt := range tests {
t.Run("errorWithRuntimeCheck "+tt.testName, func(t *TLogger) {
e, s, i := t.errorWithRuntimeCheck(tt.inputs...)
if e != tt.expectedError {
t.Error("error did not match", "got", e, "want", tt.expectedError)
}
if s != tt.expectedString {
t.Error("string did not match", "got", s, "want", tt.expectedString)
}
if !reflect.DeepEqual(i, tt.expectedInterfaces) {
t.Error("interfaces did not match", "got", i, "want", tt.expectedInterfaces)
}
})
}
if validateKeysAndValues(42, "whoops not string key before") {
t.Error("Should not have accepted non-string key")
}
if !validateKeysAndValues("we like string keys", "any value is fine") {
t.Error("Should have accepted string key")
}
input := []interface{}{4, 5, 6}
things := t.interfacesToFields(input...)
expected := []interface{}{"arg 0", 4, "arg 1", 5, "arg 2", 6}
if !reflect.DeepEqual(things, expected) {
t.Error("interfacesToFields() didn't give expected output", "input", input, "want", expected, "got", things)
}
t.Helper() // Doesn't do anything
}
func TestStructuredError(legacy *testing.T) {
verbosity = 5
InitializeLogger()
t, cancel := NewTLogger(legacy)
defer cancel()
err := Error("Hello World", "key", "value", "current function", TestStructuredError, "deep struct", someStruct, "z", 4, "y", 3, "x", 2, "w", 1)
t.Log(err.Error())
}

View File

@ -0,0 +1,74 @@
// Copyright 2020 The Knative Authors
// 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 logging
import (
"time"
"go.uber.org/zap/zapcore"
)
// sliceArrayEncoder is an ArrayEncoder backed by a simple []interface{}. Like
// the MapObjectEncoder, it's not designed for production use.
type sliceArrayEncoder struct {
elems []interface{}
}
func (s *sliceArrayEncoder) AppendArray(v zapcore.ArrayMarshaler) error {
enc := &sliceArrayEncoder{}
err := v.MarshalLogArray(enc)
s.elems = append(s.elems, enc.elems)
return err
}
func (s *sliceArrayEncoder) AppendObject(v zapcore.ObjectMarshaler) error {
m := zapcore.NewMapObjectEncoder()
err := v.MarshalLogObject(m)
s.elems = append(s.elems, m.Fields)
return err
}
func (s *sliceArrayEncoder) AppendReflected(v interface{}) error {
s.elems = append(s.elems, v)
return nil
}
func (s *sliceArrayEncoder) AppendBool(v bool) { s.elems = append(s.elems, v) }
func (s *sliceArrayEncoder) AppendByteString(v []byte) { s.elems = append(s.elems, v) }
func (s *sliceArrayEncoder) AppendComplex128(v complex128) { s.elems = append(s.elems, v) }
func (s *sliceArrayEncoder) AppendComplex64(v complex64) { s.elems = append(s.elems, v) }
func (s *sliceArrayEncoder) AppendDuration(v time.Duration) { s.elems = append(s.elems, v) }
func (s *sliceArrayEncoder) AppendFloat64(v float64) { s.elems = append(s.elems, v) }
func (s *sliceArrayEncoder) AppendFloat32(v float32) { s.elems = append(s.elems, v) }
func (s *sliceArrayEncoder) AppendInt(v int) { s.elems = append(s.elems, v) }
func (s *sliceArrayEncoder) AppendInt64(v int64) { s.elems = append(s.elems, v) }
func (s *sliceArrayEncoder) AppendInt32(v int32) { s.elems = append(s.elems, v) }
func (s *sliceArrayEncoder) AppendInt16(v int16) { s.elems = append(s.elems, v) }
func (s *sliceArrayEncoder) AppendInt8(v int8) { s.elems = append(s.elems, v) }
func (s *sliceArrayEncoder) AppendString(v string) { s.elems = append(s.elems, v) }
func (s *sliceArrayEncoder) AppendTime(v time.Time) { s.elems = append(s.elems, v) }
func (s *sliceArrayEncoder) AppendUint(v uint) { s.elems = append(s.elems, v) }
func (s *sliceArrayEncoder) AppendUint64(v uint64) { s.elems = append(s.elems, v) }
func (s *sliceArrayEncoder) AppendUint32(v uint32) { s.elems = append(s.elems, v) }
func (s *sliceArrayEncoder) AppendUint16(v uint16) { s.elems = append(s.elems, v) }
func (s *sliceArrayEncoder) AppendUint8(v uint8) { s.elems = append(s.elems, v) }
func (s *sliceArrayEncoder) AppendUintptr(v uintptr) { s.elems = append(s.elems, v) }

View File

@ -0,0 +1,196 @@
// Copyright 2020 The Knative Authors
// 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 logging
import (
"fmt"
"sort"
"strings"
"sync"
"go.uber.org/zap"
"go.uber.org/zap/buffer"
. "go.uber.org/zap/zapcore"
)
var (
_pool = buffer.NewPool()
_sliceEncoderPool = sync.Pool{
New: func() interface{} {
return &sliceArrayEncoder{elems: make([]interface{}, 0, 2)}
},
}
)
func init() {
zap.RegisterEncoder("spew", func(encoderConfig EncoderConfig) (Encoder, error) {
return NewSpewEncoder(encoderConfig), nil
})
}
// NewSpewEncoder encodes logs using the spew library.
//
// The JSON encoder (also used by the console encoder) included in Zap can only print objects that
// can be serialized to JSON and doesn't print them in the most readable way. This spew encoder is
// designed to make human-readable log only and get the most information to the user on any data type.
//
// Code is mostly from console_encoder.go in zapcore.
func NewSpewEncoder(cfg EncoderConfig) *SpewEncoder {
enc := SpewEncoder{}
enc.MapObjectEncoder = NewMapObjectEncoder()
enc.EncoderConfig = &cfg
return &enc
}
// SpewEncoder implements zapcore.Encoder interface
type SpewEncoder struct {
*MapObjectEncoder
*EncoderConfig
}
// Implements zapcore.Encoder interface
func (enc *SpewEncoder) Clone() Encoder {
n := NewSpewEncoder(*(enc.EncoderConfig))
for k, v := range enc.Fields {
n.Fields[k] = v
}
return n
}
func getSliceEncoder() *sliceArrayEncoder {
return _sliceEncoderPool.Get().(*sliceArrayEncoder)
}
func putSliceEncoder(e *sliceArrayEncoder) {
e.elems = e.elems[:0]
_sliceEncoderPool.Put(e)
}
// Implements zapcore.Encoder interface.
func (enc *SpewEncoder) EncodeEntry(ent Entry, fields []Field) (*buffer.Buffer, error) {
line := _pool.Get()
// Could probably rewrite this portion and remove the copied
// memory_encoder.go from this folder
arr := getSliceEncoder()
defer putSliceEncoder(arr)
if enc.TimeKey != "" && enc.EncodeTime != nil {
enc.EncodeTime(ent.Time, arr)
}
if enc.LevelKey != "" && enc.EncodeLevel != nil {
enc.EncodeLevel(ent.Level, arr)
}
if ent.LoggerName != "" && enc.NameKey != "" {
nameEncoder := enc.EncodeName
if nameEncoder == nil {
// Fall back to FullNameEncoder for backward compatibility.
nameEncoder = FullNameEncoder
}
nameEncoder(ent.LoggerName, arr)
}
if ent.Caller.Defined && enc.CallerKey != "" && enc.EncodeCaller != nil {
enc.EncodeCaller(ent.Caller, arr)
}
for i := range arr.elems {
if i > 0 {
line.AppendByte('\t')
}
fmt.Fprint(line, arr.elems[i])
}
// Add the message itself.
if enc.MessageKey != "" {
enc.addTabIfNecessary(line)
line.AppendString(ent.Message)
}
// Add any structured context.
enc.writeContext(line, fields)
// If there's no stacktrace key, honor that; this allows users to force
// single-line output.
if ent.Stack != "" && enc.StacktraceKey != "" {
line.AppendByte('\n')
line.AppendString(ent.Stack)
}
if enc.LineEnding != "" {
line.AppendString(enc.LineEnding)
} else {
line.AppendString(DefaultLineEnding)
}
return line, nil
}
func (enc *SpewEncoder) writeContext(line *buffer.Buffer, extra []Field) {
if len(extra) == 0 && len(enc.Fields) == 0 {
return
}
// This could probably be more efficient, but .AddTo() is convenient
context := NewMapObjectEncoder()
for k, v := range enc.Fields {
context.Fields[k] = v
}
for i := range extra {
extra[i].AddTo(context)
}
enc.addTabIfNecessary(line)
line.AppendString("\nContext:\n")
var keys []string
for k := range context.Fields {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
line.AppendString(k)
line.AppendString(": ")
line.AppendString(stringify(context.Fields[k]))
line.TrimNewline()
line.AppendString("\n")
}
}
func stringify(a interface{}) string {
s, ok := a.(string)
if !ok {
s = strings.TrimSuffix(spewConfig.Sdump(a), "\n")
}
ret := strings.ReplaceAll(s, "\n", "\n ")
hasNewlines := s != ret
if hasNewlines {
return "\n " + ret
}
return s
}
func (enc *SpewEncoder) addTabIfNecessary(line *buffer.Buffer) {
if line.Len() > 0 {
line.AppendByte('\t')
}
}

View File

@ -0,0 +1,33 @@
/*
Copyright 2020 The Knative Authors
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,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package logging
import (
"os"
"testing"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
func TestSpewEncoder(t *testing.T) {
enc := NewSpewEncoder(zap.NewDevelopmentEncoderConfig())
stdOut := zapcore.Lock(os.Stdout)
core := zapcore.NewCore(enc, stdOut, zapcore.InfoLevel)
logger := zap.New(core, zap.AddCaller(), zap.Development())
logger.Sugar().Infow("Message", "someStruct", someStruct, zap.Stack("thestack"), "zlast", "a string", "afirst", 25.8)
}

117
test/logging/sugar.go Normal file
View File

@ -0,0 +1,117 @@
// Copyright 2020 Knative Authors
// 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 logging
import (
"github.com/davecgh/go-spew/spew"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"go.uber.org/multierr"
)
const (
_oddNumberErrMsg = "Ignored key without a value."
_nonStringKeyErrMsg = "Ignored key-value pairs with non-string keys."
spewLevel1 = 2
spewLevel2 = 4
spewLevel3 = 6
)
var spewConfig *spew.ConfigState
func init() {
spewConfig = spew.NewDefaultConfig()
spewConfig.DisableCapacities = true
spewConfig.SortKeys = true
spewConfig.SpewKeys = true
spewConfig.ContinueOnMethod = true
}
func (o *TLogger) handleFields(args []interface{}) []zap.Field {
if len(args) == 0 {
return nil
}
s := o.l.Sugar()
// Allocate enough space for the worst case; if users pass only structured
// fields, we shouldn't penalize them with extra allocations.
fields := make([]zap.Field, 0, len(args))
var invalid invalidPairs
for i := 0; i < len(args); {
// This is a strongly-typed field. Consume it and move on.
if f, ok := args[i].(zap.Field); ok {
fields = append(fields, f)
i++
continue
}
// Make sure this element isn't a dangling key.
if i == len(args)-1 {
s.DPanic(_oddNumberErrMsg, zap.Any("ignored", args[i]))
break
}
// Consume this value and the next, treating them as a key-value pair. If the
// key isn't a string, add this pair to the slice of invalid pairs.
key, val := args[i], args[i+1]
if keyStr, ok := key.(string); !ok {
// Subsequent errors are likely, so allocate once up front.
if cap(invalid) == 0 {
invalid = make(invalidPairs, 0, len(args)/2)
}
invalid = append(invalid, invalidPair{i, key, val})
} else {
fields = append(fields, zap.Any(keyStr, val))
}
i += 2
}
// If we encountered any invalid key-value pairs, log an error.
if len(invalid) > 0 {
s.DPanic(_nonStringKeyErrMsg, zap.Array("invalid", invalid), zap.String("all_input", spew.Sprintf("%#+v", args)))
}
return fields
}
type invalidPair struct {
position int
key, value interface{}
}
func (p invalidPair) MarshalLogObject(enc zapcore.ObjectEncoder) error {
enc.AddInt64("position", int64(p.position))
zap.Any("key", p.key).AddTo(enc)
zap.Any("value", p.value).AddTo(enc)
return nil
}
type invalidPairs []invalidPair
func (ps invalidPairs) MarshalLogArray(enc zapcore.ArrayEncoder) error {
var err error
for i := range ps {
err = multierr.Append(err, enc.AppendObject(ps[i]))
}
return err
}

368
test/logging/tlogger.go Normal file
View File

@ -0,0 +1,368 @@
/*
Copyright 2020 The Knative Authors
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,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package logging
import (
"errors"
"fmt"
"testing"
"github.com/go-logr/logr"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// TLogger is TLogger
type TLogger struct {
l *zap.Logger
level int
t *testing.T
errs map[string][]interface{} // For Collect()
dontFail bool
}
// V() returns an InfoLogger from go-logr.
//
// This should be the main way your tests log.
// Most frequent usage is used directly:
// t.V(2).Info("Something at regular level")
// But if something computationally difficult is to be done, can do:
// if l := t.V(8); l.Enabled() {
// x := somethingExpensive()
// l.Info("logging it", "expensiveThing", x)
// }
//
// Elsewhere in this documentation refers to a hypothetical .V(errorLevel) to simplify explanations.
// The V() function cannot write to the error level; the Error, ErrorIfErr, Fatal, and
// FatalIfErr methods are the only way to write to the error level.
func (o *TLogger) V(level int) logr.InfoLogger {
// Consider adding || (level <= logrZapDebugLevel && o.l.Core().Enabled(zapLevelFromLogrLevel(level)))
// Reason to add it is even if you ask for verbosity=1, in case of error you'll get up to verbosity=3 in the debug output
// but since zapTest uses Debug, you always get V(<=3) even when verbosity < 3
// Probable solution is to write to t.Log at Info level?
if level <= o.level {
return &infoLogger{
logrLevel: o.level,
t: o,
}
}
return disabledInfoLogger
}
// WithValues() acts like Zap's With() method.
// Consistent with logr.Logger.WithValues()
// Whenever anything is logged with the returned TLogger,
// it will act as if these keys and values were passed into every logging call.
func (o *TLogger) WithValues(keysAndValues ...interface{}) *TLogger {
return o.cloneWithNewLogger(o.l.With(o.handleFields(keysAndValues)...))
}
// WithName() acts like Zap's Named() method.
// Consistent with logr.Logger.WithName()
// Appends the name onto the current logger
func (o *TLogger) WithName(name string) *TLogger {
return o.cloneWithNewLogger(o.l.Named(name))
}
// Custom additions:
// ErrorIfErr fails the current test if the err != nil.
// Remaining arguments function as if passed to .V(errorLevel).Info() (were that a thing)
// Same signature as logr.Logger.Error() method, but as this is a test, it functions slightly differently.
func (o *TLogger) ErrorIfErr(err error, msg string, keysAndValues ...interface{}) {
if err != nil {
o.error(err, msg, keysAndValues)
o.fail()
}
}
// FatalIfErr is just like ErrorIfErr() but test execution stops immediately
func (o *TLogger) FatalIfErr(err error, msg string, keysAndValues ...interface{}) {
if err != nil {
o.error(err, msg, keysAndValues)
o.failNow()
}
}
// Error is essentially a .V(errorLevel).Info() followed by failing the test.
// Intended usage is Error(msg string, key-value alternating arguments)
// Same effect as testing.T.Error
// Generic definition for compatibility with test.T interface
// Implements test.T
func (o *TLogger) Error(stringThenKeysAndValues ...interface{}) {
// Using o.error to have consistent call depth for Error, FatalIfErr, Info, etc
o.error(o.errorWithRuntimeCheck(stringThenKeysAndValues...))
o.fail()
}
// Fatal is essentially a .V(errorLevel).Info() followed by failing and immediately stopping the test.
// Intended usage is Fatal(msg string, key-value alternating arguments)
// Same effect as testing.T.Fatal
// Generic definition for compatibility with test.TLegacy interface
// Implements test.TLegacy
func (o *TLogger) Fatal(stringThenKeysAndValues ...interface{}) {
o.error(o.errorWithRuntimeCheck(stringThenKeysAndValues...))
o.failNow()
}
func (o *TLogger) fail() {
if o.t != nil && !o.dontFail {
o.t.Fail()
}
}
func (o *TLogger) failNow() {
if o.t != nil && !o.dontFail {
o.t.FailNow()
}
}
func validateKeysAndValues(keysAndValues ...interface{}) bool {
length := len(keysAndValues)
for i := 0; i < length; {
_, isField := keysAndValues[i].(zapcore.Field)
_, isString := keysAndValues[i].(string)
if isField {
i += 1
} else if isString {
if i == length-1 {
return false
}
i += 2
} else {
return false
}
}
return true
}
func (o *TLogger) interfacesToFields(things ...interface{}) []interface{} {
o.V(5).Info("DEPRECATED Error/Fatal usage", zap.Stack("callstack"))
fields := make([]interface{}, 2*len(things))
for i, d := range things {
fields[i*2] = fmt.Sprintf("arg %d", i)
fields[i*2+1] = d
}
return fields
}
func (o *TLogger) errorWithRuntimeCheck(stringThenKeysAndValues ...interface{}) (error, string, []interface{}) {
if len(stringThenKeysAndValues) == 0 {
return nil, "", nil
} else {
s, isString := stringThenKeysAndValues[0].(string)
e, isError := stringThenKeysAndValues[0].(error)
if isString {
// Desired case (hopefully)
remainder := stringThenKeysAndValues[1:]
if !validateKeysAndValues(remainder...) {
remainder = o.interfacesToFields(remainder...)
}
return nil, s, remainder
} else if isError && len(stringThenKeysAndValues) == 1 {
return e, "", nil
} else {
return nil, "unstructured error", o.interfacesToFields(stringThenKeysAndValues...)
}
}
}
// Run a subtest. Just like testing.T.Run but creates a TLogger.
func (o *TLogger) Run(name string, f func(t *TLogger)) {
tfunc := func(ts *testing.T) {
tl, cancel := newTLogger(ts, o.level, o.dontFail)
defer cancel()
f(tl)
}
o.t.Run(name, tfunc)
}
// Name is just like testing.T.Name()
// Implements test.T
func (o *TLogger) Name() string {
return o.t.Name()
}
// Helper cannot work as an indirect call, so just do nothing :(
// Implements test.T
func (o *TLogger) Helper() {
}
// SkipNow immediately stops test execution
// Implements test.T
func (o *TLogger) SkipNow() {
o.t.SkipNow()
}
// Log is deprecated: only existing for test.T compatibility
// Please use leveled logging via .V().Info()
// Will panic if given data incompatible with Info() function
// Implements test.T
func (o *TLogger) Log(args ...interface{}) {
// This is complicated to ensure exactly 2 levels of indirection
i := o.V(2)
iL, ok := i.(*infoLogger)
if ok {
iL.indirectWrite(args[0].(string), args[1:]...)
}
}
// Parallel allows tests or subtests to run in parallel
// Just calls the testing.T.Parallel() under the hood
func (o *TLogger) Parallel() {
o.t.Parallel()
}
// Logf is deprecated: only existing for test.TLegacy compatibility
// Please use leveled logging via .V().Info()
// Implements test.TLegacy
func (o *TLogger) Logf(fmtS string, args ...interface{}) {
// This is complicated to ensure exactly 2 levels of indirection
iL, ok := o.V(2).(*infoLogger)
if ok {
iL.indirectWrite(fmt.Sprintf(fmtS, args...))
}
}
func (o *TLogger) error(err error, msg string, keysAndValues []interface{}) {
var newKAV []interface{}
var serr StructuredError
if errors.As(err, &serr) {
serr.DisableValuePrinting()
defer serr.EnableValuePrinting()
newLen := len(keysAndValues) + len(serr.GetValues())
newKAV = make([]interface{}, 0, newLen+2)
newKAV = append(newKAV, keysAndValues...)
newKAV = append(newKAV, serr.GetValues()...)
}
if err != nil {
if msg == "" { // This is used if just the error is given to .Error() or .Fatal()
msg = err.Error()
} else {
if newKAV == nil {
newKAV = make([]interface{}, 0, len(keysAndValues)+1)
newKAV = append(newKAV, keysAndValues...)
}
newKAV = append(newKAV, zap.Error(err))
}
}
if newKAV != nil {
keysAndValues = newKAV
}
if checkedEntry := o.l.Check(zap.ErrorLevel, msg); checkedEntry != nil {
checkedEntry.Write(o.handleFields(keysAndValues)...)
}
}
// Creation and Teardown
// Create a TLogger object using the global Zap logger and the current testing.T
// `defer` a call to second return value immediately after.
func NewTLogger(t *testing.T) (*TLogger, func()) {
return newTLogger(t, verbosity, false)
}
func newTLogger(t *testing.T, verbosity int, dontFail bool) (*TLogger, func()) {
testOptions := []zap.Option{
zap.AddCaller(),
zap.AddCallerSkip(2),
zap.Development(),
}
writer := newTestingWriter(t)
// Based off zap.NewDevelopmentEncoderConfig()
cfg := zapcore.EncoderConfig{
// Wanted keys can be anything except the empty string.
TimeKey: "",
LevelKey: "",
NameKey: "",
CallerKey: "C",
MessageKey: "M",
StacktraceKey: "S",
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: zapcore.CapitalLevelEncoder,
EncodeTime: zapcore.ISO8601TimeEncoder,
EncodeDuration: zapcore.StringDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
}
core := zapcore.NewCore(
NewSpewEncoder(cfg),
writer,
zapcore.DebugLevel,
)
if zapCore != nil {
core = zapcore.NewTee(
zapCore,
core,
// TODO(coryrc): Open new file (maybe creating JUnit!?) with test output?
)
}
log := zap.New(core, testOptions...).Named(t.Name())
tlogger := TLogger{
l: log,
level: verbosity,
t: t,
errs: make(map[string][]interface{}, 0),
dontFail: dontFail,
}
return &tlogger, func() {
tlogger.handleCollectedErrors()
// Sometimes goroutines exist after a test and they cause panics if they attempt to call t.Log().
// Prevent this panic by disabling writes to the testing.T (we'll still get them everywhere else).
writer.Disable()
}
}
func (o *TLogger) cloneWithNewLogger(l *zap.Logger) *TLogger {
t := TLogger{
l: l,
level: o.level,
t: o.t,
errs: o.errs,
dontFail: o.dontFail,
}
return &t
}
// Collect allows you to commingle multiple validations during one test execution.
// Under the hood, it creates a sub-test during cleanup and iterates through the collected values, printing them.
// If any are errors, it fails the subtest.
// Currently experimental and likely to be removed
func (o *TLogger) Collect(key string, value interface{}) {
list, has_key := o.errs[key]
if has_key {
list = append(list, value)
} else {
list = make([]interface{}, 1)
list[0] = value
}
o.errs[key] = list
}
func (o *TLogger) handleCollectedErrors() {
for name, list := range o.errs {
o.Run(name, func(t *TLogger) {
for _, item := range list {
_, isError := item.(error)
if isError {
t.Error(item)
} else {
t.V(3).Info(spewConfig.Sprint(item))
}
}
})
}
}

47
test/logging/zapr.go Normal file
View File

@ -0,0 +1,47 @@
// Copyright 2020 Knative Authors
// Copyright 2018 Solly Ross
//
// 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,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// The useful parts of this file have been preserved
// from their origin at https://github.com/go-logr/zapr/tree/8f2487342d52a33a1793e50e3ca04bc1767aa65c
package logging
// noopInfoLogger is a logr.InfoLogger that's always disabled, and does nothing.
type noopInfoLogger struct{}
func (l *noopInfoLogger) Enabled() bool { return false }
func (l *noopInfoLogger) Info(_ string, _ ...interface{}) {}
var disabledInfoLogger = &noopInfoLogger{}
// infoLogger is a logr.InfoLogger that uses Zap to log at a particular
// level.
type infoLogger struct {
logrLevel int
t *TLogger
}
func (i *infoLogger) Enabled() bool { return true }
func (i *infoLogger) Info(msg string, keysAndVals ...interface{}) {
i.indirectWrite(msg, keysAndVals...)
}
// This function just exists to have consistent 2-level call depth for Zap proxying
func (i *infoLogger) indirectWrite(msg string, keysAndVals ...interface{}) {
lvl := zapLevelFromLogrLevel(i.logrLevel)
if checkedEntry := i.t.l.Check(lvl, msg); checkedEntry != nil {
checkedEntry.Write(i.t.handleFields(keysAndVals)...)
}
}

201
vendor/github.com/go-logr/logr/LICENSE generated vendored Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
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,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

151
vendor/github.com/go-logr/logr/logr.go generated vendored Normal file
View File

@ -0,0 +1,151 @@
// Package logr defines abstract interfaces for logging. Packages can depend on
// these interfaces and callers can implement logging in whatever way is
// appropriate.
//
// This design derives from Dave Cheney's blog:
// http://dave.cheney.net/2015/11/05/lets-talk-about-logging
//
// This is a BETA grade API. Until there is a significant 2nd implementation,
// I don't really know how it will change.
//
// The logging specifically makes it non-trivial to use format strings, to encourage
// attaching structured information instead of unstructured format strings.
//
// Usage
//
// Logging is done using a Logger. Loggers can have name prefixes and named values
// attached, so that all log messages logged with that Logger have some base context
// associated.
//
// The term "key" is used to refer to the name associated with a particular value, to
// disambiguate it from the general Logger name.
//
// For instance, suppose we're trying to reconcile the state of an object, and we want
// to log that we've made some decision.
//
// With the traditional log package, we might write
// log.Printf(
// "decided to set field foo to value %q for object %s/%s",
// targetValue, object.Namespace, object.Name)
//
// With logr's structured logging, we'd write
// // elsewhere in the file, set up the logger to log with the prefix of "reconcilers",
// // and the named value target-type=Foo, for extra context.
// log := mainLogger.WithName("reconcilers").WithValues("target-type", "Foo")
//
// // later on...
// log.Info("setting field foo on object", "value", targetValue, "object", object)
//
// Depending on our logging implementation, we could then make logging decisions based on field values
// (like only logging such events for objects in a certain namespace), or copy the structured
// information into a structured log store.
//
// For logging errors, Logger has a method called Error. Suppose we wanted to log an
// error while reconciling. With the traditional log package, we might write
// log.Errorf("unable to reconcile object %s/%s: %v", object.Namespace, object.Name, err)
//
// With logr, we'd instead write
// // assuming the above setup for log
// log.Error(err, "unable to reconcile object", "object", object)
//
// This functions similarly to:
// log.Info("unable to reconcile object", "error", err, "object", object)
//
// However, it ensures that a standard key for the error value ("error") is used across all
// error logging. Furthermore, certain implementations may choose to attach additional
// information (such as stack traces) on calls to Error, so it's preferred to use Error
// to log errors.
//
// Parts of a log line
//
// Each log message from a Logger has four types of context:
// logger name, log verbosity, log message, and the named values.
//
// The Logger name constists of a series of name "segments" added by successive calls to WithName.
// These name segments will be joined in some way by the underlying implementation. It is strongly
// reccomended that name segements contain simple identifiers (letters, digits, and hyphen), and do
// not contain characters that could muddle the log output or confuse the joining operation (e.g.
// whitespace, commas, periods, slashes, brackets, quotes, etc).
//
// Log verbosity represents how little a log matters. Level zero, the default, matters most.
// Increasing levels matter less and less. Try to avoid lots of different verbosity levels,
// and instead provide useful keys, logger names, and log messages for users to filter on.
// It's illegal to pass a log level below zero.
//
// The log message consists of a constant message attached to the the log line. This
// should generally be a simple description of what's occuring, and should never be a format string.
//
// Variable information can then be attached using named values (key/value pairs). Keys are arbitrary
// strings, while values may be any Go value.
//
// Key Naming Conventions
//
// While users are generally free to use key names of their choice, it's generally best to avoid
// using the following keys, as they're frequently used by implementations:
//
// - `"error"`: the underlying error value in the `Error` method.
// - `"stacktrace"`: the stack trace associated with a particular log line or error
// (often from the `Error` message).
// - `"caller"`: the calling information (file/line) of a particular log line.
// - `"msg"`: the log message.
// - `"level"`: the log level.
// - `"ts"`: the timestamp for a log line.
//
// Implementations are encouraged to make use of these keys to represent the above
// concepts, when neccessary (for example, in a pure-JSON output form, it would be
// necessary to represent at least message and timestamp as ordinary named values).
package logr
// TODO: consider adding back in format strings if they're really needed
// TODO: consider other bits of zap/zapcore functionality like ObjectMarshaller (for arbitrary objects)
// TODO: consider other bits of glog functionality like Flush, InfoDepth, OutputStats
// InfoLogger represents the ability to log non-error messages, at a particular verbosity.
type InfoLogger interface {
// Info logs a non-error message with the given key/value pairs as context.
//
// The msg argument should be used to add some constant description to
// the log line. The key/value pairs can then be used to add additional
// variable information. The key/value pairs should alternate string
// keys and arbitrary values.
Info(msg string, keysAndValues ...interface{})
// Enabled tests whether this InfoLogger is enabled. For example,
// commandline flags might be used to set the logging verbosity and disable
// some info logs.
Enabled() bool
}
// Logger represents the ability to log messages, both errors and not.
type Logger interface {
// All Loggers implement InfoLogger. Calling InfoLogger methods directly on
// a Logger value is equivalent to calling them on a V(0) InfoLogger. For
// example, logger.Info() produces the same result as logger.V(0).Info.
InfoLogger
// Error logs an error, with the given message and key/value pairs as context.
// It functions similarly to calling Info with the "error" named value, but may
// have unique behavior, and should be preferred for logging errors (see the
// package documentations for more information).
//
// The msg field should be used to add context to any underlying error,
// while the err field should be used to attach the actual error that
// triggered this log line, if present.
Error(err error, msg string, keysAndValues ...interface{})
// V returns an InfoLogger value for a specific verbosity level. A higher
// verbosity level means a log message is less important. It's illegal to
// pass a log level less than zero.
V(level int) InfoLogger
// WithValues adds some key-value pairs of context to a logger.
// See Info for documentation on how key/value pairs work.
WithValues(keysAndValues ...interface{}) Logger
// WithName adds a new element to the logger's name.
// Successive calls with WithName continue to append
// suffixes to the logger's name. It's strongly reccomended
// that name segments contain only letters, digits, and hyphens
// (see the package documentation for more information).
WithName(name string) Logger
}

201
vendor/github.com/go-logr/zapr/LICENSE generated vendored Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
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,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

163
vendor/github.com/go-logr/zapr/zapr.go generated vendored Normal file
View File

@ -0,0 +1,163 @@
// Copyright 2018 Solly Ross
//
// 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,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// package zapr defines an implementation of the github.com/go-logr/logr
// interfaces built on top of Zap (go.uber.org/zap).
//
// Usage
//
// A new logr.Logger can be constructed from an existing zap.Logger using
// the NewLogger function:
//
// log := zapr.NewLogger(someZapLogger)
//
// Implementation Details
//
// For the most part, concepts in Zap correspond directly with those in
// logr.
//
// Unlike Zap, all fields *must* be in the form of suggared fields --
// it's illegal to pass a strongly-typed Zap field in a key position
// to any of the log methods.
//
// Levels in logr correspond to custom debug levels in Zap. Any given level
// in logr is represents by its inverse in zap (`zapLevel = -1*logrLevel`).
// For example V(2) is equivalent to log level -2 in Zap, while V(1) is
// equivalent to Zap's DebugLevel.
package zapr
import (
"github.com/go-logr/logr"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// noopInfoLogger is a logr.InfoLogger that's always disabled, and does nothing.
type noopInfoLogger struct{}
func (l *noopInfoLogger) Enabled() bool { return false }
func (l *noopInfoLogger) Info(_ string, _ ...interface{}) {}
var disabledInfoLogger = &noopInfoLogger{}
// NB: right now, we always use the equivalent of sugared logging.
// This is necessary, since logr doesn't define non-suggared types,
// and using zap-specific non-suggared types would make uses tied
// directly to Zap.
// infoLogger is a logr.InfoLogger that uses Zap to log at a particular
// level. The level has already been converted to a Zap level, which
// is to say that `logrLevel = -1*zapLevel`.
type infoLogger struct {
lvl zapcore.Level
l *zap.Logger
}
func (l *infoLogger) Enabled() bool { return true }
func (l *infoLogger) Info(msg string, keysAndVals ...interface{}) {
if checkedEntry := l.l.Check(l.lvl, msg); checkedEntry != nil {
checkedEntry.Write(handleFields(l.l, keysAndVals)...)
}
}
// zapLogger is a logr.Logger that uses Zap to log.
type zapLogger struct {
// NB: this looks very similar to zap.SugaredLogger, but
// deals with our desire to have multiple verbosity levels.
l *zap.Logger
infoLogger
}
// handleFields converts a bunch of arbitrary key-value pairs into Zap fields. It takes
// additional pre-converted Zap fields, for use with automatically attached fields, like
// `error`.
func handleFields(l *zap.Logger, args []interface{}, additional ...zap.Field) []zap.Field {
// a slightly modified version of zap.SugaredLogger.sweetenFields
if len(args) == 0 {
// fast-return if we have no suggared fields.
return additional
}
// unlike Zap, we can be pretty sure users aren't passing structured
// fields (since logr has no concept of that), so guess that we need a
// little less space.
fields := make([]zap.Field, 0, len(args)/2+len(additional))
for i := 0; i < len(args); {
// check just in case for strongly-typed Zap fields, which is illegal (since
// it breaks implementation agnosticism), so we can give a better error message.
if _, ok := args[i].(zap.Field); ok {
l.DPanic("strongly-typed Zap Field passed to logr", zap.Any("zap field", args[i]))
break
}
// make sure this isn't a mismatched key
if i == len(args)-1 {
l.DPanic("odd number of arguments passed as key-value pairs for logging", zap.Any("ignored key", args[i]))
break
}
// process a key-value pair,
// ensuring that the key is a string
key, val := args[i], args[i+1]
keyStr, isString := key.(string)
if !isString {
// if the key isn't a string, DPanic and stop logging
l.DPanic("non-string key argument passed to logging, ignoring all later arguments", zap.Any("invalid key", key))
break
}
fields = append(fields, zap.Any(keyStr, val))
i += 2
}
return append(fields, additional...)
}
func (l *zapLogger) Error(err error, msg string, keysAndVals ...interface{}) {
if checkedEntry := l.l.Check(zap.ErrorLevel, msg); checkedEntry != nil {
checkedEntry.Write(handleFields(l.l, keysAndVals, zap.Error(err))...)
}
}
func (l *zapLogger) V(level int) logr.InfoLogger {
lvl := zapcore.Level(-1 * level)
if l.l.Core().Enabled(lvl) {
return &infoLogger{
lvl: lvl,
l: l.l,
}
}
return disabledInfoLogger
}
func (l *zapLogger) WithValues(keysAndValues ...interface{}) logr.Logger {
newLogger := l.l.With(handleFields(l.l, keysAndValues)...)
return NewLogger(newLogger)
}
func (l *zapLogger) WithName(name string) logr.Logger {
newLogger := l.l.Named(name)
return NewLogger(newLogger)
}
// NewLogger creates a new logr.Logger using the given Zap Logger to log.
func NewLogger(l *zap.Logger) logr.Logger {
return &zapLogger{
l: l,
infoLogger: infoLogger{
l: l,
lvl: zap.InfoLevel,
},
}
}

124
vendor/k8s.io/klog/klog.go generated vendored
View File

@ -20,17 +20,17 @@
//
// Basic examples:
//
// glog.Info("Prepare to repel boarders")
// klog.Info("Prepare to repel boarders")
//
// glog.Fatalf("Initialization failed: %s", err)
// klog.Fatalf("Initialization failed: %s", err)
//
// See the documentation for the V function for an explanation of these examples:
//
// if glog.V(2) {
// glog.Info("Starting transaction...")
// if klog.V(2) {
// klog.Info("Starting transaction...")
// }
//
// glog.V(2).Infoln("Processed", nItems, "elements")
// klog.V(2).Infoln("Processed", nItems, "elements")
//
// Log output is buffered and written periodically using Flush. Programs
// should call Flush before exiting to guarantee all log output is written.
@ -142,7 +142,7 @@ func (s *severity) Set(value string) error {
if v, ok := severityByName(value); ok {
threshold = v
} else {
v, err := strconv.Atoi(value)
v, err := strconv.ParseInt(value, 10, 32)
if err != nil {
return err
}
@ -226,7 +226,7 @@ func (l *Level) Get() interface{} {
// Set is part of the flag.Value interface.
func (l *Level) Set(value string) error {
v, err := strconv.Atoi(value)
v, err := strconv.ParseInt(value, 10, 32)
if err != nil {
return err
}
@ -294,7 +294,7 @@ func (m *moduleSpec) Set(value string) error {
return errVmoduleSyntax
}
pattern := patLev[0]
v, err := strconv.Atoi(patLev[1])
v, err := strconv.ParseInt(patLev[1], 10, 32)
if err != nil {
return errors.New("syntax error: expect comma-separated list of filename=N")
}
@ -396,30 +396,23 @@ type flushSyncWriter interface {
io.Writer
}
// init sets up the defaults and runs flushDaemon.
func init() {
// Default stderrThreshold is ERROR.
logging.stderrThreshold = errorLog
logging.stderrThreshold = errorLog // Default stderrThreshold is ERROR.
logging.setVState(0, nil, false)
logging.logDir = ""
logging.logFile = ""
logging.logFileMaxSizeMB = 1800
logging.toStderr = true
logging.alsoToStderr = false
logging.skipHeaders = false
logging.addDirHeader = false
logging.skipLogHeaders = false
go logging.flushDaemon()
}
var initDefaultsOnce sync.Once
// InitFlags is for explicitly initializing the flags.
func InitFlags(flagset *flag.FlagSet) {
// Initialize defaults.
initDefaultsOnce.Do(func() {
logging.logDir = ""
logging.logFile = ""
logging.logFileMaxSizeMB = 1800
logging.toStderr = true
logging.alsoToStderr = false
logging.skipHeaders = false
logging.skipLogHeaders = false
})
if flagset == nil {
flagset = flag.CommandLine
}
@ -432,6 +425,7 @@ func InitFlags(flagset *flag.FlagSet) {
flagset.BoolVar(&logging.toStderr, "logtostderr", logging.toStderr, "log to standard error instead of files")
flagset.BoolVar(&logging.alsoToStderr, "alsologtostderr", logging.alsoToStderr, "log to standard error as well as files")
flagset.Var(&logging.verbosity, "v", "number for the log level verbosity")
flagset.BoolVar(&logging.skipHeaders, "add_dir_header", logging.addDirHeader, "If true, adds the file directory to the header")
flagset.BoolVar(&logging.skipHeaders, "skip_headers", logging.skipHeaders, "If true, avoid header prefixes in the log messages")
flagset.BoolVar(&logging.skipLogHeaders, "skip_log_headers", logging.skipLogHeaders, "If true, avoid headers when opening log files")
flagset.Var(&logging.stderrThreshold, "stderrthreshold", "logs at or above this threshold go to stderr")
@ -500,6 +494,9 @@ type loggingT struct {
// If true, do not add the headers to log files
skipLogHeaders bool
// If true, add the file directory to the header
addDirHeader bool
}
// buffer holds a byte Buffer for reuse. The zero value is ready for use.
@ -585,9 +582,14 @@ func (l *loggingT) header(s severity, depth int) (*buffer, string, int) {
file = "???"
line = 1
} else {
slash := strings.LastIndex(file, "/")
if slash >= 0 {
file = file[slash+1:]
if slash := strings.LastIndex(file, "/"); slash >= 0 {
path := file
file = path[slash+1:]
if l.addDirHeader {
if dirsep := strings.LastIndex(path[:slash], "/"); dirsep >= 0 {
file = path[dirsep+1:]
}
}
}
}
return l.formatHeader(s, file, line), file, line
@ -736,6 +738,8 @@ func (rb *redirectBuffer) Write(bytes []byte) (n int, err error) {
// SetOutput sets the output destination for all severities
func SetOutput(w io.Writer) {
logging.mu.Lock()
defer logging.mu.Unlock()
for s := fatalLog; s >= infoLog; s-- {
rb := &redirectBuffer{
w: w,
@ -746,6 +750,8 @@ func SetOutput(w io.Writer) {
// SetOutputBySeverity sets the output destination for specific severity
func SetOutputBySeverity(name string, w io.Writer) {
logging.mu.Lock()
defer logging.mu.Unlock()
sev, ok := severityByName(name)
if !ok {
panic(fmt.Sprintf("SetOutputBySeverity(%q): unrecognized severity name", name))
@ -771,24 +777,38 @@ func (l *loggingT) output(s severity, buf *buffer, file string, line int, alsoTo
if alsoToStderr || l.alsoToStderr || s >= l.stderrThreshold.get() {
os.Stderr.Write(data)
}
if l.file[s] == nil {
if err := l.createFiles(s); err != nil {
os.Stderr.Write(data) // Make sure the message appears somewhere.
l.exit(err)
if logging.logFile != "" {
// Since we are using a single log file, all of the items in l.file array
// will point to the same file, so just use one of them to write data.
if l.file[infoLog] == nil {
if err := l.createFiles(infoLog); err != nil {
os.Stderr.Write(data) // Make sure the message appears somewhere.
l.exit(err)
}
}
}
switch s {
case fatalLog:
l.file[fatalLog].Write(data)
fallthrough
case errorLog:
l.file[errorLog].Write(data)
fallthrough
case warningLog:
l.file[warningLog].Write(data)
fallthrough
case infoLog:
l.file[infoLog].Write(data)
} else {
if l.file[s] == nil {
if err := l.createFiles(s); err != nil {
os.Stderr.Write(data) // Make sure the message appears somewhere.
l.exit(err)
}
}
switch s {
case fatalLog:
l.file[fatalLog].Write(data)
fallthrough
case errorLog:
l.file[errorLog].Write(data)
fallthrough
case warningLog:
l.file[warningLog].Write(data)
fallthrough
case infoLog:
l.file[infoLog].Write(data)
}
}
}
if s == fatalLog {
@ -827,7 +847,7 @@ func (l *loggingT) output(s severity, buf *buffer, file string, line int, alsoTo
// timeoutFlush calls Flush and returns when it completes or after timeout
// elapses, whichever happens first. This is needed because the hooks invoked
// by Flush may deadlock when glog.Fatal is called from a hook that holds
// by Flush may deadlock when klog.Fatal is called from a hook that holds
// a lock.
func timeoutFlush(timeout time.Duration) {
done := make(chan bool, 1)
@ -838,7 +858,7 @@ func timeoutFlush(timeout time.Duration) {
select {
case <-done:
case <-time.After(timeout):
fmt.Fprintln(os.Stderr, "glog: Flush took longer than", timeout)
fmt.Fprintln(os.Stderr, "klog: Flush took longer than", timeout)
}
}
@ -1094,9 +1114,9 @@ type Verbose bool
// The returned value is a boolean of type Verbose, which implements Info, Infoln
// and Infof. These methods will write to the Info log if called.
// Thus, one may write either
// if glog.V(2) { glog.Info("log this") }
// if klog.V(2) { klog.Info("log this") }
// or
// glog.V(2).Info("log this")
// klog.V(2).Info("log this")
// The second form is shorter but the first is cheaper if logging is off because it does
// not evaluate its arguments.
//
@ -1170,7 +1190,7 @@ func InfoDepth(depth int, args ...interface{}) {
}
// Infoln logs to the INFO log.
// Arguments are handled in the manner of fmt.Println; a newline is appended if missing.
// Arguments are handled in the manner of fmt.Println; a newline is always appended.
func Infoln(args ...interface{}) {
logging.println(infoLog, args...)
}
@ -1194,7 +1214,7 @@ func WarningDepth(depth int, args ...interface{}) {
}
// Warningln logs to the WARNING and INFO logs.
// Arguments are handled in the manner of fmt.Println; a newline is appended if missing.
// Arguments are handled in the manner of fmt.Println; a newline is always appended.
func Warningln(args ...interface{}) {
logging.println(warningLog, args...)
}
@ -1218,7 +1238,7 @@ func ErrorDepth(depth int, args ...interface{}) {
}
// Errorln logs to the ERROR, WARNING, and INFO logs.
// Arguments are handled in the manner of fmt.Println; a newline is appended if missing.
// Arguments are handled in the manner of fmt.Println; a newline is always appended.
func Errorln(args ...interface{}) {
logging.println(errorLog, args...)
}
@ -1244,7 +1264,7 @@ func FatalDepth(depth int, args ...interface{}) {
// Fatalln logs to the FATAL, ERROR, WARNING, and INFO logs,
// including a stack trace of all running goroutines, then calls os.Exit(255).
// Arguments are handled in the manner of fmt.Println; a newline is appended if missing.
// Arguments are handled in the manner of fmt.Println; a newline is always appended.
func Fatalln(args ...interface{}) {
logging.println(fatalLog, args...)
}