github.com/v2fly/v2ray-core/v4@v4.45.2/app/log/log_test.go (about)

     1  package log_test
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  
     7  	"github.com/golang/mock/gomock"
     8  
     9  	"github.com/v2fly/v2ray-core/v4/app/log"
    10  	"github.com/v2fly/v2ray-core/v4/common"
    11  	clog "github.com/v2fly/v2ray-core/v4/common/log"
    12  	"github.com/v2fly/v2ray-core/v4/testing/mocks"
    13  )
    14  
    15  func TestCustomLogHandler(t *testing.T) {
    16  	mockCtl := gomock.NewController(t)
    17  	defer mockCtl.Finish()
    18  
    19  	var loggedValue []string
    20  
    21  	mockHandler := mocks.NewLogHandler(mockCtl)
    22  	mockHandler.EXPECT().Handle(gomock.Any()).AnyTimes().DoAndReturn(func(msg clog.Message) {
    23  		loggedValue = append(loggedValue, msg.String())
    24  	})
    25  
    26  	log.RegisterHandlerCreator(log.LogType_Console, func(lt log.LogType, options log.HandlerCreatorOptions) (clog.Handler, error) {
    27  		return mockHandler, nil
    28  	})
    29  
    30  	logger, err := log.New(context.Background(), &log.Config{
    31  		ErrorLogLevel: clog.Severity_Debug,
    32  		ErrorLogType:  log.LogType_Console,
    33  		AccessLogType: log.LogType_None,
    34  	})
    35  	common.Must(err)
    36  
    37  	common.Must(logger.Start())
    38  
    39  	clog.Record(&clog.GeneralMessage{
    40  		Severity: clog.Severity_Debug,
    41  		Content:  "test",
    42  	})
    43  
    44  	if len(loggedValue) < 2 {
    45  		t.Fatal("expected 2 log messages, but actually ", loggedValue)
    46  	}
    47  
    48  	if loggedValue[1] != "[Debug] test" {
    49  		t.Fatal("expected '[Debug] test', but actually ", loggedValue[1])
    50  	}
    51  
    52  	common.Must(logger.Close())
    53  }