Testing logs printed using other external library in golang

257 Views Asked by At

My application uses other external library (which uses zap library) to print audit-logs and now I want to test the printed audit-logs in my golang testing file. Can someone help me with it.

1

There are 1 best solutions below

1
On

You could take a look at the zaptest package:

Package zaptest provides a variety of helpers for testing log output.

As example, in your test:

func Test_zap(t *testing.T) {

    t.Run("Handle log message", func(t *testing.T) {
        // Given
        observedZapCore, observedLogs := observer.New(zap.InfoLevel)
        observedLogger := zap.New(observedZapCore)

        // When
        myFunction(observedLogger)

        // Then
        require.Equal(t, 1, observedLogs.Len())
        firstLog := observedLogs.All()[0]
        assert.Equal(t, "log myFunction", firstLog.Message)

    })
}

where myfunction is

func myFunction(logger *zap.Logger) {
    logger.Info("log myFunction")
}

Check also this interesting article about that