Skip to content

Commit

Permalink
Move to zerolog
Browse files Browse the repository at this point in the history
  • Loading branch information
airenas committed Nov 23, 2022
1 parent af83078 commit 5158151
Show file tree
Hide file tree
Showing 11 changed files with 521 additions and 128 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,5 @@ git/create/version:
## cleans all temporary data
clean:
go clean
go mod tidy -compat=1.17
go mod tidy -compat=1.18
.PHONY: clean
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@ Simple template for go app with log and config initialized
### License

Copyright © 2022, [Airenas Vaičiūnas](https://github.com/airenas).
Released under the [The 3-Clause BSD License](LICENSE).
Released under [The 3-Clause BSD License](LICENSE).

---
2 changes: 1 addition & 1 deletion examples/config/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@ func main() {
goapp.StartWithDefault()

name := goapp.Config.GetString("sample_name")
goapp.Log.Infof("Hello world, %s!", name)
goapp.Log.Info().Str("name", name).Msg("Hello world!")
}
7 changes: 5 additions & 2 deletions examples/simple/main.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
package main

import (
"fmt"

"github.com/airenas/go-app/pkg/goapp"
)

func main() {
goapp.StartWithDefault()

goapp.Log.Debug("Now will be printing: Hello world")
goapp.Log.Info("Hello world!")
goapp.Log.Debug().Msg("Now will be printing: Hello world")
goapp.Log.Info().Msg("Hello world!")
goapp.Log.Error().Err(fmt.Errorf("Ops")).Send()
}
42 changes: 21 additions & 21 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,35 +1,35 @@
module github.com/airenas/go-app

go 1.17
go 1.18

require (
github.com/heralight/logrus_mate v1.0.1
github.com/pkg/errors v0.9.1
github.com/sirupsen/logrus v1.8.1
github.com/spf13/viper v1.10.1
github.com/stretchr/testify v1.7.1
github.com/rs/zerolog v1.28.0
github.com/spf13/viper v1.14.0
github.com/stretchr/testify v1.8.1
)

require (
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.16 // indirect
)

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/fsnotify/fsnotify v1.5.1 // indirect
github.com/gogap/env_json v0.0.0-20150503135429-86150085ddbe // indirect
github.com/gogap/env_strings v0.0.1 // indirect
github.com/fsnotify/fsnotify v1.6.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/heirko/go-contrib v0.0.0-20200825160048-11fc5e2235fa
github.com/hoisie/redis v0.0.0-20160730154456-b5c6e81454e0 // indirect
github.com/magiconair/properties v1.8.5 // indirect
github.com/mitchellh/mapstructure v1.4.3 // indirect
github.com/pelletier/go-toml v1.9.4 // indirect
github.com/magiconair/properties v1.8.6 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pelletier/go-toml/v2 v2.0.5 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/spf13/afero v1.6.0 // indirect
github.com/spf13/cast v1.4.1 // indirect
github.com/spf13/afero v1.9.2 // indirect
github.com/spf13/cast v1.5.0 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/subosito/gotenv v1.2.0 // indirect
golang.org/x/sys v0.0.0-20211210111614-af8b64212486 // indirect
golang.org/x/text v0.3.7 // indirect
gopkg.in/ini.v1 v1.66.2 // indirect
github.com/subosito/gotenv v1.4.1 // indirect
golang.org/x/sys v0.2.0 // indirect
golang.org/x/text v0.4.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
508 changes: 465 additions & 43 deletions go.sum

Large diffs are not rendered by default.

12 changes: 5 additions & 7 deletions pkg/goapp/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import (
"fmt"
"os"
"path/filepath"

"github.com/pkg/errors"
)

//InitConfig tries to load config.yml from exe's dir
Expand All @@ -22,21 +20,21 @@ func InitConfig(configFile string) error {
// Find home directory.
ex, err := os.Executable()
if err != nil {
return errors.Wrap(err, "Can't get the app directory")
return fmt.Errorf("can't get the app directory: %w", err)
}
Config.AddConfigPath(filepath.Dir(ex))
Config.SetConfigName("config")
}

if err := Config.ReadInConfig(); err != nil {
Log.Warn("Can't read config:", err)
Log.Warn().Err(err).Msg("can't read config")
if failOnNoFail {
return errors.Wrap(err, "Can't read config:")
return fmt.Errorf("can't read config: %w", err)
}
}
initLog()
if Config.ConfigFileUsed() != "" {
Log.Info("Config loaded from: ", Config.ConfigFileUsed())
Log.Info().Msgf("Config loaded from: %s", Config.ConfigFileUsed())
}
return nil
}
Expand All @@ -59,6 +57,6 @@ func StartWithFlags(fs *flag.FlagSet, args []string) {
fs.Parse(args[1:])
err := InitConfig(*cFile)
if err != nil {
Log.Fatal(errors.Wrap(err, "Can't init app"))
Log.Fatal().Err(err).Msg("can't init app")
}
}
21 changes: 3 additions & 18 deletions pkg/goapp/app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"os"
"testing"

