Skip to content

Commit f1ee2e1

Browse files
authored
[8.19](backport #43356) [Chore][libbeat] Replace global logger with single logger instance (#44684)
* [Chore][libbeat] Replace global logger with single logger instance (#43356)
1 parent f288ff0 commit f1ee2e1

File tree

23 files changed

+185
-127
lines changed

23 files changed

+185
-127
lines changed

filebeat/tests/integration/filebeat_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ func TestFilebeatRunsAndLogsJSONToFile(t *testing.T) {
8787
line := r.Bytes()
8888
m := map[string]any{}
8989
if err := json.Unmarshal(line, &m); err != nil {
90-
t.Fatalf("line %d is not a valid JSON: %s", count, err)
90+
t.Fatalf("line %d is not a valid JSON: %s: %s", count, err, string(line))
9191
}
9292
count++
9393
}

libbeat/api/server.go

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,6 @@ type Server struct {
4141

4242
// New creates a new API Server with no routes attached.
4343
func New(log *logp.Logger, config *config.C) (*Server, error) {
44-
if log == nil {
45-
log = logp.NewLogger("")
46-
}
47-
4844
cfg := DefaultConfig
4945
err := config.Unpack(&cfg)
5046
if err != nil {

libbeat/api/server_test.go

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,11 @@ import (
3131
"github.com/stretchr/testify/require"
3232

3333
"github.com/elastic/elastic-agent-libs/config"
34+
"github.com/elastic/elastic-agent-libs/logp/logptest"
3435
)
3536

3637
func TestConfiguration(t *testing.T) {
38+
logger := logptest.NewTestingLogger(t, "")
3739
if runtime.GOOS != "windows" {
3840
t.Skip("Check for User and Security Descriptor")
3941
return
@@ -44,7 +46,7 @@ func TestConfiguration(t *testing.T) {
4446
"user": "admin",
4547
})
4648

47-
_, err := New(nil, cfg)
49+
_, err := New(logger, cfg)
4850
require.Error(t, err)
4951
})
5052

@@ -54,12 +56,14 @@ func TestConfiguration(t *testing.T) {
5456
"security_descriptor": "D:P(A;;GA;;;1234)",
5557
})
5658

57-
_, err := New(nil, cfg)
59+
_, err := New(logger, cfg)
5860
require.Error(t, err)
5961
})
6062
}
6163

6264
func TestSocket(t *testing.T) {
65+
logger := logptest.NewTestingLogger(t, "")
66+
6367
if runtime.GOOS == "windows" {
6468
t.Skip("Unix Sockets don't work under windows")
6569
return
@@ -87,7 +91,7 @@ func TestSocket(t *testing.T) {
8791
"host": "unix://" + sockFile,
8892
})
8993

90-
s, err := New(nil, cfg)
94+
s, err := New(logger, cfg)
9195
require.NoError(t, err)
9296
attachEchoHelloHandler(t, s)
9397
go s.Start()
@@ -130,7 +134,7 @@ func TestSocket(t *testing.T) {
130134
"host": "unix://" + sockFile,
131135
})
132136

133-
s, err := New(nil, cfg)
137+
s, err := New(logger, cfg)
134138
require.NoError(t, err)
135139
attachEchoHelloHandler(t, s)
136140
go s.Start()
@@ -166,8 +170,8 @@ func TestHTTP(t *testing.T) {
166170
cfg := config.MustNewConfigFrom(map[string]interface{}{
167171
"host": url,
168172
})
169-
170-
s, err := New(nil, cfg)
173+
logger := logptest.NewTestingLogger(t, "")
174+
s, err := New(logger, cfg)
171175
require.NoError(t, err)
172176
attachEchoHelloHandler(t, s)
173177
go s.Start()
@@ -198,7 +202,8 @@ func TestAttachHandler(t *testing.T) {
198202
"host": "http://localhost:0",
199203
})
200204

201-
s, err := New(nil, cfg)
205+
logger := logptest.NewTestingLogger(t, "")
206+
s, err := New(logger, cfg)
202207
require.NoError(t, err)
203208

204209
req := httptest.NewRequest(http.MethodGet, "http://"+s.l.Addr().String()+"/test", nil)

libbeat/beat/info.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import (
2323
"github.com/gofrs/uuid/v5"
2424
"go.opentelemetry.io/collector/consumer"
2525

26+
"github.com/elastic/elastic-agent-libs/logp"
2627
"github.com/elastic/elastic-agent-libs/monitoring"
2728
)
2829

@@ -46,6 +47,7 @@ type Info struct {
4647
Monitoring Monitoring
4748
LogConsumer consumer.Logs // otel log consumer
4849
UseDefaultProcessors bool // Whether to use the default processors
50+
Logger *logp.Logger
4951
}
5052

