Skip to content

Commit

Permalink
flow/logging: check for nil values when writing logs (#6561)
Browse files Browse the repository at this point in the history
There may be situations where the flow mode logger receivers a nil
value, potentially due to misconfiguration or a component which exports
its values only after being ran.

Fixes #6557.
  • Loading branch information
rfratto authored Feb 29, 2024
1 parent 0dde507 commit bcc9b0a
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ Main (unreleased)

- Fix an issue where a custom component might be wired to a local declare instead of an import declare when they have the same label. (@wildum)

- Fix an issue where flow mode panics if the `logging` config block is given a `null` Loki receiver to write log entries to. (@rfratto)

v0.40.0 (2024-02-27)
--------------------

Expand Down
9 changes: 9 additions & 0 deletions pkg/flow/logging/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,15 @@ type lokiWriter struct {

func (fw *lokiWriter) Write(p []byte) (int, error) {
for _, receiver := range fw.f {
// We may have been given a nil value in rare circumstances due to
// misconfiguration or a component which generates exports after
// construction.
//
// Ignore nil values so we don't panic.
if receiver == nil {
continue
}

select {
case receiver.Chan() <- loki.Entry{
Labels: model.LabelSet{"component": "agent"},
Expand Down
20 changes: 20 additions & 0 deletions pkg/flow/logging/logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (

"github.com/go-kit/log"
gokitlevel "github.com/go-kit/log/level"
"github.com/grafana/agent/component/common/loki"
"github.com/grafana/agent/pkg/flow/logging"
flowlevel "github.com/grafana/agent/pkg/flow/logging/level"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -165,6 +166,25 @@ func TestLevels(t *testing.T) {
}
}

// Test_lokiWriter_nil ensures that writing to a lokiWriter doesn't panic when
// given a nil receiver.
func Test_lokiWriter_nil(t *testing.T) {
logger, err := logging.New(io.Discard, debugLevel())
require.NoError(t, err)

err = logger.Update(logging.Options{
Level: logging.LevelDebug,
Format: logging.FormatLogfmt,

WriteTo: []loki.LogsReceiver{nil},
})
require.NoError(t, err)

require.NotPanics(t, func() {
_ = logger.Log("msg", "test message")
})
}

func BenchmarkLogging_NoLevel_Prints(b *testing.B) {
logger, err := logging.New(io.Discard, infoLevel())
require.NoError(b, err)
Expand Down

0 comments on commit bcc9b0a

Please sign in to comment.