Skip to content

Commit

Permalink
Merge pull request #301 from dgrisonnet/traces-verbosity
Browse files Browse the repository at this point in the history
Gate traces behind log level 2
  • Loading branch information
k8s-ci-robot committed Apr 23, 2024
2 parents 4693a02 + be5eaf9 commit 0849a56
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
2 changes: 1 addition & 1 deletion trace/trace.go
Expand Up @@ -192,7 +192,7 @@ func (t *Trace) Log() {
t.endTime = &endTime
t.lock.Unlock()
// an explicit logging request should dump all the steps out at the higher level
if t.parentTrace == nil { // We don't start logging until Log or LogIfLong is called on the root trace
if t.parentTrace == nil && klogV(2) { // We don't start logging until Log or LogIfLong is called on the root trace
t.logTrace()
}
}
Expand Down
24 changes: 24 additions & 0 deletions trace/trace_test.go
Expand Up @@ -31,6 +31,7 @@ import (
func init() {
klog.InitFlags(flag.CommandLine)
flag.CommandLine.Lookup("logtostderr").Value.Set("false")
flag.CommandLine.Lookup("v").Value.Set("2")
}

func TestStep(t *testing.T) {
Expand Down Expand Up @@ -140,6 +141,7 @@ func TestLog(t *testing.T) {
fields []Field
expectedMessages []string
sampleTrace *Trace
verbosity klog.Level
}{
{
name: "Check the log dump with 3 msg",
Expand Down Expand Up @@ -177,13 +179,35 @@ func TestLog(t *testing.T) {
},
sampleTrace: fieldsTraceFixture(),
},
{
name: "Check that logs are not dumped if verbosity < 2",
verbosity: 1,
expectedMessages: []string{},
sampleTrace: fieldsTraceFixture(),
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var buf bytes.Buffer
klog.SetOutput(&buf)

if test.verbosity > 0 {
orig := klogV
klogV = func(l klog.Level) bool {
return l <= test.verbosity
}
defer func() {
klogV = orig
}()
}

test.sampleTrace.Log()

if len(test.expectedMessages) == 0 && buf.Len() != 0 {
t.Errorf("\nNo message expected in trace log: \n%v\n", buf.String())
}

for _, msg := range test.expectedMessages {
if !strings.Contains(buf.String(), msg) {
t.Errorf("\nMsg %q not found in log: \n%v\n", msg, buf.String())
Expand Down

0 comments on commit 0849a56

Please sign in to comment.