Skip to content

Commit

Permalink
Add logrus Hook to write logs to stderr and stdout based on log level (
Browse files Browse the repository at this point in the history
  • Loading branch information
sandyydk authored Apr 11, 2023
1 parent 53864a0 commit 9b4c2d1
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
4 changes: 4 additions & 0 deletions cmd/dkron.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"strings"

"github.com/distribworks/dkron/v3/dkron"
"github.com/distribworks/dkron/v3/logging"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
Expand Down Expand Up @@ -58,6 +59,9 @@ func initConfig() {
viper.SetEnvKeyReplacer(replacer)
viper.AutomaticEnv() // read in environment variables that match

// Add hook to set error logs to stderr and regular logs to stdout
logrus.AddHook(&logging.LogSplitter{})

err := viper.ReadInConfig() // Find and read the config file
if err != nil { // Handle errors reading the config file
logrus.WithError(err).Info("No valid config found: Applying default values.")
Expand Down
32 changes: 32 additions & 0 deletions logging/logging.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package logging

import (
"fmt"
"os"

"github.com/sirupsen/logrus"
)

type LogSplitter struct{}

// Levels returns levels that are supported by the hook
func (l *LogSplitter) Levels() []logrus.Level {
return []logrus.Level{logrus.PanicLevel, logrus.FatalLevel, logrus.ErrorLevel, logrus.WarnLevel, logrus.InfoLevel, logrus.DebugLevel, logrus.TraceLevel}
}

// Fire handles logging events based on log levels.
func (l *LogSplitter) Fire(entry *logrus.Entry) error {
if entry == nil {
return fmt.Errorf("logrus entry is nil")
}

switch entry.Level {
case logrus.WarnLevel, logrus.DebugLevel, logrus.InfoLevel, logrus.TraceLevel:
entry.Logger.Out = os.Stdout
case logrus.ErrorLevel, logrus.PanicLevel, logrus.FatalLevel:
entry.Logger.Out = os.Stderr
default:
entry.Logger.Out = os.Stdout
}
return nil
}

0 comments on commit 9b4c2d1

Please sign in to comment.