5153
type Monitoring struct {

libbeat/cmd/instance/beat.go

Lines changed: 47 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -175,8 +175,6 @@ func defaultCertReloadConfig() certReloadConfig {
175175
}
176176
}
177177

178-
var debugf = logp.MakeDebug("beat")
179-
180178
// Run initializes and runs a Beater implementation. name is the name of the
181179
// Beat (e.g. packetbeat or metricbeat). version is version number of the Beater
182180
// implementation. bt is the `Creator` callback for creating a new beater
@@ -329,9 +327,9 @@ func (b *Beat) createBeater(bt beat.Creator) (beat.Beater, error) {
329327
return nil, err
330328
}
331329

332-
log := logp.NewLogger("beat")
330+
log := b.Info.Logger.Named("beat")
333331
log.Infof("Setup Beat: %s; Version: %s", b.Info.Beat, b.Info.Version)
334-
b.logSystemInfo(log)
332+
b.logSystemInfo()
335333

336334
err = b.registerESVersionCheckCallback()
337335
if err != nil {
@@ -350,7 +348,7 @@ func (b *Beat) createBeater(bt beat.Creator) (beat.Beater, error) {
350348
reg = monitoring.Default.NewRegistry("libbeat")
351349
}
352350

353-
err = metricreport.SetupMetrics(logp.NewLogger("metrics"), b.Info.Beat, version.GetDefaultVersion())
351+
err = metricreport.SetupMetrics(b.Beat.Info.Logger.Named("metrics"), b.Info.Beat, version.GetDefaultVersion())
354352
if err != nil {
355353
return nil, err
356354
}
@@ -359,14 +357,14 @@ func (b *Beat) createBeater(bt beat.Creator) (beat.Beater, error) {
359357
mgmt := b.Info.Monitoring.StateRegistry.NewRegistry("management")
360358
monitoring.NewBool(mgmt, "enabled").Set(b.Manager.Enabled())
361359

362-
debugf("Initializing output plugins")
360+
log.Debug("Initializing output plugins")
363361
outputEnabled := b.Config.Output.IsSet() && b.Config.Output.Config().Enabled()
364362
if !outputEnabled {
365363
if b.Manager.Enabled() {
366-
logp.Info("Output is configured through Central Management")
364+
b.Info.Logger.Info("Output is configured through Central Management")
367365
} else {
368366
msg := "no outputs are defined, please define one under the output section"
369-
logp.Info("%s", msg)
367+
b.Info.Logger.Info("%s", msg)
370368
return nil, errors.New(msg)
371369
}
372370
}
@@ -375,7 +373,7 @@ func (b *Beat) createBeater(bt beat.Creator) (beat.Beater, error) {
375373
monitors := pipeline.Monitors{
376374
Metrics: reg,
377375
Telemetry: b.Info.Monitoring.StateRegistry,
378-
Logger: logp.L().Named("publisher"),
376+
Logger: b.Info.Logger.Named("publisher"),
379377
Tracer: b.Instrumentation.Tracer(),
380378
}
381379
outputFactory := b.MakeOutputFactory(b.Config.Output)
@@ -404,14 +402,15 @@ func (b *Beat) createBeater(bt beat.Creator) (beat.Beater, error) {
404402
}
405403

406404
func (b *Beat) launch(settings Settings, bt beat.Creator) error {
405+
logger := b.Info.Logger
407406
defer func() {
408-
_ = logp.Sync()
407+
_ = logger.Sync()
409408
}()
410-
defer logp.Info("%s stopped.", b.Info.Beat)
409+
defer logger.Infof("%s stopped.", b.Info.Beat)
411410

412411
defer func() {
413412
if err := b.processors.Close(); err != nil {
414-
logp.Warn("Failed to close global processing: %v", err)
413+
logger.Warnf("Failed to close global processing: %v", err)
415414
}
416415
}()
417416

@@ -433,7 +432,7 @@ func (b *Beat) launch(settings Settings, bt beat.Creator) error {
433432
_ = bl.Unlock()
434433
}()
435434
} else {
436-
logp.Info("running under elastic-agent, per-beat lockfiles disabled")
435+
logger.Info("running under elastic-agent, per-beat lockfiles disabled")
437436
}
438437

439438
svc.BeforeRun()
@@ -446,7 +445,7 @@ func (b *Beat) launch(settings Settings, bt beat.Creator) error {
446445
// that would be set at runtime.
447446
if b.Config.HTTP.Enabled() {
448447
var err error
449-
b.API, err = api.NewWithDefaultRoutes(logp.NewLogger(""), b.Config.HTTP, api.NamespaceLookupFunc())
448+
b.API, err = api.NewWithDefaultRoutes(logger, b.Config.HTTP, api.NamespaceLookupFunc())
450449
if err != nil {
451450
return fmt.Errorf("could not start the HTTP server for the API: %w", err)
452451
}
@@ -530,7 +529,7 @@ func (b *Beat) launch(settings Settings, bt beat.Creator) error {
530529
return err
531530
}
532531

533-
logp.Info("%s start running.", b.Info.Beat)
532+
logger.Infof("%s start running.", b.Info.Beat)
534533

535534
err = beater.Run(&b.Beat)
536535
if b.shouldReexec {
@@ -776,12 +775,6 @@ func (b *Beat) configure(settings Settings) error {
776775
config.OverwriteConfigOpts(configOptsWithKeystore(store))
777776
}
778777

779-
instrumentation, err := instrumentation.New(cfg, b.Info.Beat, b.Info.Version)
780-
if err != nil {
781-
return err
782-
}
783-
b.Beat.Instrumentation = instrumentation
784-
785778
b.keystore = store
786779
b.Beat.Keystore = store
787780
err = cloudid.OverwriteSettings(cfg)
@@ -795,7 +788,7 @@ func (b *Beat) configure(settings Settings) error {
795788
return fmt.Errorf("error unpacking config data: %w", err)
796789
}
797790

798-
if err := PromoteOutputQueueSettings(&b.Config); err != nil {
791+
if err := PromoteOutputQueueSettings(b); err != nil {
799792
return fmt.Errorf("could not promote output queue settings: %w", err)
800793
}
801794

@@ -814,20 +807,30 @@ func (b *Beat) configure(settings Settings) error {
814807
return fmt.Errorf("error setting timestamp precision: %w", err)
815808
}
816809

817-
if err := configure.LoggingWithTypedOutputs(b.Info.Beat, b.Config.Logging, b.Config.EventLogging, logp.TypeKey, logp.EventType); err != nil {
810+
b.Info.Logger, err = configure.LoggingWithTypedOutputsLocal(b.Info.Beat, b.Config.Logging, b.Config.EventLogging, logp.TypeKey, logp.EventType)
811+
if err != nil {
818812
return fmt.Errorf("error initializing logging: %w", err)
819813
}
820814

815+
// extracting here for ease of use
816+
logger := b.Info.Logger
817+
818+
instrumentation, err := instrumentation.New(cfg, b.Info.Beat, b.Info.Version, b.Info.Logger)
819+
if err != nil {
820+
return err
821+
}
822+
b.Beat.Instrumentation = instrumentation
823+
821824
// log paths values to help with troubleshooting
822-
logp.Info("%s", paths.Paths.String())
825+
logger.Infof("%s", paths.Paths.String())
823826

824827
metaPath := paths.Resolve(paths.Data, "meta.json")
825828
err = b.LoadMeta(metaPath)
826829
if err != nil {
827830
return err
828831
}
829832

830-
logp.Info("Beat ID: %v", b.Info.ID)
833+
logger.Infof("Beat ID: %v", b.Info.ID)
831834

832835
// Try to get the host's FQDN and set it.
833836
h, err := sysinfo.Host()
@@ -842,7 +845,7 @@ func (b *Beat) configure(settings Settings) error {
842845
if err != nil {
843846
// FQDN lookup is "best effort". We log the error, fallback to
844847
// the OS-reported hostname, and move on.
845-
logp.Warn("unable to lookup FQDN: %s, using hostname = %s as FQDN", err.Error(), b.Info.Hostname)
848+
logger.Infof("unable to lookup FQDN: %s, using hostname = %s as FQDN", err.Error(), b.Info.Hostname)
846849
b.Info.FQDN = b.Info.Hostname
847850
} else {
848851
b.Info.FQDN = fqdn
@@ -877,11 +880,11 @@ func (b *Beat) configure(settings Settings) error {
877880
}
878881

879882
if maxProcs := b.Config.MaxProcs; maxProcs > 0 {
880-
logp.Info("Set max procs limit: %v", maxProcs)
883+
logger.Infof("Set max procs limit: %v", maxProcs)
881884
runtime.GOMAXPROCS(maxProcs)
882885
}
883886
if gcPercent := b.Config.GCPercent; gcPercent > 0 {
884-
logp.Info("Set gc percentage to: %v", gcPercent)
887+
logger.Infof("Set gc percentage to: %v", gcPercent)
885888
debug.SetGCPercent(gcPercent)
886889
}
887890

@@ -894,9 +897,9 @@ func (b *Beat) configure(settings Settings) error {
894897

895898
imFactory := settings.IndexManagement
896899
if imFactory == nil {
897-
imFactory = idxmgmt.MakeDefaultSupport(settings.ILM)
900+
imFactory = idxmgmt.MakeDefaultSupport(settings.ILM, logger)
898901
}
899-
b.IdxSupporter, err = imFactory(nil, b.Beat.Info, b.RawConfig)
902+
b.IdxSupporter, err = imFactory(logger, b.Beat.Info, b.RawConfig)
900903
if err != nil {
901904
return err
902905
}
@@ -905,7 +908,7 @@ func (b *Beat) configure(settings Settings) error {
905908
if processingFactory == nil {
906909
processingFactory = processing.MakeDefaultBeatSupport(true)
907910
}
908-
b.processors, err = processingFactory(b.Info, logp.L().Named("processors"), b.RawConfig)
911+
b.processors, err = processingFactory(b.Info, logger.Named("processors"), b.RawConfig)
909912

910913
b.Manager.RegisterDiagnosticHook("global processors", "a list of currently configured global beat processors",
911914
"global_processors.txt", "text/plain", b.agentDiagnosticHook)
@@ -914,7 +917,7 @@ func (b *Beat) configure(settings Settings) error {
914917
m := monitoring.CollectStructSnapshot(monitoring.Default, monitoring.Full, true)
915918
data, err := json.MarshalIndent(m, "", " ")
916919
if err != nil {
917-
logp.L().Warnw("Failed to collect beat metric snapshot for Agent diagnostics.", "error", err)
920+
logger.Warnw("Failed to collect beat metric snapshot for Agent diagnostics.", "error", err)
918921
return []byte(err.Error())
919922
}
920923
return data
@@ -943,7 +946,7 @@ func (b *Beat) LoadMeta(metaPath string) error {
943946
FirstStart time.Time `json:"first_start"`
944947
}
945948

946-
logp.Debug("beat", "Beat metadata path: %v", metaPath)
949+
b.Info.Logger.Debugf("beat", "Beat metadata path: %v", metaPath)
947950

948951
f, err := openRegular(metaPath)
949952
if err != nil && !os.IsNotExist(err) {
@@ -1065,7 +1068,7 @@ func (b *Beat) loadDashboards(ctx context.Context, force bool) error {
10651068
if err != nil {
10661069
return fmt.Errorf("error importing Kibana dashboards: %w", err)
10671070
}
1068-
logp.Info("Kibana dashboards successfully loaded.")
1071+
b.Info.Logger.Info("Kibana dashboards successfully loaded.")
10691072
}
10701073

10711074
return nil
@@ -1171,7 +1174,7 @@ func (b *Beat) MakeOutputFactory(
11711174
}
11721175

11731176
func (b *Beat) reloadOutputOnCertChange(cfg config.Namespace) error {
1174-
logger := logp.L().Named("ssl.cert.reloader")
1177+
logger := b.Info.Logger.Named("ssl.cert.reloader")
11751178
// Here the output is created and we have access to the Beat struct (with the manager)
11761179
// as a workaround we can unpack the new settings and trigger the reload-watcher from here
11771180

@@ -1360,8 +1363,9 @@ func handleError(err error) error {
13601363
// in debugging. This information includes data about the beat, build, go
13611364
// runtime, host, and process. If any of the data is not available it will be
13621365
// omitted.
1363-
func (b *Beat) logSystemInfo(log *logp.Logger) {
1364-
defer logp.Recover("An unexpected error occurred while collecting " +
1366+
func (b *Beat) logSystemInfo() {
1367+
log := b.Beat.Info.Logger
1368+
defer log.Recover("An unexpected error occurred while collecting " +
13651369
"information about the system.")
13661370
log = log.With(logp.Namespace("system_info"))
13671371

@@ -1527,21 +1531,21 @@ func sanitizeIPs(ips []string) []string {
15271531
return validIPs
15281532
}
15291533

1530-
// promoteOutputQueueSettings checks to see if the output
1534+
// PromoteOutputQueueSettings checks to see if the output
15311535
// configuration has queue settings defined and if so it promotes them
15321536
// to the top level queue settings. This is done to allow existing
15331537
// behavior of specifying queue settings at the top level or like
15341538
// elastic-agent that specifies queue settings under the output
1535-
func PromoteOutputQueueSettings(bc *beatConfig) error {
1536-
if bc.Output.IsSet() && bc.Output.Config().Enabled() {
1539+
func PromoteOutputQueueSettings(b *Beat) error {
1540+
if b.Config.Output.IsSet() && b.Config.Output.Config().Enabled() {
15371541
pc := pipeline.Config{}
1538-
err := bc.Output.Config().Unpack(&pc)
1542+
err := b.Config.Output.Config().Unpack(&pc)
15391543
if err != nil {
15401544
return fmt.Errorf("error unpacking output queue settings: %w", err)
15411545
}
15421546
if pc.Queue.IsSet() {
1543-
logp.Info("global queue settings replaced with output queue settings")
1544-
bc.Pipeline.Queue = pc.Queue
1547+
b.Info.Logger.Info("global queue settings replaced with output queue settings")
1548+
b.Config.Pipeline.Queue = pc.Queue
15451549
}
15461550
}
15471551
return nil

0 commit comments

Comments
 (0)