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

zap logger added #19

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions application.yml.default
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
APP_NAME: "samplemgr"
APP_PORT: "33001"
ENV: "development"

# MongoDB URI
#DB_URI: "mongodb://user:password@localhost:27017/dbname?authMechanism=SCRAM-SHA-1"
Expand Down
8 changes: 8 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
var (
appName string
appPort int
env string
)

func Load() {
Expand Down Expand Up @@ -40,6 +41,13 @@ func AppPort() int {
return appPort
}

func Env() string {
if env == "" {
env = ReadEnvString("ENV")
}
return env
}

func ReadEnvInt(key string) int {
checkIfSet(key)
v, err := strconv.Atoi(viper.GetString(key))
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,6 @@ require (
github.com/xdg/scram v0.0.0-20180814205039-7eeb5667e42c // indirect
github.com/xdg/stringprep v0.0.0-20180714160509-73f8eece6fdc // indirect
go.mongodb.org/mongo-driver v1.7.3
go.uber.org/zap v1.10.0 // indirect
gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22
)
3 changes: 3 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -199,8 +199,11 @@ go.mongodb.org/mongo-driver v1.3.2 h1:IYppNjEV/C+/3VPbhHVxQ4t04eVW0cLp0/pNdW++6U
go.mongodb.org/mongo-driver v1.3.2/go.mod h1:MSWZXKOynuguX+JSvwP8i+58jYCXxbia8HS3gZBapIE=
go.mongodb.org/mongo-driver v1.7.3 h1:G4l/eYY9VrQAK/AUgkV0koQKzQnyddnWxrd/Etf0jIs=
go.mongodb.org/mongo-driver v1.7.3/go.mod h1:NqaYOwnXWr5Pm7AOpO5QFxKJ503nbMse/R79oO62zWg=
go.uber.org/atomic v1.4.0 h1:cxzIVoETapQEqDhQu3QfnvXAV4AlzcvUCxkVUFw3+EU=
go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
go.uber.org/multierr v1.1.0 h1:HoEmRHQPVSqub6w2z2d2EOVs2fjyFRGyofhKuyDq0QI=
go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
go.uber.org/zap v1.10.0 h1:ORx85nbTijNz8ljznvCMR1ZBIPKFn3jQrag10X2AsuM=
go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
Expand Down
5 changes: 5 additions & 0 deletions logger/constants.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package logger

type ContextKey string

const requestIDKey ContextKey = "request-id"
94 changes: 94 additions & 0 deletions logger/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package logger

import (
"context"

"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)

var sugaredLogger *zap.SugaredLogger

func SetupLogger(env string) (*zap.SugaredLogger, error) {
logger, err := getLoggerbyEnv(env)
if err != nil {
return nil, err
}

sugaredLogger = logger.Sugar()
return sugaredLogger, nil
}

func getLoggerbyEnv(env string) (logger *zap.Logger, err error) {
option := zap.AddCallerSkip(1)

if env == "production" {
Copy link

@ChandanChainani ChandanChainani Sep 17, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please move production key to const and how about if no env is defined we set the logger in production mode

return zap.NewProduction(option)
}

config := zap.NewDevelopmentConfig()
config.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
return config.Build(option)
}

func Errorw(ctx context.Context, message string, args ...interface{}) {
args = appendRequestIDIntoArgs(ctx, args)
sugaredLogger.Errorw(message, args...)
}

func Errorf(ctx context.Context, message string, args ...interface{}) {
sugaredLogger.Errorf(message, args...)
}

func Error(ctx context.Context, args ...interface{}) {
sugaredLogger.Error(args...)
}

func Infow(ctx context.Context, message string, args ...interface{}) {
args = appendRequestIDIntoArgs(ctx, args)
sugaredLogger.Infow(message, args...)
}

func Infof(ctx context.Context, message string, args ...interface{}) {
sugaredLogger.Infof(message, args...)
}

func Info(ctx context.Context, args ...interface{}) {
sugaredLogger.Info(args...)
}

func Warnw(ctx context.Context, message string, args ...interface{}) {
args = appendRequestIDIntoArgs(ctx, args)
sugaredLogger.Warnw(message, args...)
}

func Warnf(ctx context.Context, message string, args ...interface{}) {
sugaredLogger.Warnf(message, args...)
}

func Warn(ctx context.Context, args ...interface{}) {
sugaredLogger.Warn(args...)
}

func Debugw(ctx context.Context, message string, args ...interface{}) {
args = appendRequestIDIntoArgs(ctx, args)
sugaredLogger.Debugw(message, args...)
}

func Debugf(ctx context.Context, message string, args ...interface{}) {
sugaredLogger.Debugf(message, args...)
}

func Debug(ctx context.Context, args ...interface{}) {
sugaredLogger.Debug(args...)
}

func appendRequestIDIntoArgs(ctx context.Context, args []interface{}) []interface{} {
ridValue, ok := ctx.Value(requestIDKey).(string)
if !ok {
return args
}
args = append(args, "request-id")
args = append(args, ridValue)
return args
}
15 changes: 8 additions & 7 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,20 @@ package main
// @APIDescription Main API for Microservices in Go!

import (
"context"
"fmt"
"joshsoftware/golang-boilerplate/config"
"joshsoftware/golang-boilerplate/db"
"joshsoftware/golang-boilerplate/logger"
"joshsoftware/golang-boilerplate/service"
"os"
"strconv"

logger "github.com/sirupsen/logrus"
cli "github.com/urfave/cli/v2"
"github.com/urfave/negroni"
)

func main() {
logger.SetFormatter(&logger.TextFormatter{
FullTimestamp: true,
TimestampFormat: "02-01-2006 15:04:05",
})

config.Load()

cliApp := cli.NewApp()
Expand Down Expand Up @@ -64,9 +60,14 @@ func main() {
}

func startApp() (err error) {
_, err = logger.SetupLogger(config.Env())
if err != nil {
return
}

store, err := db.Init()
if err != nil {
logger.WithField("err", err.Error()).Error("Database init failed")
logger.Errorw(context.Background(), "Database init failed", "err", err.Error())
return
}

Expand Down