From be5eaf9ce8a8662eff1c519ca1c14882deb9eccb Mon Sep 17 00:00:00 2001 From: Damien Grisonnet Date: Fri, 16 Feb 2024 15:52:04 +0100 Subject: [PATCH] trace: gate traces behind log level 2 Traces are now only dumped in logs if klog verbosity level is >= 2. Prior to this change, they were outputted to logs even when the verbosity level was set to 0 although this level should only be dedicated to critical information. Level 2 is better suited for information about requests. Signed-off-by: Damien Grisonnet --- trace/trace.go | 2 +- trace/trace_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/trace/trace.go b/trace/trace.go index 187eb5d8..559aebb5 100644 --- a/trace/trace.go +++ b/trace/trace.go @@ -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() } } diff --git a/trace/trace_test.go b/trace/trace_test.go index ee7e74fa..cec0d437 100644 --- a/trace/trace_test.go +++ b/trace/trace_test.go @@ -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) { @@ -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", @@ -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())