Skip to content

Commit

Permalink
bin/crowdsec: avoid writing errors twice when log_media=stdout
Browse files Browse the repository at this point in the history
simpler, correct hook usage
  • Loading branch information
mmetc committed Mar 7, 2024
1 parent e611d01 commit 475bf18
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 26 deletions.
33 changes: 9 additions & 24 deletions cmd/crowdsec/hook.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,42 +2,27 @@ package main

import (
"io"
"os"

log "github.com/sirupsen/logrus"
)

type ConditionalHook struct {
// FatalHook is used to log fatal messages to stderr when the rest goes to a file
type FatalHook struct {
Writer io.Writer
LogLevels []log.Level
Enabled bool
}

func (hook *ConditionalHook) Fire(entry *log.Entry) error {
if hook.Enabled {
line, err := entry.String()
if err != nil {
return err
}

_, err = hook.Writer.Write([]byte(line))

func (hook *FatalHook) Fire(entry *log.Entry) error {
line, err := entry.String()
if err != nil {
return err
}

return nil
}
_, err = hook.Writer.Write([]byte(line))

func (hook *ConditionalHook) Levels() []log.Level {
return hook.LogLevels
return err
}

// The primal logging hook is set up before parsing config.yaml.
// Once config.yaml is parsed, the primal hook is disabled if the
// configured logger is writing to stderr. Otherwise it's used to
// report fatal errors and panics to stderr in addition to the log file.
var primalHook = &ConditionalHook{
Writer: os.Stderr,
LogLevels: []log.Level{log.FatalLevel, log.PanicLevel},
Enabled: true,
func (hook *FatalHook) Levels() []log.Level {
return hook.LogLevels
}
11 changes: 9 additions & 2 deletions cmd/crowdsec/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,12 @@ func LoadConfig(configFile string, disableAgent bool, disableAPI bool, quiet boo
return nil, err
}

primalHook.Enabled = (cConfig.Common.LogMedia != "stdout")
if cConfig.Common.LogMedia != "stdout" {
log.AddHook(&FatalHook{
Writer: os.Stderr,
LogLevels: []log.Level{log.FatalLevel, log.PanicLevel},
})
}

if err := csconfig.LoadFeatureFlagsFile(configFile, log.StandardLogger()); err != nil {
return nil, err
Expand Down Expand Up @@ -323,7 +328,9 @@ func LoadConfig(configFile string, disableAgent bool, disableAPI bool, quiet boo
var crowdsecT0 time.Time

func main() {
log.AddHook(primalHook)
// The initial log level is INFO, even if the user provided an -error or -warning flag
// because we need feature flags before parsing cli flags
log.SetFormatter(&log.TextFormatter{TimestampFormat: time.RFC3339, FullTimestamp: true})

if err := fflag.RegisterAllFeatures(); err != nil {
log.Fatalf("failed to register features: %s", err)
Expand Down

0 comments on commit 475bf18

Please sign in to comment.