Skip to content

Commit

Permalink
Simplify logging setup (#47)
Browse files Browse the repository at this point in the history
  • Loading branch information
patricksanders authored Feb 18, 2021
1 parent 179a1f9 commit a37f413
Show file tree
Hide file tree
Showing 22 changed files with 112 additions and 68 deletions.
1 change: 0 additions & 1 deletion cmd/completion.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ package cmd
import (
"os"

log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)

Expand Down
1 change: 0 additions & 1 deletion cmd/credential_process.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import (
"gopkg.in/ini.v1"

"github.com/netflix/weep/creds"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)

Expand Down
1 change: 0 additions & 1 deletion cmd/docs.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
package cmd

import (
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/cobra/doc"
)
Expand Down
1 change: 0 additions & 1 deletion cmd/ecs_credential_provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import (

"github.com/gorilla/mux"
"github.com/netflix/weep/handlers"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)

Expand Down
1 change: 0 additions & 1 deletion cmd/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ import (
"github.com/mitchellh/go-homedir"
"github.com/netflix/weep/creds"
"github.com/netflix/weep/util"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)

Expand Down
1 change: 0 additions & 1 deletion cmd/metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ import (
"github.com/gorilla/mux"
"github.com/netflix/weep/creds"
"github.com/netflix/weep/handlers"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)

Expand Down
58 changes: 12 additions & 46 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,13 @@
package cmd

import (
"io"
"os"
"os/signal"
"path/filepath"
"syscall"

"github.com/netflix/weep/config"
"github.com/netflix/weep/logging"

"github.com/kardianos/service"

log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
Expand All @@ -39,11 +35,12 @@ var (
Long: "Weep is a CLI tool that manages AWS access via ConsoleMe for local development.",
DisableAutoGenTag: true,
}
log = logging.GetLogger()
)

func init() {
cobra.OnInitialize(initConfig)
cobra.OnInitialize(initLogging)
cobra.OnInitialize(updateLoggingConfig)

rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "config file (default is $HOME/.weep.yaml)")
rootCmd.PersistentFlags().StringSliceVarP(&assumeRole, "assume-role", "A", make([]string, 0), "one or more roles to assume after retrieving credentials")
Expand All @@ -52,6 +49,11 @@ func init() {
rootCmd.PersistentFlags().StringVar(&logLevel, "log-level", "", "log level (debug, info, warn)")
}

func Run(initFunctions ...func()) {
cobra.OnInitialize(initFunctions...)
Execute()
}

func Execute() {
shutdown = make(chan os.Signal, 1)
done = make(chan int, 1)
Expand All @@ -68,46 +70,10 @@ func initConfig() {
}
}

func initLogging() {
// Set the log level and default to INFO
switch logLevel {
case "error":
log.SetLevel(log.ErrorLevel)
case "warn":
log.SetLevel(log.WarnLevel)
case "debug":
log.SetLevel(log.DebugLevel)
default:
log.SetLevel(log.InfoLevel)
}

// Set the log format. Default to Text
if logFormat == "json" {
log.SetFormatter(&log.JSONFormatter{})
} else {
log.SetFormatter(&log.TextFormatter{})
}

logDir := filepath.Dir(logFile)
if _, err := os.Stat(logDir); os.IsNotExist(err) {
log.Debugf("attempting to create log directory %s", logDir)
err := os.MkdirAll(logDir, os.ModePerm)
if err != nil {
log.Errorf("could not create log directory")
}
}

var w io.Writer
file, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
// updateLoggingConfig overrides the default logging settings based on the config and CLI args
func updateLoggingConfig() {
err := logging.UpdateConfig(logLevel, logFormat, logFile)
if err != nil {
log.Errorf("could not open %s for logging, defaulting to stderr: %v", logFile, err)
log.SetOutput(os.Stderr)
w = os.Stderr
} else if service.Interactive() {
w = io.MultiWriter(os.Stderr, file)
} else {
w = file
log.Errorf("failed to configure logger: %v", err)
}
log.SetOutput(w)
log.Debug("logging configured")
}
1 change: 0 additions & 1 deletion cmd/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"github.com/spf13/viper"

"github.com/kardianos/service"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)

Expand Down
5 changes: 4 additions & 1 deletion config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,16 @@ import (
"path/filepath"
"runtime"

"github.com/netflix/weep/logging"

"github.com/mitchellh/go-homedir"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"

"github.com/spf13/viper"
)

var log = logging.GetLogger()

func init() {
// Set default configuration values here
viper.SetTypeByDefaultValue(true)
Expand Down
1 change: 0 additions & 1 deletion creds/aws.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import (
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sts"
log "github.com/sirupsen/logrus"
)

// getAwsCredentials uses the provided Client to request credentials from ConsoleMe.
Expand Down
4 changes: 3 additions & 1 deletion creds/consoleme.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,18 +29,20 @@ import (
"syscall"
"time"

"github.com/netflix/weep/logging"

werrors "github.com/netflix/weep/errors"
"github.com/spf13/viper"

"github.com/netflix/weep/challenge"
"github.com/netflix/weep/mtls"
log "github.com/sirupsen/logrus"

"github.com/pkg/errors"

"github.com/netflix/weep/version"
)

var log = logging.GetLogger()
var clientVersion = fmt.Sprintf("%s", version.Version)

var userAgent = "weep/" + clientVersion + " Go-http-client/1.1"
Expand Down
1 change: 0 additions & 1 deletion creds/refreshable.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import (
"github.com/netflix/weep/errors"

"github.com/aws/aws-sdk-go/aws/credentials"
log "github.com/sirupsen/logrus"
)

// NewRefreshableProvider creates an AWS credential provider that will automatically refresh credentials
Expand Down
4 changes: 4 additions & 0 deletions handlers/baseHandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,12 @@ package handlers
import (
"fmt"
"net/http"

"github.com/netflix/weep/logging"
)

var log = logging.GetLogger()

func BaseHandler(w http.ResponseWriter, r *http.Request) {

baseMetadata := `ami-id
Expand Down
1 change: 0 additions & 1 deletion handlers/credentialsHandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import (
"net/http"

"github.com/netflix/weep/cache"
log "github.com/sirupsen/logrus"

"github.com/netflix/weep/metadata"
)
Expand Down
1 change: 0 additions & 1 deletion handlers/ecsCredentialsHandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ import (
"github.com/gorilla/mux"
"github.com/netflix/weep/creds"
"github.com/netflix/weep/metadata"
log "github.com/sirupsen/logrus"
)

// parseAssumeRoleQuery extracts the assume query string argument, splits it on commas, validates that each element
Expand Down
1 change: 0 additions & 1 deletion handlers/healthcheckHandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"net/http"

"github.com/netflix/weep/health"
log "github.com/sirupsen/logrus"
)

type healthcheckResponse struct {
Expand Down
2 changes: 0 additions & 2 deletions handlers/iamInfoHandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@ import (
"fmt"
"net/http"

log "github.com/sirupsen/logrus"

"github.com/netflix/weep/metadata"
"github.com/netflix/weep/util"
)
Expand Down
2 changes: 0 additions & 2 deletions handlers/instanceIdentityDocument.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@ import (

"github.com/netflix/weep/creds"

log "github.com/sirupsen/logrus"

"github.com/netflix/weep/metadata"
"github.com/netflix/weep/util"
)
Expand Down
5 changes: 3 additions & 2 deletions handlers/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,11 @@ import (
"strconv"
"strings"

"github.com/sirupsen/logrus"

"github.com/netflix/weep/util"

"github.com/netflix/weep/metadata"
log "github.com/sirupsen/logrus"
)

// CredentialServiceMiddleware is a convenience wrapper that chains BrowserFilterMiddleware and AWSHeaderMiddleware
Expand Down Expand Up @@ -53,7 +54,7 @@ func AWSHeaderMiddleware(next http.HandlerFunc) http.HandlerFunc {
metadataVersion = 2
}

log.WithFields(log.Fields{
log.WithFields(logrus.Fields{
"user-agent": ua,
"path": r.URL.Path,
"metadata_version": metadataVersion,
Expand Down
79 changes: 79 additions & 0 deletions logging/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package logging

import (
"io"
"os"
"path/filepath"

"github.com/kardianos/service"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)

var log *logrus.Logger

func init() {
log = &logrus.Logger{
Out: os.Stderr,
Formatter: new(logrus.TextFormatter),
Level: logrus.InfoLevel,
}
}

// GetLogger returns the configured logger for use by the rest of the application.
func GetLogger() *logrus.Logger {
return log
}

// UpdateConfig overrides the default logging settings. This function is meant to be
// used during CLI initialization to update the logger based on config file and CLI args.
func UpdateConfig(logLevel string, logFormat string, logFile string) error {
// Set the log level and default to INFO
switch logLevel {
case "error":
log.SetLevel(logrus.ErrorLevel)
case "warn":
log.SetLevel(logrus.WarnLevel)
case "debug":
log.SetLevel(logrus.DebugLevel)
default:
log.SetLevel(logrus.InfoLevel)
}

// Set the log format. Default to Text
if logFormat == "json" {
log.SetFormatter(&logrus.JSONFormatter{})
} else {
log.SetFormatter(&logrus.TextFormatter{})
}

var w io.Writer
if logFile != "" {
logDir := filepath.Dir(logFile)
if _, err := os.Stat(logDir); os.IsNotExist(err) {
// Log directory doesn't exist. Try to make it exist.
log.Debugf("attempting to create log directory %s", logDir)
err := os.MkdirAll(logDir, os.ModePerm)
if err != nil {
return errors.Wrap(err, "could not create log directory")
}
}
// Since we hopefully have the directory, try to open the file
file, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
// No go. Bail out to stderr.
log.SetOutput(os.Stderr)
return errors.Wrapf(err, "could not open %s for logging, defaulting to stderr", logFile)
} else if service.Interactive() {
// No error opening the file, and we know that this is an interactive session.
// Write to stderr and the file.
w = io.MultiWriter(os.Stderr, file)
} else {
// No error on file, not interactive, so just write to the file.
w = file
}
}
log.SetOutput(w)
log.Debug("logging configured")
return nil
}
5 changes: 4 additions & 1 deletion mtls/mtls.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import (
"io/ioutil"
"net/http"

"github.com/netflix/weep/logging"

"github.com/spf13/viper"

"path/filepath"
Expand All @@ -32,9 +34,10 @@ import (
"github.com/mitchellh/go-homedir"
"github.com/netflix/weep/config"
"github.com/netflix/weep/util"
log "github.com/sirupsen/logrus"
)

var log = logging.GetLogger()

// getTLSConfig makes and returns a pointer to a tls.Config
func getTLSConfig() (*tls.Config, error) {
dirs, err := getTLSDirs()
Expand Down
4 changes: 3 additions & 1 deletion util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,11 @@ import (
"os"
"strings"

log "github.com/sirupsen/logrus"
"github.com/netflix/weep/logging"
)

var log = logging.GetLogger()

type AwsArn struct {
Arn string
Partition string
Expand Down

0 comments on commit a37f413

Please sign in to comment.