Skip to content

Commit

Permalink
add log handler
Browse files Browse the repository at this point in the history
  • Loading branch information
Quang nd committed Sep 19, 2024
1 parent 75a7135 commit 470a56c
Show file tree
Hide file tree
Showing 7 changed files with 161 additions and 96 deletions.
42 changes: 8 additions & 34 deletions cmd/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@ package main

import (
"test-go/internal/api/routes"
"time"

"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"test-go/internal/logger"
"test-go/internal/middleware"

"github.com/gin-gonic/gin"
)
Expand Down Expand Up @@ -51,34 +49,10 @@ func main() {
// search.ConnectElasticSearch(elasticSearchHost)
// loggerPdt := logger.NewLogger()

zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
router := gin.New()
router.Use(func(c *gin.Context) {
start := time.Now()
raw := c.Request.URL.RawQuery

c.Next()

latency := time.Since(start).Milliseconds()

var zeroLog *zerolog.Event
status := c.Writer.Status()
switch {
case status < 400:
zeroLog = log.Info()
case status < 500:
zeroLog = log.Warn()
default:
zeroLog = log.Error()
}
zeroLog.
Int("status", c.Writer.Status()).
Int64("latency", latency).
Str("method", c.Request.Method).
Str("path", c.Request.URL.Path).
Str("method", c.Request.Method).
Str("query", raw).
Msg("HTTP request completed")
})
routes.UseRoutes(router)
logger.SetupLogger()
engine := gin.New()
engine.Use(middleware.Logger())
engine.Use(middleware.ErrorHandler())
routes.SetupRoutes(engine)
engine.Run(":8080")
}
27 changes: 27 additions & 0 deletions deployment.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: basic-go-deployment
spec:
selector:
matchLabels:
app: basic-go
template:
metadata:
labels:
app: basic-go
spec:
containers:
- name: basic-go
image: darthmalgus1997/basic-go-service:v1.0.2
resources:
limits:
memory: "128Mi"
cpu: "500m"
ports:
- containerPort: 8080
env:
- name: service-name
valueFrom:
fieldRef:
fieldPath: spec.selector.matchLabels.app
5 changes: 1 addition & 4 deletions internal/api/routes/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,7 @@ import (
"github.com/gin-gonic/gin"
)

