Skip to content

Commit

Permalink
feat: add journald-friendly log format
Browse files Browse the repository at this point in the history
Pass structured log data to journald using its native protocol [1].

[1] https://systemd.io/JOURNAL_NATIVE_PROTOCOL/

Signed-off-by: Michael Adler <[email protected]>
  • Loading branch information
michaeladler committed Feb 24, 2025
1 parent 8cc2b1f commit be3b387
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
2 changes: 1 addition & 1 deletion cmd/wfx/cmd/config/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ func NewFlagset() *pflag.FlagSet {

allLevels := []string{zerolog.TraceLevel.String(), zerolog.DebugLevel.String(), zerolog.InfoLevel.String(), zerolog.WarnLevel.String(), zerolog.ErrorLevel.String(), zerolog.FatalLevel.String(), zerolog.PanicLevel.String()}
f.String(LogLevelFlag, "info", fmt.Sprintf("set log level. one of: [%s]", strings.Join(allLevels, ", ")))
f.String(LogFormatFlag, "auto", "log format; possible values: json, pretty, auto")
f.String(LogFormatFlag, "auto", "log format; possible values: json, pretty, journald, auto")
return f
}

Expand Down
16 changes: 13 additions & 3 deletions cmd/wfx/cmd/root/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ import (
"os"
"time"

"github.com/coreos/go-systemd/v22/journal"
"github.com/rs/zerolog"
"github.com/rs/zerolog/journald"
"github.com/rs/zerolog/log"
"golang.org/x/term"
)
Expand All @@ -26,19 +28,27 @@ func setupLogging(out *os.File, format string, lvl zerolog.Level) {
if term.IsTerminal(int(out.Fd())) {
format = "pretty"
} else {
format = "json"
if ok, _ := journal.StderrIsJournalStream(); ok {
format = "journald"

Check warning on line 32 in cmd/wfx/cmd/root/setup.go

View check run for this annotation

Codecov / codecov/patch

cmd/wfx/cmd/root/setup.go#L32

Added line #L32 was not covered by tests
} else {
format = "json"
}
}
}
switch format {
case "json":
logger = zerolog.New(out).With().Caller().Logger()
logger = zerolog.New(out)
case "pretty":
logger = zerolog.New(zerolog.ConsoleWriter{
Out: out,
TimeFormat: time.Stamp,
})
case "journald":
logger = zerolog.New(journald.NewJournalDWriter())

Check warning on line 47 in cmd/wfx/cmd/root/setup.go

View check run for this annotation

Codecov / codecov/patch

cmd/wfx/cmd/root/setup.go#L46-L47

Added lines #L46 - L47 were not covered by tests
default:
fmt.Fprintf(os.Stderr, "Invalid log format: %s\n", format)
fmt.Fprintf(os.Stderr, "Invalid log format specified: %s\n", format)

Check warning on line 49 in cmd/wfx/cmd/root/setup.go

View check run for this annotation

Codecov / codecov/patch

cmd/wfx/cmd/root/setup.go#L49

Added line #L49 was not covered by tests
}
log.Logger = logger.With().Timestamp().Caller().Logger()

log.Debug().Str("format", format).Msg("Logging configured successfully")
}

0 comments on commit be3b387

Please sign in to comment.