"github.com/sirupsen/logrus"
"github.com/rs/zerolog"
"github.com/stretchr/testify/assert"
)

Expand Down Expand Up @@ -90,21 +90,6 @@ func TestLoggerLevelInitFromEnv(t *testing.T) {
assert.Equal(t, "trace", Log.GetLevel().String())
}

func TestLoggerOutFromEnv(t *testing.T) {
initDefaultLevel()
assert.Equal(t, os.Stdout, Log.Out)

os.Setenv("LOGGER_OUT_NAME", "stderr")
initAppFromTempFile(t, "logger:\n level: info\n")

assert.Equal(t, os.Stderr, Log.Out)

os.Setenv("LOGGER_OUT_NAME", "stdout")
initAppFromTempFile(t, "logger:\n level: info\n")

assert.Equal(t, os.Stdout, Log.Out)
}

func TestStartWitFlags(t *testing.T) {
f, err := ioutil.TempFile("", "test.*.yml")
assert.Nil(t, err)
Expand Down Expand Up @@ -136,6 +121,6 @@ func initAppFromTempFile(t *testing.T, data string) {
}

func initDefaultLevel() {
Log.SetLevel(logrus.ErrorLevel)
Log.Out = os.Stdout
Log.Level(zerolog.InfoLevel)
Log.Output(os.Stdout)
}
45 changes: 15 additions & 30 deletions pkg/goapp/log.go
Original file line number Diff line number Diff line change
@@ -1,42 +1,27 @@
package goapp

import (
"github.com/heirko/go-contrib/logrusHelper"
"github.com/heralight/logrus_mate"
"github.com/sirupsen/logrus"
"strings"

"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)

//Log is applications logger
var Log = logrus.New()
var Log = log.Logger

func initLog() {
initDefaultLogConfig()
c := logrusHelper.UnmarshalConfiguration(Config.Sub("logger"))
initLogFromEnv(&c)
err := logrusHelper.SetConfig(Log, c)
if err != nil {
Log.Error("Can't init log ", err)
}
}

//initLogFromEnv tries to set level from environment
func initLogFromEnv(c *logrus_mate.LoggerConfig) {
ll := Config.GetString("logger.level")
if ll != "" {
c.Level = ll
sl := Config.GetString("logger.level")
if sl == "" {
sl = "info"
}
out := Config.GetString("logger.out.name")
if out != "" {
c.Out.Name = out
l, err := zerolog.ParseLevel(strings.ToLower(sl))
if err != nil {
Log.Error().Err(err).Msgf("can't parse %s", sl)
} else {
Log = log.Logger.Level(l).Output(zerolog.NewConsoleWriter())
}
}

func initDefaultLogConfig() {
defaultLogConfig := map[string]interface{}{
"level": "info",
"formatter.name": "text",
"formatter.options.full_timestamp": true,
"formatter.options.timestamp_format": "2006-01-02T15:04:05.000",
if strings.ToLower(Config.GetString("logger.out")) == "console" {
Log = log.Logger.Level(l).Output(zerolog.NewConsoleWriter(func(w *zerolog.ConsoleWriter) { w.TimeFormat = "2006-01-02T15:04:05.000" }))
}
Config.SetDefault("logger", defaultLogConfig)
}
6 changes: 3 additions & 3 deletions pkg/goapp/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
func HidePass(link string) string {
u, err := url.Parse(link)
if err != nil {
Log.Warn("Can't parse url.")
Log.Warn().Msg("can't parse url.")
return ""
}
if u.User != nil {
Expand All @@ -27,7 +27,7 @@ func HidePass(link string) string {
func Estimate(name string) func() {
start := time.Now()
return func() {
Log.Infof("%s took %v", name, time.Since(start))
Log.Info().Msgf("%s took %v", name, time.Since(start))
}
}

Expand All @@ -44,7 +44,7 @@ func getBodyStr(rd io.Reader, l int) string {
if l > 0 {
bytes, err := io.ReadAll(io.LimitReader(rd, int64(l+1)))
if err != nil && err != io.EOF {
Log.Warn(err)
Log.Warn().Err(err).Send()
}
if len(bytes) > l {
return "\n" + string(bytes[:l]) + "..."
Expand Down
2 changes: 1 addition & 1 deletion version
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
commit_count=$(shell git rev-list --count HEAD)

version=v0.4.$(commit_count)
version=v1.0.$(commit_count)

0 comments on commit 5158151

Please sign in to comment.