Skip to content

Commit f29c30a

Browse files
committed
feat: better formating of logs
1 parent 2c2c012 commit f29c30a

File tree

2 files changed

+31
-10
lines changed

2 files changed

+31
-10
lines changed

helm/chart/templates/deployment.yaml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,11 +43,11 @@ spec:
4343
protocol: TCP
4444
livenessProbe:
4545
httpGet:
46-
path: /
46+
path: /health
4747
port: http
4848
readinessProbe:
4949
httpGet:
50-
path: /
50+
path: /health
5151
port: http
5252
resources:
5353
{{- toYaml .Values.resources | nindent 12 }}

src/github.com/hoverkraft-tech/http-header-authenticator/main.go

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@ package main
33
import (
44
"fmt"
55
"net/http"
6+
"os"
7+
"strings"
68

7-
"github.com/gin-contrib/logger"
89
"github.com/gin-contrib/requestid"
910
"github.com/gin-gonic/gin"
1011
"github.com/rs/zerolog"
@@ -27,13 +28,13 @@ func main() {
2728
return
2829
}
2930

30-
r := gin.Default()
31+
l := zerolog.New(os.Stdout).With().Timestamp().Logger()
32+
l.Info().Msg(fmt.Sprintf("Expected header is '%s' and expected value is '%s'", headerName, expectedValue))
3133

32-
l := logger.WithLogger(func(_ *gin.Context, l zerolog.Logger) zerolog.Logger {
33-
return l.Output(gin.DefaultWriter).With().Logger()
34-
})
34+
r := gin.New()
35+
r.Use(gin.Recovery())
3536
r.Use(requestid.New())
36-
r.Use(logger.SetLogger(l))
37+
r.Use(CustomLoggerMiddleware(l))
3738

3839
// Health check endpoint
3940
r.GET("/health", func(c *gin.Context) {
@@ -44,9 +45,9 @@ func main() {
4445
r.NoRoute(func(c *gin.Context) {
4546
value := c.GetHeader(headerName)
4647
if value == expectedValue {
47-
c.String(http.StatusOK, "HTTP header is present with the expected value.")
48+
c.JSON(http.StatusOK, "HTTP header is present with the expected value.")
4849
} else {
49-
c.String(http.StatusForbidden, "HTTP header is not present with the expected value.")
50+
c.JSON(http.StatusForbidden, "HTTP header is not present with the expected value.")
5051
}
5152
})
5253

@@ -62,3 +63,23 @@ func main() {
6263
fmt.Println(err)
6364
}
6465
}
66+
67+
func CustomLoggerMiddleware(logger zerolog.Logger) gin.HandlerFunc {
68+
return func(c *gin.Context) {
69+
// Continue processing other middleware and the request
70+
c.Next()
71+
72+
// Check the request path and exclude the health route from logging
73+
if c.Request.URL.Path != "/health" {
74+
logger.Info().
75+
Str("request_id", c.Request.Header.Get("X-Request-ID")).
76+
Str("client_ip", strings.Split(c.Request.RemoteAddr, ":")[0]).
77+
Int("status", c.Writer.Status()).
78+
Str("method", c.Request.Method).
79+
Str("path", c.Request.URL.Path).
80+
Str("protocol", c.Request.Proto).
81+
Str("user_agent", c.Request.UserAgent()).
82+
Msg("")
83+
}
84+
}
85+
}

0 commit comments

Comments
 (0)