working commit
This commit is contained in:
+208
@@ -0,0 +1,208 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 log
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
)
|
||||
|
||||
// loggerPromise knows how to populate a concrete logr.Logger
|
||||
// with options, given an actual base logger later on down the line.
|
||||
type loggerPromise struct {
|
||||
logger *delegatingLogSink
|
||||
childPromises []*loggerPromise
|
||||
promisesLock sync.Mutex
|
||||
|
||||
name *string
|
||||
tags []any
|
||||
}
|
||||
|
||||
func (p *loggerPromise) WithName(l *delegatingLogSink, name string) *loggerPromise {
|
||||
res := &loggerPromise{
|
||||
logger: l,
|
||||
name: &name,
|
||||
promisesLock: sync.Mutex{},
|
||||
}
|
||||
|
||||
p.promisesLock.Lock()
|
||||
defer p.promisesLock.Unlock()
|
||||
p.childPromises = append(p.childPromises, res)
|
||||
return res
|
||||
}
|
||||
|
||||
// WithValues provides a new Logger with the tags appended.
|
||||
func (p *loggerPromise) WithValues(l *delegatingLogSink, tags ...any) *loggerPromise {
|
||||
res := &loggerPromise{
|
||||
logger: l,
|
||||
tags: tags,
|
||||
promisesLock: sync.Mutex{},
|
||||
}
|
||||
|
||||
p.promisesLock.Lock()
|
||||
defer p.promisesLock.Unlock()
|
||||
p.childPromises = append(p.childPromises, res)
|
||||
return res
|
||||
}
|
||||
|
||||
// Fulfill instantiates the Logger with the provided logger.
|
||||
func (p *loggerPromise) Fulfill(parentLogSink logr.LogSink) {
|
||||
sink := parentLogSink
|
||||
if p.name != nil {
|
||||
sink = sink.WithName(*p.name)
|
||||
}
|
||||
|
||||
if p.tags != nil {
|
||||
sink = sink.WithValues(p.tags...)
|
||||
}
|
||||
|
||||
p.logger.lock.Lock()
|
||||
p.logger.logger = sink
|
||||
if withCallDepth, ok := sink.(logr.CallDepthLogSink); ok {
|
||||
p.logger.logger = withCallDepth.WithCallDepth(1)
|
||||
}
|
||||
p.logger.promise = nil
|
||||
p.logger.lock.Unlock()
|
||||
|
||||
for _, childPromise := range p.childPromises {
|
||||
childPromise.Fulfill(sink)
|
||||
}
|
||||
}
|
||||
|
||||
// delegatingLogSink is a logsink that delegates to another logr.LogSink.
|
||||
// If the underlying promise is not nil, it registers calls to sub-loggers with
|
||||
// the logging factory to be populated later, and returns a new delegating
|
||||
// logger. It expects to have *some* logr.Logger set at all times (generally
|
||||
// a no-op logger before the promises are fulfilled).
|
||||
type delegatingLogSink struct {
|
||||
lock sync.RWMutex
|
||||
logger logr.LogSink
|
||||
promise *loggerPromise
|
||||
info logr.RuntimeInfo
|
||||
}
|
||||
|
||||
// Init implements logr.LogSink.
|
||||
func (l *delegatingLogSink) Init(info logr.RuntimeInfo) {
|
||||
eventuallyFulfillRoot()
|
||||
l.lock.Lock()
|
||||
defer l.lock.Unlock()
|
||||
l.info = info
|
||||
}
|
||||
|
||||
// Enabled tests whether this Logger is enabled. For example, commandline
|
||||
// flags might be used to set the logging verbosity and disable some info
|
||||
// logs.
|
||||
func (l *delegatingLogSink) Enabled(level int) bool {
|
||||
eventuallyFulfillRoot()
|
||||
l.lock.RLock()
|
||||
defer l.lock.RUnlock()
|
||||
return l.logger.Enabled(level)
|
||||
}
|
||||
|
||||
// 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.
|
||||
func (l *delegatingLogSink) Info(level int, msg string, keysAndValues ...any) {
|
||||
eventuallyFulfillRoot()
|
||||
l.lock.RLock()
|
||||
defer l.lock.RUnlock()
|
||||
l.logger.Info(level, msg, keysAndValues...)
|
||||
}
|
||||
|
||||
// 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.
|
||||
func (l *delegatingLogSink) Error(err error, msg string, keysAndValues ...any) {
|
||||
eventuallyFulfillRoot()
|
||||
l.lock.RLock()
|
||||
defer l.lock.RUnlock()
|
||||
l.logger.Error(err, msg, keysAndValues...)
|
||||
}
|
||||
|
||||
// WithName provides a new Logger with the name appended.
|
||||
func (l *delegatingLogSink) WithName(name string) logr.LogSink {
|
||||
eventuallyFulfillRoot()
|
||||
l.lock.RLock()
|
||||
defer l.lock.RUnlock()
|
||||
|
||||
if l.promise == nil {
|
||||
sink := l.logger.WithName(name)
|
||||
if withCallDepth, ok := sink.(logr.CallDepthLogSink); ok {
|
||||
sink = withCallDepth.WithCallDepth(-1)
|
||||
}
|
||||
return sink
|
||||
}
|
||||
|
||||
res := &delegatingLogSink{logger: l.logger}
|
||||
promise := l.promise.WithName(res, name)
|
||||
res.promise = promise
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
// WithValues provides a new Logger with the tags appended.
|
||||
func (l *delegatingLogSink) WithValues(tags ...any) logr.LogSink {
|
||||
eventuallyFulfillRoot()
|
||||
l.lock.RLock()
|
||||
defer l.lock.RUnlock()
|
||||
|
||||
if l.promise == nil {
|
||||
sink := l.logger.WithValues(tags...)
|
||||
if withCallDepth, ok := sink.(logr.CallDepthLogSink); ok {
|
||||
sink = withCallDepth.WithCallDepth(-1)
|
||||
}
|
||||
return sink
|
||||
}
|
||||
|
||||
res := &delegatingLogSink{logger: l.logger}
|
||||
promise := l.promise.WithValues(res, tags...)
|
||||
res.promise = promise
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
// Fulfill switches the logger over to use the actual logger
|
||||
// provided, instead of the temporary initial one, if this method
|
||||
// has not been previously called.
|
||||
func (l *delegatingLogSink) Fulfill(actual logr.LogSink) {
|
||||
if actual == nil {
|
||||
actual = NullLogSink{}
|
||||
}
|
||||
if l.promise != nil {
|
||||
l.promise.Fulfill(actual)
|
||||
}
|
||||
}
|
||||
|
||||
// newDelegatingLogSink constructs a new DelegatingLogSink which uses
|
||||
// the given logger before its promise is fulfilled.
|
||||
func newDelegatingLogSink(initial logr.LogSink) *delegatingLogSink {
|
||||
l := &delegatingLogSink{
|
||||
logger: initial,
|
||||
promise: &loggerPromise{promisesLock: sync.Mutex{}},
|
||||
}
|
||||
l.promise.logger = l
|
||||
return l
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 log contains utilities for fetching a new logger
|
||||
// when one is not already available.
|
||||
//
|
||||
// # The Log Handle
|
||||
//
|
||||
// This package contains a root logr.Logger Log. It may be used to
|
||||
// get a handle to whatever the root logging implementation is. By
|
||||
// default, no implementation exists, and the handle returns "promises"
|
||||
// to loggers. When the implementation is set using SetLogger, these
|
||||
// "promises" will be converted over to real loggers.
|
||||
//
|
||||
// # Logr
|
||||
//
|
||||
// All logging in controller-runtime is structured, using a set of interfaces
|
||||
// defined by a package called logr
|
||||
// (https://pkg.go.dev/github.com/go-logr/logr). The sub-package zap provides
|
||||
// helpers for setting up logr backed by Zap (go.uber.org/zap).
|
||||
package log
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime/debug"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
)
|
||||
|
||||
// SetLogger sets a concrete logging implementation for all deferred Loggers.
|
||||
func SetLogger(l logr.Logger) {
|
||||
logFullfilled.Store(true)
|
||||
rootLog.Fulfill(l.GetSink())
|
||||
}
|
||||
|
||||
func eventuallyFulfillRoot() {
|
||||
if logFullfilled.Load() {
|
||||
return
|
||||
}
|
||||
if time.Since(rootLogCreated).Seconds() >= 30 {
|
||||
if logFullfilled.CompareAndSwap(false, true) {
|
||||
stack := debug.Stack()
|
||||
stackLines := bytes.Count(stack, []byte{'\n'})
|
||||
sep := []byte{'\n', '\t', '>', ' ', ' '}
|
||||
|
||||
fmt.Fprintf(os.Stderr,
|
||||
"[controller-runtime] log.SetLogger(...) was never called; logs will not be displayed.\nDetected at:%s%s", sep,
|
||||
// prefix every line, so it's clear this is a stack trace related to the above message
|
||||
bytes.Replace(stack, []byte{'\n'}, sep, stackLines-1),
|
||||
)
|
||||
SetLogger(logr.New(NullLogSink{}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
logFullfilled atomic.Bool
|
||||
)
|
||||
|
||||
// Log is the base logger used by kubebuilder. It delegates
|
||||
// to another logr.Logger. You *must* call SetLogger to
|
||||
// get any actual logging. If SetLogger is not called within
|
||||
// the first 30 seconds of a binaries lifetime, it will get
|
||||
// set to a NullLogSink.
|
||||
var (
|
||||
rootLog, rootLogCreated = func() (*delegatingLogSink, time.Time) {
|
||||
return newDelegatingLogSink(NullLogSink{}), time.Now()
|
||||
}()
|
||||
Log = logr.New(rootLog)
|
||||
)
|
||||
|
||||
// FromContext returns a logger with predefined values from a context.Context.
|
||||
func FromContext(ctx context.Context, keysAndValues ...any) logr.Logger {
|
||||
log := Log
|
||||
if ctx != nil {
|
||||
if logger, err := logr.FromContext(ctx); err == nil {
|
||||
log = logger
|
||||
}
|
||||
}
|
||||
return log.WithValues(keysAndValues...)
|
||||
}
|
||||
|
||||
// IntoContext takes a context and sets the logger as one of its values.
|
||||
// Use FromContext function to retrieve the logger.
|
||||
func IntoContext(ctx context.Context, log logr.Logger) context.Context {
|
||||
return logr.NewContext(ctx, log)
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 log
|
||||
|
||||
import (
|
||||
"github.com/go-logr/logr"
|
||||
)
|
||||
|
||||
// NB: this is the same as the null logger logr/testing,
|
||||
// but avoids accidentally adding the testing flags to
|
||||
// all binaries.
|
||||
|
||||
// NullLogSink is a logr.Logger that does nothing.
|
||||
type NullLogSink struct{}
|
||||
|
||||
var _ logr.LogSink = NullLogSink{}
|
||||
|
||||
// Init implements logr.LogSink.
|
||||
func (log NullLogSink) Init(logr.RuntimeInfo) {
|
||||
}
|
||||
|
||||
// Info implements logr.InfoLogger.
|
||||
func (NullLogSink) Info(_ int, _ string, _ ...any) {
|
||||
// Do nothing.
|
||||
}
|
||||
|
||||
// Enabled implements logr.InfoLogger.
|
||||
func (NullLogSink) Enabled(level int) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// Error implements logr.Logger.
|
||||
func (NullLogSink) Error(_ error, _ string, _ ...any) {
|
||||
// Do nothing.
|
||||
}
|
||||
|
||||
// WithName implements logr.Logger.
|
||||
func (log NullLogSink) WithName(_ string) logr.LogSink {
|
||||
return log
|
||||
}
|
||||
|
||||
// WithValues implements logr.Logger.
|
||||
func (log NullLogSink) WithValues(_ ...any) logr.LogSink {
|
||||
return log
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 log
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// KubeAPIWarningLoggerOptions controls the behavior
|
||||
// of a rest.WarningHandlerWithContext constructed using NewKubeAPIWarningLogger().
|
||||
type KubeAPIWarningLoggerOptions struct {
|
||||
// Deduplicate indicates a given warning message should only be written once.
|
||||
// Setting this to true in a long-running process handling many warnings can
|
||||
// result in increased memory use.
|
||||
Deduplicate bool
|
||||
}
|
||||
|
||||
// KubeAPIWarningLogger is a wrapper around
|
||||
// a provided logr.Logger that implements the
|
||||
// rest.WarningHandlerWithContext interface.
|
||||
type KubeAPIWarningLogger struct {
|
||||
// opts contain options controlling warning output
|
||||
opts KubeAPIWarningLoggerOptions
|
||||
// writtenLock gurads written
|
||||
writtenLock sync.Mutex
|
||||
// used to keep track of already logged messages
|
||||
// and help in de-duplication.
|
||||
written map[string]struct{}
|
||||
}
|
||||
|
||||
// HandleWarningHeaderWithContext handles logging for responses from API server that are
|
||||
// warnings with code being 299 and uses a logr.Logger from context for its logging purposes.
|
||||
func (l *KubeAPIWarningLogger) HandleWarningHeaderWithContext(ctx context.Context, code int, _ string, message string) {
|
||||
log := FromContext(ctx)
|
||||
|
||||
if code != 299 || len(message) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
if l.opts.Deduplicate {
|
||||
l.writtenLock.Lock()
|
||||
defer l.writtenLock.Unlock()
|
||||
|
||||
if _, alreadyLogged := l.written[message]; alreadyLogged {
|
||||
return
|
||||
}
|
||||
l.written[message] = struct{}{}
|
||||
}
|
||||
log.Info(message)
|
||||
}
|
||||
|
||||
// NewKubeAPIWarningLogger returns an implementation of rest.WarningHandlerWithContext that logs warnings
|
||||
// with code = 299 to the logger passed into HandleWarningHeaderWithContext via the context.
|
||||
func NewKubeAPIWarningLogger(opts KubeAPIWarningLoggerOptions) *KubeAPIWarningLogger {
|
||||
h := &KubeAPIWarningLogger{opts: opts}
|
||||
if opts.Deduplicate {
|
||||
h.written = map[string]struct{}{}
|
||||
}
|
||||
return h
|
||||
}
|
||||
Reference in New Issue
Block a user