...

Source file src/github.com/containerd/log/logtest/context.go

Documentation: github.com/containerd/log/logtest

     1  /*
     2     Copyright The containerd Authors.
     3  
     4     Licensed under the Apache License, Version 2.0 (the "License");
     5     you may not use this file except in compliance with the License.
     6     You may obtain a copy of the License at
     7  
     8         http://www.apache.org/licenses/LICENSE-2.0
     9  
    10     Unless required by applicable law or agreed to in writing, software
    11     distributed under the License is distributed on an "AS IS" BASIS,
    12     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13     See the License for the specific language governing permissions and
    14     limitations under the License.
    15  */
    16  
    17  package logtest
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  	"io"
    23  	"path/filepath"
    24  	"runtime"
    25  	"testing"
    26  
    27  	"github.com/containerd/log"
    28  	"github.com/sirupsen/logrus"
    29  )
    30  
    31  // WithT adds a logging hook for the given test
    32  // Changes debug level to debug, clears output, and
    33  // outputs all log messages as test logs.
    34  func WithT(ctx context.Context, t testing.TB) context.Context {
    35  	// Create a new logger to avoid adding hooks from multiple tests
    36  	l := logrus.New()
    37  
    38  	// Increase debug level for tests
    39  	l.SetLevel(logrus.DebugLevel)
    40  	l.SetOutput(io.Discard)
    41  	l.SetReportCaller(true)
    42  
    43  	// Add testing hook
    44  	l.AddHook(&testHook{
    45  		t: t,
    46  		fmt: &logrus.TextFormatter{
    47  			DisableColors:   true,
    48  			TimestampFormat: log.RFC3339NanoFixed,
    49  			CallerPrettyfier: func(frame *runtime.Frame) (string, string) {
    50  				return filepath.Base(frame.Function), fmt.Sprintf("%s:%d", frame.File, frame.Line)
    51  			},
    52  		},
    53  	})
    54  
    55  	return log.WithLogger(ctx, logrus.NewEntry(l).WithField("testcase", t.Name()))
    56  }
    57  

View as plain text