go.mondoo.com/cnquery@v0.0.0-20231005093811-59568235f6ea/logger/context_test.go (about) 1 // Copyright (c) Mondoo, Inc. 2 // SPDX-License-Identifier: BUSL-1.1 3 4 package logger 5 6 import ( 7 "context" 8 "encoding/json" 9 "strings" 10 "testing" 11 12 "github.com/stretchr/testify/require" 13 ) 14 15 func TestRequestIDLoggingContext(t *testing.T) { 16 type testLogMsg struct { 17 RequestID string `json:"req-id"` 18 } 19 t.Run("outputs the provided request id with the log message", func(t *testing.T) { 20 testRequestID := "test-req-id" 21 twriter := &strings.Builder{} 22 ctx := RequestScopedContext(context.Background(), testRequestID) 23 log := FromContext(ctx).Output(twriter) 24 25 log.Debug().Msg("hello") 26 msg := testLogMsg{} 27 err := json.Unmarshal([]byte(twriter.String()), &msg) 28 require.NoError(t, err) 29 require.Equal(t, testRequestID, msg.RequestID) 30 }) 31 32 t.Run("generates a request id if one is not provided", func(t *testing.T) { 33 twriter := &strings.Builder{} 34 ctx := RequestScopedContext(context.Background(), "") 35 log := FromContext(ctx).Output(twriter) 36 37 log.Debug().Msg("hello") 38 msg := testLogMsg{} 39 err := json.Unmarshal([]byte(twriter.String()), &msg) 40 require.NoError(t, err) 41 require.True(t, len(msg.RequestID) > 1) 42 require.True(t, strings.HasPrefix(msg.RequestID, "_")) 43 }) 44 }