Add custom object encoders for the set of string and namespaced name (#1309)

* Add custom object encoders for the set of string and namespaced name

In future we might add more (endpoints is a really good candidate)

* switch NN logging

* usage

* nn without ns

* nit
This commit is contained in:
Victor Agababov 2020-05-06 18:13:44 -07:00 committed by GitHub
parent c88f43eed9
commit 2581370e4a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 59 additions and 0 deletions

View File

@ -0,0 +1,59 @@
/*
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 (
"strings"
"go.uber.org/zap/zapcore"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/sets"
)
// This file contains the specific object encoders for use in Knative
// to optimize logging experience and performance.
// StringSet returns a marshaler for the set of strings.
// To use this in sugared logger do:
// logger.Infow("Revision State", zap.Object("healthy", logging.StringSet(healthySet)),
// zap.Object("unhealthy", logging.StringSet(unhealthySet)))
// To use with non-sugared logger do:
// logger.Info("Revision State", zap.Object("healthy", logging.StringSet(healthySet)),
// zap.Object("unhealthy", logging.StringSet(unhealthySet)))
func StringSet(s sets.String) zapcore.ObjectMarshalerFunc {
return func(enc zapcore.ObjectEncoder) error {
enc.AddString("keys", strings.Join(s.UnsortedList(), ","))
return nil
}
}
// NamespacedName returns a marshaler for NamespacedName.
// To use this in sugared logger do:
// logger.Infow("Enqueuing", zap.Object("key", logging.NamespacedName(n)))
// To use with non-sugared logger do:
// logger.Info("Enqueuing", zap.Object("key", logging.NamespacedName(n)))
func NamespacedName(n types.NamespacedName) zapcore.ObjectMarshalerFunc {
return func(enc zapcore.ObjectEncoder) error {
if n.Namespace != "" {
enc.AddString("key", n.Name)
} else {
enc.AddString("key", n.Namespace+"/"+n.Name)
}
return nil
}
}