Skip to content

Commit 3950425

Browse files
committed
logging#Config: Implement SetDefaults() to configure Output
Previously, logging output was configured in `Validate()` if not set, which is inappropriate. It is now handled by implementing the `SetDefaults()` interface from the `defaults` package.
1 parent 64c2634 commit 3950425

File tree

2 files changed

+14
-14
lines changed

2 files changed

+14
-14
lines changed

logging/config.go

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package logging
22

33
import (
44
"fmt"
5+
"github.com/creasty/defaults"
56
"github.com/pkg/errors"
67
"go.uber.org/zap/zapcore"
78
"os"
@@ -49,28 +50,29 @@ type Config struct {
4950
Options `yaml:"options" env:"OPTIONS"`
5051
}
5152

52-
// Validate checks constraints in the configuration and returns an error if they are violated.
53-
// Also configures the log output if it is not configured:
53+
// SetDefaults implements defaults.Setter to configure the log output if it is not set:
5454
// systemd-journald is used when Icinga DB is running under systemd, otherwise stderr.
55-
func (l *Config) Validate() error {
56-
if l.Interval <= 0 {
57-
return errors.New("periodic logging interval must be positive")
58-
}
59-
60-
if l.Output == "" {
55+
func (c *Config) SetDefaults() {
56+
if defaults.CanUpdate(c.Output) {
6157
if _, ok := os.LookupEnv("NOTIFY_SOCKET"); ok {
6258
// When started by systemd, NOTIFY_SOCKET is set by systemd for Type=notify supervised services,
6359
// which is the default setting for the Icinga DB service.
6460
// This assumes that Icinga DB is running under systemd, so set output to systemd-journald.
65-
l.Output = JOURNAL
61+
c.Output = JOURNAL
6662
} else {
6763
// Otherwise set it to console, i.e. write log messages to stderr.
68-
l.Output = CONSOLE
64+
c.Output = CONSOLE
6965
}
7066
}
67+
}
68+
69+
// Validate checks constraints in the configuration and returns an error if they are violated.
70+
func (c *Config) Validate() error {
71+
if c.Interval <= 0 {
72+
return errors.New("periodic logging interval must be positive")
73+
}
7174

72-
// To be on the safe side, always call AssertOutput.
73-
return AssertOutput(l.Output)
75+
return AssertOutput(c.Output)
7476
}
7577

7678
// AssertOutput returns an error if output is not a valid logger output.

logging/config_test.go

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,6 @@ import (
1515
func TestConfig(t *testing.T) {
1616
var defaultConfig Config
1717
require.NoError(t, defaults.Set(&defaultConfig), "setting default config")
18-
// Validate also sets default values.
19-
require.NoError(t, defaultConfig.Validate(), "setting default config")
2018

2119
configTests := []testutils.TestCase[Config, testutils.ConfigTestData]{
2220
{

0 commit comments

Comments
 (0)