Skip to content

Commit

Permalink
update logger
Browse files Browse the repository at this point in the history
  • Loading branch information
mohitsethiaDH committed Jul 2, 2024
1 parent c3f0e52 commit ab5dc5f
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 46 deletions.
65 changes: 36 additions & 29 deletions app/infrastructure/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,40 +6,51 @@ import (
"errors"
"fmt"
"html/template"
"io"
"net"
"net/http"
"sync"
"time"

"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/sirupsen/logrus"
)

// logMu is a mutex to control changes on watson.LogData
var logMu sync.RWMutex

// NewLogger create a new logger instance
func NewLogger(logLevel string) *zap.Logger {
ll, err := zap.ParseAtomicLevel(logLevel)
func NewLogger(out io.Writer, logLevel string, env string) *logrus.Logger {
log := logrus.New()
log.Out = out
log.Formatter = getJSONFormatter(env)
level, err := logrus.ParseLevel(logLevel)
if err != nil {
ll = zap.NewAtomicLevelAt(zap.DebugLevel)
level = logrus.DebugLevel
}
config := zap.NewProductionConfig()
config.Level = ll
config.EncoderConfig = getEncoderConfig()
return zap.Must(config.Build())
log.Level = level

return log
}

// getEncoderConfig
func getEncoderConfig() zapcore.EncoderConfig {
encoderCfg := zap.NewProductionEncoderConfig()
encoderCfg.TimeKey = "timestamp"
encoderCfg.EncodeTime = zapcore.ISO8601TimeEncoder
return encoderCfg
// JSONFormatter Wrapper for logrus.JSONFormatter
type JSONFormatter struct {
logrus.JSONFormatter
}

// getJSONFormatter
func getJSONFormatter(env string) *JSONFormatter {
jsonFormatter := logrus.JSONFormatter{
TimestampFormat: "2006-01-02T15:04:05-0700",
FieldMap: logrus.FieldMap{
logrus.FieldKeyTime: "@timestamp",
},
PrettyPrint: env == "dev",
}
return &JSONFormatter{jsonFormatter}
}

type loggerMiddleware struct {
logger *zap.Logger
logger *logrus.Entry
}

// Middleware specify a interface to http calls
Expand All @@ -48,7 +59,7 @@ type Middleware interface {
}

// NewLoggerMiddleware ...
func NewLoggerMiddleware(logEntry *zap.Logger) Middleware {
func NewLoggerMiddleware(logEntry *logrus.Entry) Middleware {
return &loggerMiddleware{
logger: logEntry,
}
Expand All @@ -69,37 +80,33 @@ func (lmw *loggerMiddleware) Wrap(next http.Handler) http.Handler {
// copy log data
ld := LogData(r.Context())
ld["status_code"] = lr.StatusCode
ld["response_time"] = fmt.Sprintf("%fms", float64(elapsed)/float64(time.Millisecond))
ld["response_time"] = elapsed.Milliseconds()
ld["request_path"] = r.RequestURI
ld["remote_addr"] = r.RemoteAddr

var logLevel zapcore.Level
var logAttr []zapcore.Field
var logLevel logrus.Level
switch statusCode := lr.StatusCode; {
case statusCode >= http.StatusInternalServerError:
logLevel = zap.ErrorLevel
logLevel = logrus.ErrorLevel
case statusCode >= http.StatusMultipleChoices && statusCode < http.StatusInternalServerError:
logLevel = zap.WarnLevel
logLevel = logrus.WarnLevel
default:
logLevel = zap.InfoLevel
}
for key, value := range ld {
logAttr = append(logAttr, zap.Any(key, value))
logLevel = logrus.InfoLevel
}
lmw.logger.With(logAttr...).Log(logLevel, fmt.Sprintf("[%s]", r.Method))
lmw.logger.WithFields(ld).Logf(logLevel, fmt.Sprintf("[%s] %s", r.Method, r.RequestURI))
}

return http.HandlerFunc(fn)
}

// CoreLogger ...
type CoreLogger struct {
logger *zap.Logger
logger *logrus.Entry
}

// Printf ...
func (c *CoreLogger) Printf(format string, v ...interface{}) {
c.logger.Sugar().Infof(format, v...)
c.logger.Infof(format, v...)
}

// Logger is the interface used internally to log
Expand Down
32 changes: 15 additions & 17 deletions cmd/link-identity-api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,31 +19,29 @@ import (
"github.com/link-identity/app/utils"

"github.com/go-chi/chi"
"go.uber.org/zap"
"github.com/sirupsen/logrus"
)

var (
// zap logger instance
logEntryZap *zap.Logger
logEntry *logrus.Entry
)

func init() {
logger := infrastructure.NewLogger(os.Stdout, "info", "test")
hostname, _ := os.Hostname()

logZap := infrastructure.NewLogger("debug")

logEntryZap = logZap.With(
zap.String("env", "dev"),
zap.String("pod_id", hostname),
zap.String("program", "link-identity"),
zap.String("channel", "http"),
)
logEntry = logger.WithFields(logrus.Fields{
"env": "test",
"pod_id": hostname,
"program": "test-app",
"channel": "http",
"request_path": "",
"remote_addr": "",
"status_code": "",
})
}

func main() {
// logger defers
defer logEntryZap.Sync()

// setup database connection
db := sql.NewDBConnection()

Expand Down Expand Up @@ -87,21 +85,21 @@ func main() {
serverStopCtx()
}()
// Run the server
logEntryZap.Info("Starting application at port: " + appconfig.Values.Server.Port)
logEntry.Info("Starting application at port: " + appconfig.Values.Server.Port)
errServer := srv.ListenAndServe()
if errServer != nil && errServer != http.ErrServerClosed {
log.Fatal(errServer)
}
// Wait for server context to be stopped
<-serverCtx.Done()
logEntryZap.Info("Application stopped gracefully!")
logEntry.Info("Application stopped gracefully!")
}

// SetupRouters ...
func SetupRouters(handler *httpHandler.LinkIdentityHandler) *chi.Mux {
// Base route initialize.
router := chi.NewRouter()
router.Use(infrastructure.NewLoggerMiddleware(logEntryZap).Wrap)
router.Use(infrastructure.NewLoggerMiddleware(logEntry).Wrap)

//Health check registration
router.Get("/health/check", GetHealthCheck)
Expand Down
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ require (
github.com/joho/godotenv v1.5.1
github.com/nyaruka/phonenumbers v1.3.4
github.com/pkg/errors v0.9.1
github.com/sirupsen/logrus v1.9.3
github.com/stretchr/testify v1.9.0
go.uber.org/zap v1.27.0
gorm.io/driver/postgres v1.5.7
Expand All @@ -26,6 +27,7 @@ require (
github.com/stretchr/objx v0.5.2 // indirect
go.uber.org/multierr v1.10.0 // indirect
golang.org/x/crypto v0.16.0 // indirect
golang.org/x/sys v0.15.0 // indirect
golang.org/x/text v0.14.0 // indirect
google.golang.org/protobuf v1.33.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
Expand Down
6 changes: 6 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-chi/chi v1.5.5 h1:vOB/HbEMt9QqBqErz07QehcOKHaWFtuj87tTDVz2qXE=
Expand Down Expand Up @@ -32,6 +33,8 @@ github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRI
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
Expand All @@ -47,6 +50,9 @@ go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
golang.org/x/crypto v0.16.0 h1:mMMrFzRSCF0GvB7Ne27XVtVAaXLrPmgPC7/v0tkwHaY=
golang.org/x/crypto v0.16.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc=
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
Expand Down

0 comments on commit ab5dc5f

Please sign in to comment.