github.com/lalkh/containerd@v1.4.3/log/logtest/context.go (about)

     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  	"io/ioutil"
    22  	"testing"
    23  
    24  	"github.com/containerd/containerd/log"
    25  	"github.com/sirupsen/logrus"
    26  )
    27  
    28  // WithT adds a logging hook for the given test
    29  // Changes debug level to debug, clears output, and
    30  // outputs all log messages as test logs.
    31  func WithT(ctx context.Context, t testing.TB) context.Context {
    32  	// Create a new logger to avoid adding hooks from multiple tests
    33  	l := logrus.New()
    34  
    35  	// Increase debug level for tests
    36  	l.SetLevel(logrus.DebugLevel)
    37  	l.SetOutput(ioutil.Discard)
    38  
    39  	// Add testing hook
    40  	l.AddHook(&testHook{
    41  		t: t,
    42  		fmt: &logrus.TextFormatter{
    43  			DisableColors:   true,
    44  			TimestampFormat: log.RFC3339NanoFixed,
    45  		},
    46  	})
    47  
    48  	return log.WithLogger(ctx, logrus.NewEntry(l))
    49  }