func UseRoutes(router *gin.Engine) {

func SetupRoutes(router *gin.Engine) {
router.GET("/health", handlers.HealthCheck)
AddSearchRoutes(router)

router.Run(":8080")
}
5 changes: 2 additions & 3 deletions internal/logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ type Field struct {
Value interface{}
}

func NewLogger() Logger {
logger, _ := newZapLogger()
return logger
func SetupLogger() {
SetupZeroLogger()
}
110 changes: 55 additions & 55 deletions internal/logger/zap.go
Original file line number Diff line number Diff line change
@@ -1,65 +1,65 @@
package logger

import (
"os"
"time"
// import (
// "os"
// "time"

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

type zapLogger struct {
logger *zap.Logger
}
// type zapLogger struct {
// logger *zap.Logger
// }

func newZapLogger() (Logger, error) {
config := zap.NewProductionConfig()
config.EncoderConfig.TimeKey = ""
customConfig := zapcore.EncoderConfig{
TimeKey: "timestamp",
LevelKey: "level",
NameKey: "logger",
CallerKey: "caller",
FunctionKey: zapcore.OmitKey,
MessageKey: "msg",
StacktraceKey: "stacktrace",
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: zapcore.LowercaseLevelEncoder,
EncodeTime: zapcore.TimeEncoderOfLayout(time.RFC3339),
EncodeDuration: zapcore.StringDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
}
customCore := zapcore.NewCore(
zapcore.NewJSONEncoder(customConfig),
zapcore.AddSync(os.Stdout),
config.Level,
)
// func newZapLogger() (Logger, error) {
// config := zap.NewProductionConfig()
// config.EncoderConfig.TimeKey = ""
// customConfig := zapcore.EncoderConfig{
// TimeKey: "timestamp",
// LevelKey: "level",
// NameKey: "logger",
// CallerKey: "caller",
// FunctionKey: zapcore.OmitKey,
// MessageKey: "msg",
// StacktraceKey: "stacktrace",
// LineEnding: zapcore.DefaultLineEnding,
// EncodeLevel: zapcore.LowercaseLevelEncoder,
// EncodeTime: zapcore.TimeEncoderOfLayout(time.RFC3339),
// EncodeDuration: zapcore.StringDurationEncoder,
// EncodeCaller: zapcore.ShortCallerEncoder,
// }
// customCore := zapcore.NewCore(
// zapcore.NewJSONEncoder(customConfig),
// zapcore.AddSync(os.Stdout),
// config.Level,
// )

// Combine the custom core with the default core
core := zapcore.NewTee(
zapcore.NewCore(zapcore.NewJSONEncoder(config.EncoderConfig), zapcore.AddSync(os.Stdout), config.Level),
customCore,
)
logger := zap.New(core)
return &zapLogger{logger: logger}, nil
}
// // Combine the custom core with the default core
// core := zapcore.NewTee(
// zapcore.NewCore(zapcore.NewJSONEncoder(config.EncoderConfig), zapcore.AddSync(os.Stdout), config.Level),
// customCore,
// )
// logger := zap.New(core)
// return &zapLogger{logger: logger}, nil
// }

func (z *zapLogger) Info(msg string, fields ...Field) {
z.logger.Info(msg, convertToZapFields(fields)...)
}
// func (z *zapLogger) Info(msg string, fields ...Field) {
// z.logger.Info(msg, convertToZapFields(fields)...)
// }

func (z *zapLogger) Error(msg string, fields ...Field) {
z.logger.Error(msg, convertToZapFields(fields)...)
}
// func (z *zapLogger) Error(msg string, fields ...Field) {
// z.logger.Error(msg, convertToZapFields(fields)...)
// }

func (z *zapLogger) Debug(msg string, fields ...Field) {
z.logger.Debug(msg, convertToZapFields(fields)...)
}
// func (z *zapLogger) Debug(msg string, fields ...Field) {
// z.logger.Debug(msg, convertToZapFields(fields)...)
// }

func convertToZapFields(fields []Field) []zap.Field {
zapFields := make([]zap.Field, len(fields))
for i, f := range fields {
zapFields[i] = zap.Any(f.Key, f.Value)
}
return zapFields
}
// func convertToZapFields(fields []Field) []zap.Field {
// zapFields := make([]zap.Field, len(fields))
// for i, f := range fields {
// zapFields[i] = zap.Any(f.Key, f.Value)
// }
// return zapFields
// }
14 changes: 14 additions & 0 deletions internal/logger/zerolog.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package logger

import (
"os"

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

func SetupZeroLogger() {
service_name := os.Getenv("service_name")
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
log.Logger = log.With().Str("service", service_name).Logger()
}
54 changes: 54 additions & 0 deletions internal/middleware/middleware.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package middleware

import (
"time"

"github.com/gin-gonic/gin"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)

func Logger() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
raw := c.Request.URL.RawQuery

c.Next()

latency := time.Since(start).Milliseconds()
var zeroLog *zerolog.Event
status := c.Writer.Status()
switch {
case status < 400:
zeroLog = log.Info()
case status < 500:
zeroLog = log.Warn()
default:
zeroLog = log.Error()
}
zeroLog.
Int("status", c.Writer.Status()).
Int64("latency", latency).
Str("method", c.Request.Method).
Str("path", c.Request.URL.Path).
Str("method", c.Request.Method).
Str("query", raw).
Msg("HTTP request completed")
}
}

func ErrorHandler() gin.HandlerFunc {
return func(c *gin.Context) {
c.Next()

status := c.Writer.Status()
if status < 500 {
return
}
c.Errors = c.Errors[:0]
c.JSON(500, gin.H{
"error": "An internal server error occurred",
})
c.Abort()
}
}

0 comments on commit 470a56c

Please sign in to comment.