diff --git a/internal/pkg/agent/application/actions/handlers/handler_action_diagnostics_test.go b/internal/pkg/agent/application/actions/handlers/handler_action_diagnostics_test.go index e6e8270d56f..de591b2eb78 100644 --- a/internal/pkg/agent/application/actions/handlers/handler_action_diagnostics_test.go +++ b/internal/pkg/agent/application/actions/handlers/handler_action_diagnostics_test.go @@ -18,8 +18,6 @@ import ( "github.com/elastic/elastic-agent-client/v7/pkg/client" "github.com/elastic/elastic-agent-client/v7/pkg/proto" - "github.com/elastic/elastic-agent/pkg/control/v2/cproto" - "github.com/elastic/elastic-agent/internal/pkg/agent/application/paths" "github.com/elastic/elastic-agent/internal/pkg/agent/errors" "github.com/elastic/elastic-agent/internal/pkg/core/monitoring/config" @@ -27,7 +25,8 @@ import ( "github.com/elastic/elastic-agent/internal/pkg/fleetapi" "github.com/elastic/elastic-agent/pkg/component" "github.com/elastic/elastic-agent/pkg/component/runtime" - "github.com/elastic/elastic-agent/pkg/core/logger" + "github.com/elastic/elastic-agent/pkg/control/v2/cproto" + "github.com/elastic/elastic-agent/pkg/core/logger/loggertest" mockhandlers "github.com/elastic/elastic-agent/testing/mocks/internal_/pkg/agent/application/actions/handlers" mockackers "github.com/elastic/elastic-agent/testing/mocks/internal_/pkg/fleetapi/acker" ) @@ -81,7 +80,7 @@ func TestDiagnosticHandlerHappyPathWithLogs(t *testing.T) { mockDiagProvider := mockhandlers.NewDiagnosticsProvider(t) mockUploader := mockhandlers.NewUploader(t) - testLogger, observedLogs := logger.NewTesting("diagnostic-handler-test") + testLogger, observedLogs := loggertest.New("diagnostic-handler-test") handler := NewDiagnostics(testLogger, tempAgentRoot, mockDiagProvider, defaultRateLimit, mockUploader) mockDiagProvider.EXPECT().DiagnosticHooks().Return([]diagnostics.Hook{hook1}) @@ -162,7 +161,7 @@ func TestDiagnosticHandlerUploaderErrorWithLogs(t *testing.T) { mockDiagProvider := mockhandlers.NewDiagnosticsProvider(t) mockUploader := mockhandlers.NewUploader(t) - testLogger, observedLogs := logger.NewTesting("diagnostic-handler-test") + testLogger, observedLogs := loggertest.New("diagnostic-handler-test") handler := NewDiagnostics(testLogger, tempAgentRoot, mockDiagProvider, defaultRateLimit, mockUploader) mockDiagProvider.EXPECT().DiagnosticHooks().Return([]diagnostics.Hook{}) @@ -203,7 +202,7 @@ func TestDiagnosticHandlerZipArchiveErrorWithLogs(t *testing.T) { mockDiagProvider := mockhandlers.NewDiagnosticsProvider(t) mockUploader := mockhandlers.NewUploader(t) - testLogger, observedLogs := logger.NewTesting("diagnostic-handler-test") + testLogger, observedLogs := loggertest.New("diagnostic-handler-test") handler := NewDiagnostics(testLogger, tempAgentRoot, mockDiagProvider, defaultRateLimit, mockUploader) mockDiagProvider.EXPECT().DiagnosticHooks().Return([]diagnostics.Hook{}) @@ -239,7 +238,7 @@ func TestDiagnosticHandlerAckErrorWithLogs(t *testing.T) { mockDiagProvider := mockhandlers.NewDiagnosticsProvider(t) mockUploader := mockhandlers.NewUploader(t) - testLogger, observedLogs := logger.NewTesting("diagnostic-handler-test") + testLogger, observedLogs := loggertest.New("diagnostic-handler-test") handler := NewDiagnostics(testLogger, tempAgentRoot, mockDiagProvider, defaultRateLimit, mockUploader) mockDiagProvider.EXPECT().DiagnosticHooks().Return([]diagnostics.Hook{}) @@ -278,7 +277,7 @@ func TestDiagnosticHandlerCommitErrorWithLogs(t *testing.T) { mockDiagProvider := mockhandlers.NewDiagnosticsProvider(t) mockUploader := mockhandlers.NewUploader(t) - testLogger, observedLogs := logger.NewTesting("diagnostic-handler-test") + testLogger, observedLogs := loggertest.New("diagnostic-handler-test") handler := NewDiagnostics(testLogger, tempAgentRoot, mockDiagProvider, defaultRateLimit, mockUploader) mockDiagProvider.EXPECT().DiagnosticHooks().Return([]diagnostics.Hook{}) @@ -318,7 +317,7 @@ func TestDiagnosticHandlerContexteExpiredErrorWithLogs(t *testing.T) { mockDiagProvider := mockhandlers.NewDiagnosticsProvider(t) mockUploader := mockhandlers.NewUploader(t) - testLogger, observedLogs := logger.NewTesting("diagnostic-handler-test") + testLogger, observedLogs := loggertest.New("diagnostic-handler-test") handler := NewDiagnostics(testLogger, tempAgentRoot, mockDiagProvider, defaultRateLimit, mockUploader) mockDiagProvider.EXPECT().DiagnosticHooks().Return([]diagnostics.Hook{}) @@ -362,7 +361,7 @@ func TestDiagnosticHandlerWithCPUProfile(t *testing.T) { mockDiagProvider := mockhandlers.NewDiagnosticsProvider(t) mockUploader := mockhandlers.NewUploader(t) - testLogger, _ := logger.NewTesting("diagnostic-handler-test") + testLogger, _ := loggertest.New("diagnostic-handler-test") handler := NewDiagnostics(testLogger, tempAgentRoot, mockDiagProvider, defaultRateLimit, mockUploader) mockDiagProvider.EXPECT().DiagnosticHooks().Return([]diagnostics.Hook{hook1}) diff --git a/internal/pkg/agent/application/actions/handlers/handler_action_policy_change_test.go b/internal/pkg/agent/application/actions/handlers/handler_action_policy_change_test.go index 6ebc5ef783d..1ca4083194b 100644 --- a/internal/pkg/agent/application/actions/handlers/handler_action_policy_change_test.go +++ b/internal/pkg/agent/application/actions/handlers/handler_action_policy_change_test.go @@ -39,6 +39,7 @@ import ( "github.com/elastic/elastic-agent/internal/pkg/fleetapi/client" "github.com/elastic/elastic-agent/internal/pkg/remote" "github.com/elastic/elastic-agent/pkg/core/logger" + "github.com/elastic/elastic-agent/pkg/core/logger/loggertest" mockhandlers "github.com/elastic/elastic-agent/testing/mocks/internal_/pkg/agent/application/actions/handlers" ) @@ -165,7 +166,7 @@ func TestPolicyChangeHandler_handlePolicyChange_FleetClientSettings(t *testing.T t.Run("policy with proxy config", func(t *testing.T) { t.Run("rollback client changes when cannot create client", func(t *testing.T) { - log, _ := logger.NewTesting("TestPolicyChangeHandler") + log, _ := loggertest.New("TestPolicyChangeHandler") var setterCalledCount int setter := testSetter{SetClientFn: func(c client.Sender) { setterCalledCount++ @@ -221,7 +222,7 @@ func TestPolicyChangeHandler_handlePolicyChange_FleetClientSettings(t *testing.T t.Run("rollback client changes when cannot reach fleet-server", func(t *testing.T) { - log, _ := logger.NewTesting("TestPolicyChangeHandler") + log, _ := loggertest.New("TestPolicyChangeHandler") var setterCalledCount int setter := testSetter{SetClientFn: func(c client.Sender) { setterCalledCount++ @@ -277,7 +278,7 @@ func TestPolicyChangeHandler_handlePolicyChange_FleetClientSettings(t *testing.T }) t.Run("a new Hosts and no proxy changes the remote config", func(t *testing.T) { - log, _ := logger.NewTesting("TestPolicyChangeHandler") + log, _ := loggertest.New("TestPolicyChangeHandler") var setterCalledCount int setter := testSetter{SetClientFn: func(c client.Sender) { setterCalledCount++ @@ -321,7 +322,7 @@ func TestPolicyChangeHandler_handlePolicyChange_FleetClientSettings(t *testing.T }) t.Run("a proxy changes the fleet client", func(t *testing.T) { - log, _ := logger.NewTesting("TestPolicyChangeHandler") + log, _ := loggertest.New("TestPolicyChangeHandler") var setterCalledCount int setter := testSetter{SetClientFn: func(c client.Sender) { setterCalledCount++ @@ -371,7 +372,7 @@ func TestPolicyChangeHandler_handlePolicyChange_FleetClientSettings(t *testing.T func(t *testing.T) { wantProxy := mockProxy.URL - log, _ := logger.NewTesting("TestPolicyChangeHandler") + log, _ := loggertest.New("TestPolicyChangeHandler") var setterCalledCount int setter := testSetter{SetClientFn: func(c client.Sender) { setterCalledCount++ @@ -433,7 +434,7 @@ func TestPolicyChangeHandler_handlePolicyChange_FleetClientSettings(t *testing.T })) defer alwaysErroringServer.Close() - log, _ := logger.NewTesting("TestPolicyChangeHandler") + log, _ := loggertest.New("TestPolicyChangeHandler") var setterCalledCount int setter := testSetter{SetClientFn: func(c client.Sender) { setterCalledCount++ @@ -886,7 +887,7 @@ func TestPolicyChangeHandler_handlePolicyChange_FleetClientSettings(t *testing.T for _, tc := range tcs { t.Run(tc.name, func(t *testing.T) { - log, logs := logger.NewTesting(tc.name) + log, logs := loggertest.New(tc.name) defer func() { if t.Failed() { t.Log("test failed, see handler logs below:") @@ -1081,7 +1082,7 @@ func TestPolicyChangeHandler_handlePolicyChange_LogLevelSet(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - log, _ := logger.NewTesting(tt.name) + log, _ := loggertest.New(tt.name) mockLogLevelSetter := mockhandlers.NewLogLevelSetter(t) if tt.setupExpectations != nil { diff --git a/internal/pkg/agent/application/actions/handlers/handler_action_settings_test.go b/internal/pkg/agent/application/actions/handlers/handler_action_settings_test.go index 0d8d6e1444e..cf407ac67ff 100644 --- a/internal/pkg/agent/application/actions/handlers/handler_action_settings_test.go +++ b/internal/pkg/agent/application/actions/handlers/handler_action_settings_test.go @@ -15,6 +15,7 @@ import ( "github.com/elastic/elastic-agent-libs/logp" "github.com/elastic/elastic-agent/internal/pkg/fleetapi" "github.com/elastic/elastic-agent/pkg/core/logger" + "github.com/elastic/elastic-agent/pkg/core/logger/loggertest" mockhandlers "github.com/elastic/elastic-agent/testing/mocks/internal_/pkg/agent/application/actions/handlers" mockinfo "github.com/elastic/elastic-agent/testing/mocks/internal_/pkg/agent/application/info" mockfleetacker "github.com/elastic/elastic-agent/testing/mocks/internal_/pkg/fleetapi/acker" @@ -88,7 +89,7 @@ func TestSettings_SetLogLevel(t *testing.T) { tt.setupMocks(t, mockLogLevelSetter, mockAgentInfo) } - log, _ := logger.NewTesting(tt.name) + log, _ := loggertest.New(tt.name) ctx := context.Background() @@ -191,7 +192,7 @@ func TestSettings_handleLogLevel(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - log, _ := logger.NewTesting(tt.name) + log, _ := loggertest.New(tt.name) mockAgentInfo := mockinfo.NewAgent(t) mockLogLevelSetter := mockhandlers.NewLogLevelSetter(t) mockAcker := mockfleetacker.NewAcker(t) diff --git a/internal/pkg/agent/application/apm_config_modifier_test.go b/internal/pkg/agent/application/apm_config_modifier_test.go index 11e71c2b820..0c080e5f281 100644 --- a/internal/pkg/agent/application/apm_config_modifier_test.go +++ b/internal/pkg/agent/application/apm_config_modifier_test.go @@ -14,10 +14,9 @@ import ( "gopkg.in/yaml.v2" "github.com/elastic/elastic-agent-client/v7/pkg/proto" - "github.com/elastic/elastic-agent/internal/pkg/config" "github.com/elastic/elastic-agent/pkg/component" - "github.com/elastic/elastic-agent/pkg/core/logger" + "github.com/elastic/elastic-agent/pkg/core/logger/loggertest" ) type injectedConfigAssertion func(*testing.T, []component.Component) @@ -449,7 +448,7 @@ func TestPatchAPMConfig(t *testing.T) { require.NoError(t, err) agtConf, err := config.NewConfigFrom(tt.args.agentFileCfg) require.NoError(t, err) - log, _ := logger.NewTesting(tt.name) + log, _ := loggertest.New(tt.name) patcher := PatchAPMConfig(log, agtConf) mcc := &mockConfigChange{c: fleetConf} diff --git a/internal/pkg/agent/application/application_test.go b/internal/pkg/agent/application/application_test.go index 37744a54a3e..22b6d9d6f62 100644 --- a/internal/pkg/agent/application/application_test.go +++ b/internal/pkg/agent/application/application_test.go @@ -17,7 +17,7 @@ import ( "github.com/elastic/elastic-agent/internal/pkg/agent/application/info" "github.com/elastic/elastic-agent/internal/pkg/config" "github.com/elastic/elastic-agent/internal/pkg/testutils" - "github.com/elastic/elastic-agent/pkg/core/logger" + "github.com/elastic/elastic-agent/pkg/core/logger/loggertest" "github.com/elastic/elastic-agent/pkg/limits" ) @@ -48,7 +48,7 @@ func TestMergeFleetConfig(t *testing.T) { } func TestLimitsLog(t *testing.T) { - log, obs := logger.NewTesting("TestLimitsLog") + log, obs := loggertest.New("TestLimitsLog") ctx, cn := context.WithCancel(context.Background()) defer cn() diff --git a/internal/pkg/agent/application/coordinator/coordinator_unit_test.go b/internal/pkg/agent/application/coordinator/coordinator_unit_test.go index 5aa8e975872..c60c37aa648 100644 --- a/internal/pkg/agent/application/coordinator/coordinator_unit_test.go +++ b/internal/pkg/agent/application/coordinator/coordinator_unit_test.go @@ -34,7 +34,7 @@ import ( "github.com/elastic/elastic-agent/pkg/component" "github.com/elastic/elastic-agent/pkg/component/runtime" agentclient "github.com/elastic/elastic-agent/pkg/control/v2/client" - "github.com/elastic/elastic-agent/pkg/core/logger" + "github.com/elastic/elastic-agent/pkg/core/logger/loggertest" "github.com/elastic/elastic-agent/pkg/utils/broadcaster" ) @@ -338,7 +338,7 @@ func TestCoordinatorReportsInvalidPolicy(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() - log, obs := logger.NewTesting("") + log, obs := loggertest.New("") defer func() { if t.Failed() { t.Log("test failed, coordinator logs below:") diff --git a/internal/pkg/agent/application/dispatcher/dispatcher_test.go b/internal/pkg/agent/application/dispatcher/dispatcher_test.go index e8cd23b2cce..805e04f81e7 100644 --- a/internal/pkg/agent/application/dispatcher/dispatcher_test.go +++ b/internal/pkg/agent/application/dispatcher/dispatcher_test.go @@ -20,7 +20,7 @@ import ( "github.com/elastic/elastic-agent/internal/pkg/fleetapi" "github.com/elastic/elastic-agent/internal/pkg/fleetapi/acker" "github.com/elastic/elastic-agent/internal/pkg/fleetapi/acker/noop" - "github.com/elastic/elastic-agent/pkg/core/logger" + "github.com/elastic/elastic-agent/pkg/core/logger/loggertest" ) type mockHandler struct { @@ -753,7 +753,7 @@ func TestReportNextScheduledUpgrade(t *testing.T) { detailsSetter := func(upgradeDetails *details.Details) { actualDetails = upgradeDetails } - log, obs := logger.NewTesting("report_next_upgrade_details") + log, obs := loggertest.New("report_next_upgrade_details") d.reportNextScheduledUpgrade(test.actions, detailsSetter, log) diff --git a/internal/pkg/agent/application/gateway/fleet/fleet_gateway_test.go b/internal/pkg/agent/application/gateway/fleet/fleet_gateway_test.go index b395b92965e..7130768cb34 100644 --- a/internal/pkg/agent/application/gateway/fleet/fleet_gateway_test.go +++ b/internal/pkg/agent/application/gateway/fleet/fleet_gateway_test.go @@ -9,7 +9,6 @@ import ( "context" "encoding/json" "fmt" - "io" "net/http" "net/url" @@ -32,6 +31,7 @@ import ( "github.com/elastic/elastic-agent/internal/pkg/scheduler" agentclient "github.com/elastic/elastic-agent/pkg/control/v2/client" "github.com/elastic/elastic-agent/pkg/core/logger" + "github.com/elastic/elastic-agent/pkg/core/logger/loggertest" ) type clientCallbackFunc func(headers http.Header, body io.Reader) (*http.Response, error) @@ -317,7 +317,7 @@ func TestFleetGateway(t *testing.T) { scheduler := scheduler.NewStepper() client := newTestingClient() - log, _ := logger.NewTesting("fleet_gateway") + log, _ := loggertest.New("fleet_gateway") stateStore := newStateStore(t, log) diff --git a/internal/pkg/agent/application/monitoring/reload/reload_test.go b/internal/pkg/agent/application/monitoring/reload/reload_test.go index 7a42a64cca6..132cafb92e1 100644 --- a/internal/pkg/agent/application/monitoring/reload/reload_test.go +++ b/internal/pkg/agent/application/monitoring/reload/reload_test.go @@ -12,7 +12,7 @@ import ( aConfig "github.com/elastic/elastic-agent/internal/pkg/config" monitoringCfg "github.com/elastic/elastic-agent/internal/pkg/core/monitoring/config" - "github.com/elastic/elastic-agent/pkg/core/logger" + "github.com/elastic/elastic-agent/pkg/core/logger/loggertest" ) func TestReload(t *testing.T) { @@ -78,7 +78,7 @@ agent.monitoring.enabled: false for _, tc := range tcs { t.Run(tc.name, func(t *testing.T) { fsc := &fakeServerController{} - log, _ := logger.NewTesting(tc.name) + log, _ := loggertest.New(tc.name) cfg := &monitoringCfg.MonitoringConfig{ Enabled: tc.currEnabled, MonitorMetrics: tc.currMetrics, diff --git a/internal/pkg/agent/application/upgrade/artifact/config_test.go b/internal/pkg/agent/application/upgrade/artifact/config_test.go index 736c9a02d55..29d0f159f48 100644 --- a/internal/pkg/agent/application/upgrade/artifact/config_test.go +++ b/internal/pkg/agent/application/upgrade/artifact/config_test.go @@ -16,7 +16,7 @@ import ( agentlibsconfig "github.com/elastic/elastic-agent-libs/config" "github.com/elastic/elastic-agent-libs/transport/httpcommon" "github.com/elastic/elastic-agent/internal/pkg/config" - "github.com/elastic/elastic-agent/pkg/core/logger" + "github.com/elastic/elastic-agent/pkg/core/logger/loggertest" ) func TestReload(t *testing.T) { @@ -224,7 +224,7 @@ func TestReload(t *testing.T) { }, } - l, _ := logger.NewTesting("t") + l, _ := loggertest.New("t") for _, tc := range testCases { cfg := tc.initialConfig reloader := NewReloader(cfg, l) diff --git a/internal/pkg/agent/application/upgrade/artifact/download/fs/verifier_test.go b/internal/pkg/agent/application/upgrade/artifact/download/fs/verifier_test.go index 280a4c374b3..7496c0cb9b2 100644 --- a/internal/pkg/agent/application/upgrade/artifact/download/fs/verifier_test.go +++ b/internal/pkg/agent/application/upgrade/artifact/download/fs/verifier_test.go @@ -22,6 +22,7 @@ import ( "github.com/elastic/elastic-agent/internal/pkg/agent/application/upgrade/artifact/download" "github.com/elastic/elastic-agent/internal/pkg/release" "github.com/elastic/elastic-agent/pkg/core/logger" + "github.com/elastic/elastic-agent/pkg/core/logger/loggertest" agtversion "github.com/elastic/elastic-agent/pkg/version" "github.com/elastic/elastic-agent/testing/pgptest" ) @@ -201,7 +202,7 @@ func TestVerify(t *testing.T) { for _, tc := range tt { t.Run(tc.Name, func(t *testing.T) { - log, obs := logger.NewTesting("TestVerify") + log, obs := loggertest.New("TestVerify") targetDir := t.TempDir() timeout := 30 * time.Second diff --git a/internal/pkg/agent/application/upgrade/artifact/download/http/downloader_test.go b/internal/pkg/agent/application/upgrade/artifact/download/http/downloader_test.go index c914d9d8b38..f4853b2474e 100644 --- a/internal/pkg/agent/application/upgrade/artifact/download/http/downloader_test.go +++ b/internal/pkg/agent/application/upgrade/artifact/download/http/downloader_test.go @@ -25,6 +25,7 @@ import ( "github.com/elastic/elastic-agent/internal/pkg/agent/application/upgrade/artifact" "github.com/elastic/elastic-agent/internal/pkg/agent/application/upgrade/details" "github.com/elastic/elastic-agent/pkg/core/logger" + "github.com/elastic/elastic-agent/pkg/core/logger/loggertest" agtversion "github.com/elastic/elastic-agent/pkg/version" "github.com/docker/go-units" @@ -109,7 +110,7 @@ func TestDownloadBodyError(t *testing.T) { Architecture: "64", } - log, obs := logger.NewTesting("downloader") + log, obs := loggertest.New("downloader") upgradeDetails := details.NewDetails("8.12.0", details.StateRequested, "") testClient := NewDownloaderWithClient(log, config, *client, upgradeDetails) artifactPath, err := testClient.Download(context.Background(), beatSpec, version) @@ -166,7 +167,7 @@ func TestDownloadLogProgressWithLength(t *testing.T) { }, } - log, obs := logger.NewTesting("downloader") + log, obs := loggertest.New("downloader") upgradeDetails := details.NewDetails("8.12.0", details.StateRequested, "") testClient := NewDownloaderWithClient(log, config, *client, upgradeDetails) artifactPath, err := testClient.Download(context.Background(), beatSpec, version) @@ -249,7 +250,7 @@ func TestDownloadLogProgressWithoutLength(t *testing.T) { }, } - log, obs := logger.NewTesting("downloader") + log, obs := loggertest.New("downloader") upgradeDetails := details.NewDetails("8.12.0", details.StateRequested, "") testClient := NewDownloaderWithClient(log, config, *client, upgradeDetails) artifactPath, err := testClient.Download(context.Background(), beatSpec, version) @@ -510,7 +511,7 @@ func TestDownloadVersion(t *testing.T) { defer server.Close() elasticClient := server.Client() - log, _ := logger.NewTesting("downloader") + log, _ := loggertest.New("downloader") upgradeDetails := details.NewDetails(tt.args.version.String(), details.StateRequested, "") config := tt.fields.config config.SourceURI = server.URL diff --git a/internal/pkg/agent/application/upgrade/artifact/download/snapshot/downloader_test.go b/internal/pkg/agent/application/upgrade/artifact/download/snapshot/downloader_test.go index 7260b11f351..996a2b478c1 100644 --- a/internal/pkg/agent/application/upgrade/artifact/download/snapshot/downloader_test.go +++ b/internal/pkg/agent/application/upgrade/artifact/download/snapshot/downloader_test.go @@ -21,7 +21,7 @@ import ( "github.com/elastic/elastic-agent/internal/pkg/agent/application/upgrade/artifact" "github.com/elastic/elastic-agent/internal/pkg/agent/application/upgrade/details" - "github.com/elastic/elastic-agent/pkg/core/logger" + "github.com/elastic/elastic-agent/pkg/core/logger/loggertest" agtversion "github.com/elastic/elastic-agent/pkg/version" ) @@ -123,7 +123,7 @@ func TestDownloadVersion(t *testing.T) { server := httptest.NewTLSServer(http.HandlerFunc(handleDownload)) defer server.Close() - log, _ := logger.NewTesting("downloader") + log, _ := loggertest.New("downloader") upgradeDetails := details.NewDetails(tt.args.version.String(), details.StateRequested, "") config := tt.fields.config diff --git a/internal/pkg/agent/application/upgrade/artifact/download/verifier_test.go b/internal/pkg/agent/application/upgrade/artifact/download/verifier_test.go index 923ef35ecac..66a7004bdfc 100644 --- a/internal/pkg/agent/application/upgrade/artifact/download/verifier_test.go +++ b/internal/pkg/agent/application/upgrade/artifact/download/verifier_test.go @@ -21,7 +21,7 @@ import ( "github.com/stretchr/testify/require" "github.com/elastic/elastic-agent/internal/pkg/agent/errors" - "github.com/elastic/elastic-agent/pkg/core/logger" + "github.com/elastic/elastic-agent/pkg/core/logger/loggertest" ) func TestPgpBytesFromSource(t *testing.T) { @@ -100,7 +100,7 @@ func TestPgpBytesFromSource(t *testing.T) { for _, tc := range testCases { t.Run(tc.Name, func(t *testing.T) { - log, obs := logger.NewTesting(tc.Name) + log, obs := loggertest.New(tc.Name) mockClient := &MockClient{ DoFunc: func(req *http.Request) (*http.Response, error) { if tc.ClientDoErr != nil { @@ -294,7 +294,7 @@ func TestVerifySHA512HashWithCleanup_BrokenHashFile(t *testing.T) { require.NoError(t, err, "could not write test hash file") } - testLogger, obsLogs := logger.NewTesting(tt.name) + testLogger, obsLogs := loggertest.New(tt.name) err = VerifySHA512HashWithCleanup(testLogger, dataFilePath) tt.wantErr(t, err) for _, log := range tt.wantLogSnippets { diff --git a/internal/pkg/agent/application/upgrade/marker_watcher_test.go b/internal/pkg/agent/application/upgrade/marker_watcher_test.go index 42af901687a..2c0c47826f0 100644 --- a/internal/pkg/agent/application/upgrade/marker_watcher_test.go +++ b/internal/pkg/agent/application/upgrade/marker_watcher_test.go @@ -19,13 +19,13 @@ import ( "gopkg.in/yaml.v2" "github.com/elastic/elastic-agent/internal/pkg/agent/application/upgrade/details" - "github.com/elastic/elastic-agent/pkg/core/logger" + "github.com/elastic/elastic-agent/pkg/core/logger/loggertest" ) func TestMarkerWatcher(t *testing.T) { testMarkerDir := t.TempDir() testMarkerFile := filepath.Join(testMarkerDir, markerFilename) - testLogger, _ := logger.NewTesting("watch_marker") + testLogger, _ := loggertest.New("watch_marker") markerWatcher := newMarkerFileWatcher(testMarkerFile, testLogger) @@ -225,7 +225,7 @@ details: err := os.WriteFile(testMarkerFilePath, []byte(test.markerFileContents), 0644) require.NoError(t, err) } - log, obs := logger.NewTesting("marker_watcher") + log, obs := loggertest.New("marker_watcher") updateCh := make(chan UpdateMarker) mfw := MarkerFileWatcher{ markerFilePath: testMarkerFilePath, diff --git a/internal/pkg/agent/application/upgrade/rollback_test.go b/internal/pkg/agent/application/upgrade/rollback_test.go index 5c77caf7953..e87e2dc0beb 100644 --- a/internal/pkg/agent/application/upgrade/rollback_test.go +++ b/internal/pkg/agent/application/upgrade/rollback_test.go @@ -18,6 +18,7 @@ import ( "github.com/elastic/elastic-agent/internal/pkg/agent/application/paths" "github.com/elastic/elastic-agent/pkg/core/logger" + "github.com/elastic/elastic-agent/pkg/core/logger/loggertest" mocks "github.com/elastic/elastic-agent/testing/mocks/pkg/control/v2/client" ) @@ -204,7 +205,7 @@ func TestCleanup(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { - testLogger, _ := logger.NewTesting(t.Name()) + testLogger, _ := loggertest.New(t.Name()) testTop := t.TempDir() setupAgents(t, testLogger, testTop, tt.agentInstallsSetup) if tt.additionalSetup != nil { @@ -299,7 +300,7 @@ func TestRollback(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { - testLogger, _ := logger.NewTesting(t.Name()) + testLogger, _ := loggertest.New(t.Name()) testTop := t.TempDir() setupAgents(t, testLogger, testTop, tt.agentInstallsSetup) if tt.additionalSetup != nil { diff --git a/internal/pkg/agent/application/upgrade/step_download_test.go b/internal/pkg/agent/application/upgrade/step_download_test.go index ed2ef1535c3..1b710be774e 100644 --- a/internal/pkg/agent/application/upgrade/step_download_test.go +++ b/internal/pkg/agent/application/upgrade/step_download_test.go @@ -21,6 +21,7 @@ import ( "github.com/elastic/elastic-agent/internal/pkg/agent/application/upgrade/details" "github.com/elastic/elastic-agent/internal/pkg/agent/errors" "github.com/elastic/elastic-agent/pkg/core/logger" + "github.com/elastic/elastic-agent/pkg/core/logger/loggertest" agtversion "github.com/elastic/elastic-agent/pkg/version" ) @@ -53,7 +54,7 @@ func TestFallbackIsAppended(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - l, _ := logger.NewTesting(tc.name) + l, _ := loggertest.New(tc.name) u := Upgrader{ fleetServerURI: tc.fleetServerURI, log: l, @@ -75,7 +76,7 @@ func TestFallbackIsAppended(t *testing.T) { func TestDownloadWithRetries(t *testing.T) { expectedDownloadPath := "https://artifacts.elastic.co/downloads/beats/elastic-agent" - testLogger, obs := logger.NewTesting("TestDownloadWithRetries") + testLogger, obs := loggertest.New("TestDownloadWithRetries") settings := artifact.Config{ RetrySleepInitDuration: 20 * time.Millisecond, @@ -271,7 +272,7 @@ func TestDownloadWithRetries(t *testing.T) { // Check that upgradeDetails.Metadata.RetryErrorMsg was set at some point // during the retryable download and then check that it was never unset, - //since we didn't have a successful download. + // since we didn't have a successful download. require.NotEmpty(t, *upgradeDetailsRetryErrorMsg) require.Equal(t, *upgradeDetailsRetryErrorMsg, upgradeDetails.Metadata.RetryErrorMsg) }) diff --git a/internal/pkg/agent/application/upgrade/step_unpack_test.go b/internal/pkg/agent/application/upgrade/step_unpack_test.go index 5151058e0e7..30cf89a9c50 100644 --- a/internal/pkg/agent/application/upgrade/step_unpack_test.go +++ b/internal/pkg/agent/application/upgrade/step_unpack_test.go @@ -23,7 +23,7 @@ import ( "github.com/stretchr/testify/require" v1 "github.com/elastic/elastic-agent/pkg/api/v1" - "github.com/elastic/elastic-agent/pkg/core/logger" + "github.com/elastic/elastic-agent/pkg/core/logger/loggertest" ) const agentBinaryPlaceholderContent = "Placeholder for the elastic-agent binary" @@ -185,7 +185,7 @@ func TestUpgrader_unpackTarGz(t *testing.T) { testDataDir := filepath.Join(testTop, "data") err := os.MkdirAll(testDataDir, 0o777) assert.NoErrorf(t, err, "error creating initial structure %q", testDataDir) - log, _ := logger.NewTesting(tt.name) + log, _ := loggertest.New(tt.name) archiveFile, err := tt.args.archiveGenerator(t, tt.args.archiveFiles) require.NoError(t, err, "creation of test archive file failed") @@ -256,7 +256,7 @@ func TestUpgrader_unpackZip(t *testing.T) { testDataDir := filepath.Join(testTop, "data") err := os.MkdirAll(testDataDir, 0o777) assert.NoErrorf(t, err, "error creating initial structure %q", testDataDir) - log, _ := logger.NewTesting(tt.name) + log, _ := loggertest.New(tt.name) archiveFile, err := tt.args.archiveGenerator(t, tt.args.archiveFiles) require.NoError(t, err, "creation of test archive file failed") diff --git a/internal/pkg/agent/application/upgrade/upgrade_test.go b/internal/pkg/agent/application/upgrade/upgrade_test.go index bcb96f44cac..77d3a8a6c06 100644 --- a/internal/pkg/agent/application/upgrade/upgrade_test.go +++ b/internal/pkg/agent/application/upgrade/upgrade_test.go @@ -32,6 +32,7 @@ import ( "github.com/elastic/elastic-agent/pkg/control/v2/client" "github.com/elastic/elastic-agent/pkg/control/v2/cproto" "github.com/elastic/elastic-agent/pkg/core/logger" + "github.com/elastic/elastic-agent/pkg/core/logger/loggertest" agtversion "github.com/elastic/elastic-agent/pkg/version" mocks "github.com/elastic/elastic-agent/testing/mocks/pkg/control/v2/client" ) @@ -268,7 +269,7 @@ func TestUpgraderReload(t *testing.T) { // and a certificate from that CA and the keys. cfgyaml, want := prepareTestUpgraderReload() - log, _ := logger.NewTesting("") + log, _ := loggertest.New("") u := Upgrader{ log: log, settings: artifact.DefaultConfig(), @@ -521,7 +522,7 @@ agent.download: for _, tc := range tcs { t.Run(tc.name, func(t *testing.T) { - log, _ := logger.NewTesting("") + log, _ := loggertest.New("") u := Upgrader{ log: log, @@ -735,7 +736,7 @@ func TestIsSameVersion(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - log, _ := logger.NewTesting(test.name) + log, _ := loggertest.New(test.name) actualSame, actualNewVersion := isSameVersion(log, test.args.current, test.args.metadata, test.args.version) assert.Equal(t, test.want.same, actualSame, "Unexpected boolean comparison result: isSameVersion(%v, %v, %v, %v) should be %v", @@ -870,7 +871,7 @@ func TestWaitForWatcher(t *testing.T) { } }() - log, _ := logger.NewTesting(tt.name) + log, _ := loggertest.New(tt.name) tt.wantErr(t, waitForWatcherWithTimeoutCreationFunc(testCtx, log, updMarkerFilePath, fakeTimeout, createContextFunc), fmt.Sprintf("waitForWatcher %s, %v, %s, %s)", updMarkerFilePath, tt.states, tt.stateChangeInterval, fakeTimeout)) diff --git a/internal/pkg/agent/application/upgrade/watcher_test.go b/internal/pkg/agent/application/upgrade/watcher_test.go index 29e1194eb99..79004b07fba 100644 --- a/internal/pkg/agent/application/upgrade/watcher_test.go +++ b/internal/pkg/agent/application/upgrade/watcher_test.go @@ -17,8 +17,7 @@ import ( "github.com/elastic/elastic-agent/pkg/control/v2/client" "github.com/elastic/elastic-agent/pkg/control/v2/cproto" - - "github.com/elastic/elastic-agent/pkg/core/logger" + "github.com/elastic/elastic-agent/pkg/core/logger/loggertest" ) func TestWatcher_CannotConnect(t *testing.T) { @@ -27,7 +26,7 @@ func TestWatcher_CannotConnect(t *testing.T) { defer cancel() errCh := make(chan error) - logger, _ := logger.NewTesting("watcher") + logger, _ := loggertest.New("watcher") w := NewAgentWatcher(errCh, logger, 1*time.Millisecond) go w.Run(ctx) @@ -45,7 +44,7 @@ func TestWatcher_LostConnection(t *testing.T) { defer cancel() errCh := make(chan error) - logger, _ := logger.NewTesting("watcher") + logger, _ := loggertest.New("watcher") w := NewAgentWatcher(errCh, logger, 1*time.Millisecond) // error on watch (counts as lost connect) @@ -74,7 +73,7 @@ func TestWatcher_PIDChange(t *testing.T) { defer cancel() errCh := make(chan error) - logger, _ := logger.NewTesting("watcher") + logger, _ := loggertest.New("watcher") w := NewAgentWatcher(errCh, logger, 1*time.Millisecond) // error on watch (counts as lost connect) @@ -150,7 +149,7 @@ func TestWatcher_PIDChangeSuccess(t *testing.T) { defer cancel() errCh := make(chan error) - logger, _ := logger.NewTesting("watcher") + logger, _ := loggertest.New("watcher") w := NewAgentWatcher(errCh, logger, 1*time.Millisecond) // error on watch (counts as lost connect) @@ -236,7 +235,7 @@ func TestWatcher_AgentError(t *testing.T) { defer cancel() errCh := make(chan error) - logger, _ := logger.NewTesting("watcher") + logger, _ := loggertest.New("watcher") w := NewAgentWatcher(errCh, logger, 100*time.Millisecond) // reports only an error state, triggers failed @@ -275,17 +274,10 @@ func TestWatcher_AgentErrorQuick(t *testing.T) { defer cancel() errCh := make(chan error) - log, obs := logger.NewTesting("watcher") + log, obs := loggertest.New("watcher") defer func() { if t.Failed() { - rawLogs := obs.All() - for _, rawLog := range rawLogs { - msg := fmt.Sprintf("[%s] %s", rawLog.Level, rawLog.Message) - for k, v := range rawLog.ContextMap() { - msg += fmt.Sprintf("%s=%v", k, v) - } - t.Log(msg) - } + loggertest.PrintObservedLogs(obs.TakeAll(), t.Log) } }() w := NewAgentWatcher(errCh, log, 100*time.Millisecond) @@ -334,7 +326,7 @@ func TestWatcher_ComponentError(t *testing.T) { defer cancel() errCh := make(chan error) - logger, _ := logger.NewTesting("watcher") + logger, _ := loggertest.New("watcher") w := NewAgentWatcher(errCh, logger, 100*time.Millisecond) // reports only an error state, triggers failed @@ -394,7 +386,7 @@ func TestWatcher_ComponentErrorQuick(t *testing.T) { defer cancel() errCh := make(chan error) - logger, _ := logger.NewTesting("watcher") + logger, _ := loggertest.New("watcher") w := NewAgentWatcher(errCh, logger, 100*time.Millisecond) // reports an error state, followed by a healthy state (should not error) @@ -481,7 +473,7 @@ func TestWatcher_AgentErrorFlipFlop(t *testing.T) { defer cancel() errCh := make(chan error) - logger, _ := logger.NewTesting("watcher") + logger, _ := loggertest.New("watcher") w := NewAgentWatcher(errCh, logger, 300*time.Millisecond) // reports only an error state, triggers failed diff --git a/internal/pkg/agent/cmd/enroll_cmd_test.go b/internal/pkg/agent/cmd/enroll_cmd_test.go index a9597336760..da1725310f6 100644 --- a/internal/pkg/agent/cmd/enroll_cmd_test.go +++ b/internal/pkg/agent/cmd/enroll_cmd_test.go @@ -29,6 +29,7 @@ import ( "github.com/elastic/elastic-agent/internal/pkg/core/authority" "github.com/elastic/elastic-agent/internal/pkg/testutils" "github.com/elastic/elastic-agent/pkg/core/logger" + "github.com/elastic/elastic-agent/pkg/core/logger/loggertest" ) type mockStore struct { @@ -578,7 +579,7 @@ func TestDaemonReloadWithBackoff(t *testing.T) { } func TestWaitForFleetServer_timeout(t *testing.T) { - log, _ := logger.NewTesting("TestWaitForFleetServer_timeout") + log, _ := loggertest.New("TestWaitForFleetServer_timeout") timeout := 5 * time.Second testTimeout := 2 * timeout diff --git a/internal/pkg/agent/cmd/watch_test.go b/internal/pkg/agent/cmd/watch_test.go index 8a3494d042c..e71ce6c05de 100644 --- a/internal/pkg/agent/cmd/watch_test.go +++ b/internal/pkg/agent/cmd/watch_test.go @@ -11,13 +11,11 @@ import ( "github.com/elastic/elastic-agent/internal/pkg/agent/application/upgrade/details" "github.com/elastic/elastic-agent/internal/pkg/agent/errors" - "github.com/elastic/elastic-agent/internal/pkg/fleetapi" + "github.com/elastic/elastic-agent/pkg/core/logger/loggertest" "github.com/stretchr/testify/require" - "github.com/elastic/elastic-agent/pkg/core/logger" - "github.com/elastic/elastic-agent/internal/pkg/agent/application/upgrade" ) @@ -38,7 +36,7 @@ func TestInitUpgradeDetails(t *testing.T) { return errors.New("some error") } - log, obs := logger.NewTesting("initUpgradeDetails") + log, obs := loggertest.New("initUpgradeDetails") upgradeDetails := initUpgradeDetails(testMarker, mockSaveMarker, log) diff --git a/internal/pkg/agent/storage/store/migrations_test.go b/internal/pkg/agent/storage/store/migrations_test.go index bb55322dc1b..a26d26569fc 100644 --- a/internal/pkg/agent/storage/store/migrations_test.go +++ b/internal/pkg/agent/storage/store/migrations_test.go @@ -17,13 +17,13 @@ import ( "github.com/elastic/elastic-agent/internal/pkg/agent/application/paths" "github.com/elastic/elastic-agent/internal/pkg/agent/storage" "github.com/elastic/elastic-agent/internal/pkg/fleetapi" - "github.com/elastic/elastic-agent/pkg/core/logger" + "github.com/elastic/elastic-agent/pkg/core/logger/loggertest" ) func TestStoreMigrations(t *testing.T) { t.Run("action store file does not exists", func(t *testing.T) { ctx := context.Background() - log, _ := logger.NewTesting("") + log, _ := loggertest.New("") tempDir := t.TempDir() oldActionStorePath := filepath.Join(tempDir, "action_store.yml") @@ -46,7 +46,7 @@ func TestStoreMigrations(t *testing.T) { t.Run("action store is empty", func(t *testing.T) { ctx := context.Background() - log, _ := logger.NewTesting("") + log, _ := loggertest.New("") tempDir := t.TempDir() oldActionStorePath := filepath.Join(tempDir, "action_store.yml") @@ -127,7 +127,7 @@ func TestStoreMigrations(t *testing.T) { for _, tc := range tcs { t.Run(tc.name, func(t *testing.T) { ctx := context.Background() - log, _ := logger.NewTesting("") + log, _ := loggertest.New("") tempDir := t.TempDir() vaultPath := createAgentVaultAndSecret(t, ctx, tempDir) @@ -291,7 +291,7 @@ func TestStoreMigrations(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx := context.Background() - log, _ := logger.NewTesting("") + log, _ := loggertest.New("") tempDir := t.TempDir() vaultPath := createAgentVaultAndSecret(t, ctx, tempDir) @@ -322,7 +322,7 @@ func TestStoreMigrations(t *testing.T) { t.Run("YAML state store containing an ActionPolicyChange to JSON state store", func(t *testing.T) { ctx := context.Background() - log, _ := logger.NewTesting("") + log, _ := loggertest.New("") want := state{ Version: "1", @@ -405,7 +405,7 @@ func TestStoreMigrations(t *testing.T) { }) t.Run("YAML state store when JSON state store exists", func(t *testing.T) { - log, _ := logger.NewTesting("") + log, _ := loggertest.New("") ctx := context.Background() @@ -494,7 +494,7 @@ func TestStoreMigrations(t *testing.T) { t.Run("newStateStoreWithMigration", func(t *testing.T) { t.Run("action store exists", func(t *testing.T) { ctx := context.Background() - log, _ := logger.NewTesting("") + log, _ := loggertest.New("") want := &fleetapi.ActionPolicyChange{ ActionID: "abc123", @@ -550,7 +550,7 @@ func TestStoreMigrations(t *testing.T) { t.Run("YAML state store to JSON state store", func(t *testing.T) { ctx := context.Background() - log, _ := logger.NewTesting("") + log, _ := loggertest.New("") want := state{ Version: "1", @@ -629,7 +629,7 @@ func TestStoreMigrations(t *testing.T) { }) t.Run("up to date store, no migration needed", func(t *testing.T) { - log, _ := logger.NewTesting("") + log, _ := loggertest.New("") ctx := context.Background() @@ -712,7 +712,7 @@ func TestStoreMigrations(t *testing.T) { t.Run("no store exists", func(t *testing.T) { ctx := context.Background() - log, _ := logger.NewTesting("") + log, _ := loggertest.New("") tempDir := t.TempDir() paths.SetConfig(tempDir) @@ -737,7 +737,7 @@ func TestStoreMigrations(t *testing.T) { t.Run("NewStateStoreWithMigration", func(t *testing.T) { t.Run("return error if action store is invalid", func(t *testing.T) { ctx := context.Background() - log, _ := logger.NewTesting("") + log, _ := loggertest.New("") tempDir := t.TempDir() oldActionStorePath := filepath.Join(tempDir, "action_store.yml") @@ -755,7 +755,7 @@ func TestStoreMigrations(t *testing.T) { t.Run("returns error if YAML state store is invalid", func(t *testing.T) { ctx := context.Background() - log, _ := logger.NewTesting("") + log, _ := loggertest.New("") tempDir := t.TempDir() paths.SetConfig(tempDir) @@ -778,7 +778,7 @@ func TestStoreMigrations(t *testing.T) { // Therefore, the error is regarding invalid YAML and not invalid JSON. ctx := context.Background() - log, _ := logger.NewTesting("") + log, _ := loggertest.New("") tempDir := t.TempDir() paths.SetConfig(tempDir) diff --git a/internal/pkg/fleetapi/client/client_test.go b/internal/pkg/fleetapi/client/client_test.go index 4baf3c13eeb..e91f3b92a4b 100644 --- a/internal/pkg/fleetapi/client/client_test.go +++ b/internal/pkg/fleetapi/client/client_test.go @@ -19,7 +19,7 @@ import ( "github.com/elastic/elastic-agent/internal/pkg/config" "github.com/elastic/elastic-agent/internal/pkg/remote" - "github.com/elastic/elastic-agent/pkg/core/logger" + "github.com/elastic/elastic-agent/pkg/core/logger/loggertest" ) func TestHTTPClient(t *testing.T) { @@ -170,7 +170,7 @@ func TestElasticApiVersion(t *testing.T) { ts := httptest.NewServer(mux) defer ts.Close() - testLogger, _ := logger.NewTesting("testElasticApiVersion") + testLogger, _ := loggertest.New("testElasticApiVersion") clt, err := NewWithConfig(testLogger, remote.Config{ Hosts: []string{ts.URL}, @@ -198,7 +198,7 @@ func TestElasticApiVersion(t *testing.T) { ts := httptest.NewServer(mux) defer ts.Close() - testLogger, obsLogs := logger.NewTesting("testElasticApiVersion") + testLogger, obsLogs := loggertest.New("testElasticApiVersion") clt, err := NewWithConfig(testLogger, remote.Config{ Hosts: []string{ts.URL}, @@ -229,7 +229,7 @@ func TestElasticApiVersion(t *testing.T) { ts := httptest.NewServer(mux) defer ts.Close() - testLogger, obsLogs := logger.NewTesting("testElasticApiVersion") + testLogger, obsLogs := loggertest.New("testElasticApiVersion") clt, err := NewWithConfig(testLogger, remote.Config{ Hosts: []string{ts.URL}, @@ -260,7 +260,7 @@ func TestElasticApiVersion(t *testing.T) { ts := httptest.NewServer(mux) defer ts.Close() - testLogger, obsLogs := logger.NewTesting("testElasticApiVersion") + testLogger, obsLogs := loggertest.New("testElasticApiVersion") clt, err := NewWithConfig(testLogger, remote.Config{ Hosts: []string{ts.URL}, diff --git a/pkg/component/runtime/manager_fake_input_test.go b/pkg/component/runtime/manager_fake_input_test.go index 98288df3ced..a54f4a7d2d6 100644 --- a/pkg/component/runtime/manager_fake_input_test.go +++ b/pkg/component/runtime/manager_fake_input_test.go @@ -24,14 +24,14 @@ import ( "google.golang.org/protobuf/encoding/protojson" gproto "google.golang.org/protobuf/proto" - fakecmp "github.com/elastic/elastic-agent/pkg/component/fake/component/comp" - "github.com/elastic/elastic-agent/pkg/core/logger" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "go.elastic.co/apm/v2/apmtest" + fakecmp "github.com/elastic/elastic-agent/pkg/component/fake/component/comp" + "github.com/elastic/elastic-agent/pkg/core/logger/loggertest" + "github.com/elastic/elastic-agent-client/v7/pkg/client" "github.com/elastic/elastic-agent-client/v7/pkg/proto" @@ -2548,7 +2548,7 @@ func (suite *FakeInputSuite) TestManager_StartStopComponent() { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - log, logs := logger.NewTesting("TestManager_StartStopComponent") + log, logs := loggertest.New("TestManager_StartStopComponent") ai := &info.AgentInfo{} m, err := NewManager( log, diff --git a/pkg/core/logger/loggertest/logger.go b/pkg/core/logger/loggertest/logger.go new file mode 100644 index 00000000000..bdf8e9abe93 --- /dev/null +++ b/pkg/core/logger/loggertest/logger.go @@ -0,0 +1,42 @@ +// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one +// or more contributor license agreements. Licensed under the Elastic License; +// you may not use this file except in compliance with the Elastic License. + +package loggertest + +import ( + "fmt" + + "go.uber.org/zap" + "go.uber.org/zap/zapcore" + "go.uber.org/zap/zaptest/observer" + + "github.com/elastic/elastic-agent-libs/logp" + "github.com/elastic/elastic-agent/pkg/core/logger" +) + +// New creates a testing logger that buffers the logs in memory and +// logs in debug level. Check observer.ObservedLogs for more details. +func New(name string) (*logger.Logger, *observer.ObservedLogs) { + core, obs := observer.New(zapcore.DebugLevel) + + log := logp.NewLogger( + name, + zap.WrapCore(func(in zapcore.Core) zapcore.Core { + return zapcore.NewTee(in, core) + })) + + return log, obs +} + +// PrintObservedLogs formats and prints all log entries in logs, one at a time +// using printFn. +func PrintObservedLogs(logs []observer.LoggedEntry, printFn func(a ...any)) { + for _, l := range logs { + msg := fmt.Sprintf("[%s] %s", l.Level, l.Message) + for k, v := range l.ContextMap() { + msg += fmt.Sprintf(" %s=%v", k, v) + } + printFn(msg) + } +} diff --git a/pkg/core/logger/loggertest/logger_test.go b/pkg/core/logger/loggertest/logger_test.go new file mode 100644 index 00000000000..73abefdecab --- /dev/null +++ b/pkg/core/logger/loggertest/logger_test.go @@ -0,0 +1,34 @@ +// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one +// or more contributor license agreements. Licensed under the Elastic License; +// you may not use this file except in compliance with the Elastic License. + +package loggertest + +import "fmt" + +func ExamplePrintObservedLogs() { + logger, obs := New("testLogger") + + logger.Debug("a debug message") + logger.Debugw("a debug message with keys", "key2", 42) + logger.Infow("an info message") + logger.Infow("an info message with keys", "key1", "value1") + logger.Warn("a warn message") + logger.Warnw("a warn message with keys", "key2", 42) + logger.Error("an error message") + logger.Errorw("an error message with keys", "key1", "value1") + + printFn := func(a ...any) { fmt.Println(a...) } + + PrintObservedLogs(obs.TakeAll(), printFn) + + // Output: + // [debug] a debug message + // [debug] a debug message with keys key2=42 + // [info] an info message + // [info] an info message with keys key1=value1 + // [warn] a warn message + // [warn] a warn message with keys key2=42 + // [error] an error message + // [error] an error message with keys key1=value1 +} diff --git a/pkg/core/logger/testing.go b/pkg/core/logger/testing.go deleted file mode 100644 index a303584b067..00000000000 --- a/pkg/core/logger/testing.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one -// or more contributor license agreements. Licensed under the Elastic License; -// you may not use this file except in compliance with the Elastic License. - -package logger - -import ( - "go.uber.org/zap" - "go.uber.org/zap/zapcore" - "go.uber.org/zap/zaptest/observer" - - "github.com/elastic/elastic-agent-libs/logp" -) - -// NewTesting creates a testing logger that buffers the logs in memory and -// logs in debug level. Check observer.ObservedLogs for more details. -func NewTesting(name string) (*Logger, *observer.ObservedLogs) { - core, obs := observer.New(zapcore.DebugLevel) - - logger := logp.NewLogger( - name, - zap.WrapCore(func(in zapcore.Core) zapcore.Core { - return zapcore.NewTee(in, core) - })) - return logger, obs -}