1
package logger

import (
    "bytes"
    . "github.com/onsi/ginkgo"
    . "github.com/onsi/gomega"
    ctrl "sigs.k8s.io/controller-runtime"
)
var _ = Describe("Logger", func() {
    It("Test Default Log Level", func() {
        buf := &bytes.Buffer{}
        testLog := ctrl.Log.WithName("setup")
        SetLogger()
        

        testLog.Info("This is a test")
        Expect(buf.String(),"This is a test")
    })
})

这就是SetLogger生产中也使用的功能:

package logger

import (
    ctrl "sigs.k8s.io/controller-runtime"
    "sigs.k8s.io/controller-runtime/pkg/log/zap"
    ...
)

func SetLogger() {
    opts := zap.Options{
        Development:     developmentFlag,
        StacktraceLevel: stacktraceLevel,
        Level:           isLevelEnabler,
        Encoder:         logFmtEncoder,
    }
  ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts)))
}

如何更改testLog.Info缓冲区的输出?

4

1 回答 1

1

如果您只对测试日志消息感兴趣,则可以使用挂钩。

特别是zap.Hooks函数zap.Option从可变数量的钩子中构造一个。钩子只是func(entry zapcore.Entry) error您可以用来拦截条目并将其消息写入缓冲区的一个。

要将其设置zap.Option到您的sigs.k8s.io记录器中,请将其设置为ZapOpts字段:

    opts := k8szap.Options{
        // ...
        ZapOpts: []zap.Option{
            zap.Hooks(func(entry zapcore.Entry) error {
                buf.WriteString(entry.Message)
                return nil
            }),
        },
    }

因此,由于您需要访问缓冲区,因此可以将其作为参数传递给SetLogger函数:

func SetLogger(buf *bytes.Buffer) {
    opts := zap.Options{
        Development:     developmentFlag,
        StacktraceLevel: stacktraceLevel,
        Level:           isLevelEnabler,
        Encoder:         logFmtEncoder,

        // here 'zap' selector is 'go.uber.org/zap'
        ZapOpts: []zap.Option{
            zap.Hooks(func(entry zapcore.Entry) error {
                buf.WriteString(entry.Message)
                return nil
            }),
        },
    }
    // here I call 'k8szap' selector the package 'sigs.k8s.io/controller-runtime/pkg/log/zap'
    ctrl.SetLogger(k8szap.New(k8szap.UseFlagOptions(&opts)))
}

然后在您的测试功能中:

    It("Test Default Log Level", func() {
        buf := &bytes.Buffer{}
        testLog := ctrl.Log.WithName("setup")

        // pass buffer to SetLogger
        SetLogger(buf)
        

        testLog.Info("This is a test")
        Expect(buf.String(), "This is a test")
    })

最小示例(在操场上下载包时可能会超时): https: //play.golang.org/p/oBN3SHFKVC8

于 2021-10-28T12:54:16.217 回答