Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: switch to zerolog #24

Merged
merged 2 commits into from
Sep 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 36 additions & 19 deletions cmd/cli/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,22 @@ import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"reflect"
"runtime/debug"
"strings"
"text/tabwriter"
"time"

"github.com/TylerBrock/colorjson"
"github.com/Yamashou/gqlgenc/clientv2"
homedir "github.com/mitchellh/go-homedir"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"github.com/theopenlane/utils/cli/rows"
"go.uber.org/zap"

"github.com/theopenlane/dbx/pkg/dbxclient"
)
Expand All @@ -28,7 +32,6 @@ const (

var (
cfgFile string
Logger *zap.SugaredLogger
)

var (
Expand Down Expand Up @@ -96,35 +99,49 @@ func initConfig() {
viper.AutomaticEnv() // read in environment variables that match

err := viper.ReadInConfig()
if err == nil {
log.Info().Str("file", viper.ConfigFileUsed()).Msg("using config file")
}

GraphAPIHost = fmt.Sprintf("%s%s", RootHost, graphEndpoint)

setupLogging()

if err == nil {
Logger.Infow("using config file", "file", viper.ConfigFileUsed())
}
}

// setupLogging sets up the logging defaults for the application
func setupLogging() {
cfg := zap.NewProductionConfig()
if viper.GetBool("logging.pretty") {
cfg = zap.NewDevelopmentConfig()
}
// setup logging with time and app name
log.Logger = zerolog.New(os.Stderr).
With().Timestamp().
Logger().
With().Str("app", appName).
Logger()

// set the log level
zerolog.SetGlobalLevel(zerolog.InfoLevel)

// set the log level to debug if the debug flag is set and add additional information
if viper.GetBool("logging.debug") {
cfg.Level = zap.NewAtomicLevelAt(zap.DebugLevel)
} else {
cfg.Level = zap.NewAtomicLevelAt(zap.InfoLevel)
}
zerolog.SetGlobalLevel(zerolog.DebugLevel)

l, err := cfg.Build()
if err != nil {
panic(err)
buildInfo, _ := debug.ReadBuildInfo()

log.Logger = log.Logger.With().
Caller().
Int("pid", os.Getpid()).
Str("go_version", buildInfo.GoVersion).Logger()
}

Logger = l.Sugar().With("app", appName)
defer Logger.Sync() //nolint:errcheck
// pretty logging for development
if viper.GetBool("logging.pretty") {
log.Logger = log.Output(zerolog.ConsoleWriter{
Out: os.Stderr,
TimeFormat: time.RFC3339,
FormatCaller: func(i interface{}) string {
return filepath.Base(fmt.Sprintf("%s", i))
},
})
}
}

// ViperBindFlag provides a wrapper around the viper bindings that panics if an error occurs
Expand Down
65 changes: 41 additions & 24 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
package cmd

import (
"fmt"
"os"
"path/filepath"
"runtime/debug"
"time"

"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"go.uber.org/zap"
)

const appName = "dbx"

var (
logger *zap.SugaredLogger
)

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: appName,
Expand Down Expand Up @@ -40,12 +43,11 @@ func init() {
// refer to the README.md for more information
func initConfig() {
err := viper.ReadInConfig()

logger = newLogger()

if err == nil {
logger.Infow("using config file", "file", viper.ConfigFileUsed())
if err != nil {
log.Info().Err(err).Str("file", viper.ConfigFileUsed()).Msg("error reading config file")
}

setupLogging()
}

// viperBindFlag provides a wrapper around the viper bindings that panics if an error occurs
Expand All @@ -56,23 +58,38 @@ func viperBindFlag(name string, flag *pflag.Flag) {
}
}

// newLogger creates a new zap logger with the appropriate configuration based on the viper settings for pretty and debug
func newLogger() *zap.SugaredLogger {
cfg := zap.NewProductionConfig()
if viper.GetBool("pretty") {
cfg = zap.NewDevelopmentConfig()
}
// setupLogging sets up the logging defaults for the application
func setupLogging() {
// setup logging with time and app name
log.Logger = zerolog.New(os.Stderr).
With().Timestamp().
Logger().
With().Str("app", appName).
Logger()

// set the log level
zerolog.SetGlobalLevel(zerolog.InfoLevel)

// set the log level to debug if the debug flag is set and add additional information
if viper.GetBool("debug") {
cfg.Level = zap.NewAtomicLevelAt(zap.DebugLevel)
} else {
cfg.Level = zap.NewAtomicLevelAt(zap.InfoLevel)
}
zerolog.SetGlobalLevel(zerolog.DebugLevel)

logger, err := cfg.Build()
if err != nil {
panic(err)
buildInfo, _ := debug.ReadBuildInfo()

log.Logger = log.Logger.With().
Caller().
Int("pid", os.Getpid()).
Str("go_version", buildInfo.GoVersion).Logger()
}

return logger.Sugar()
// pretty logging for development
if viper.GetBool("pretty") {
log.Logger = log.Output(zerolog.ConsoleWriter{
Out: os.Stderr,
TimeFormat: time.RFC3339,
FormatCaller: func(i interface{}) string {
return filepath.Base(fmt.Sprintf("%s", i))
},
})
}
}
16 changes: 7 additions & 9 deletions cmd/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@ package cmd
import (
"context"

"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/theopenlane/beacon/otelx"
"go.uber.org/zap"

"github.com/theopenlane/go-turso"
"github.com/theopenlane/utils/cache"

Expand Down Expand Up @@ -42,7 +41,6 @@ func serve(ctx context.Context) error {
serverOpts := []serveropts.ServerOption{}
serverOpts = append(serverOpts,
serveropts.WithConfigProvider(&config.ConfigProviderWithRefresh{}),
serveropts.WithLogger(logger),
serveropts.WithHTTPS(),
serveropts.WithMiddleware(),
)
Expand All @@ -51,23 +49,23 @@ func serve(ctx context.Context) error {

err = otelx.NewTracer(so.Config.Settings.Tracer, appName)
if err != nil {
logger.Fatalw("failed to initialize tracer", "error", err)
log.Fatal().Err(err).Msg("failed to initialize tracer")
}

// create ent dependency injection
entOpts := []ent.Option{ent.Logger(*logger)}
entOpts := []ent.Option{}

if so.Config.Settings.Providers.TursoEnabled {
tursoClient, err := turso.NewClient(so.Config.Settings.Turso)
if err != nil {
logger.Fatalw("failed to initialize turso client", "error", err)
log.Fatal().Err(err).Msg("failed to initialize turso client")
}

entOpts = append(entOpts, ent.Turso(tursoClient))
}

// Setup DB connection
entdbClient, dbConfig, err := entdb.NewMultiDriverDBClient(ctx, so.Config.Settings.DB, logger, entOpts)
entdbClient, dbConfig, err := entdb.NewMultiDriverDBClient(ctx, so.Config.Settings.DB, entOpts)
if err != nil {
return err
}
Expand All @@ -89,13 +87,13 @@ func serve(ctx context.Context) error {
serveropts.WithReadyChecks(dbConfig, redisClient),
)

srv := server.NewServer(so.Config, so.Config.Logger)
srv := server.NewServer(so.Config)

// Setup Graph API Handlers
so.AddServerOptions(serveropts.WithGraphRoute(srv, entdbClient))

if err := srv.StartEchoServer(ctx); err != nil {
logger.Error("failed to run server", zap.Error(err))
log.Error().Err(err).Msg("failed to run server")
}

return nil
Expand Down
Loading