1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2025-03-29 10:55:05 +00:00

feat: add context funcs to logging package (#4812)

Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>

Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>
This commit is contained in:
Charles-Edouard Brétéché 2022-10-05 11:37:52 +02:00 committed by GitHub
parent e75b57e635
commit 433c5bfd77
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 38 additions and 2 deletions

View file

@ -70,7 +70,7 @@ func main() {
os.Exit(1)
}
// os signal handler
signalCtx, signalCancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
signalCtx, signalCancel := signal.NotifyContext(logging.Background(), os.Interrupt, syscall.SIGTERM)
defer signalCancel()
stopCh := signalCtx.Done()

View file

@ -238,7 +238,7 @@ func main() {
// show startup message
showStartup(logger)
// os signal handler
signalCtx, signalCancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
signalCtx, signalCancel := signal.NotifyContext(logging.IntoBackground(logger), os.Interrupt, syscall.SIGTERM)
defer signalCancel()
// setup metrics

View file

@ -1,6 +1,7 @@
package logging
import (
"context"
"errors"
"flag"
"os"
@ -79,3 +80,38 @@ func Info(msg string, keysAndValues ...interface{}) {
func Error(err error, msg string, keysAndValues ...interface{}) {
GlobalLogger().Error(err, msg, keysAndValues...)
}
// FromContext returns a logger with predefined values from a context.Context.
func FromContext(ctx context.Context, keysAndValues ...interface{}) (logr.Logger, error) {
logger, err := logr.FromContext(ctx)
if err != nil {
return logger, err
}
return logger.WithValues(keysAndValues...), nil
}
// 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)
}
// IntoBackground calls IntoContext with the logger and a Background context.
func IntoBackground(log logr.Logger) context.Context {
return IntoContext(context.Background(), log)
}
// IntoTODO calls IntoContext with the logger and a TODO context.
func IntoTODO(log logr.Logger) context.Context {
return IntoContext(context.TODO(), log)
}
// Background calls IntoContext with the global logger and a Background context.
func Background() context.Context {
return IntoContext(context.Background(), GlobalLogger())
}
// TODO calls IntoContext with the global logger and a TODO context.
func TODO() context.Context {
return IntoContext(context.TODO(), GlobalLogger())
}