-
Notifications
You must be signed in to change notification settings - Fork 480
/
logger.go
74 lines (62 loc) · 2.23 KB
/
logger.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package util
import (
"bytes"
"github.com/devtron-labs/devtron/internal/middleware"
"github.com/devtron-labs/devtron/pkg/user"
"io"
"log"
"net/http"
"time"
)
type AuditLoggerDTO struct {
UrlPath string `json:"urlPath"`
UserEmail string `json:"userEmail"`
UpdatedOn time.Time `json:"updatedOn"`
QueryParams string `json:"queryParams"`
ApiResponseCode int `json:"apiResponseCode"`
RequestPayload []byte `json:"requestPayload"`
}
type LoggingMiddlewareImpl struct {
userService user.UserService
}
func NewLoggingMiddlewareImpl(userService user.UserService) *LoggingMiddlewareImpl {
return &LoggingMiddlewareImpl{
userService: userService,
}
}
type LoggingMiddleware interface {
LoggingMiddleware(next http.Handler) http.Handler
}
// LoggingMiddleware is a middleware function that logs the incoming request.
func (impl LoggingMiddlewareImpl) LoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
d := middleware.NewDelegator(w, nil)
token := r.Header.Get("token")
userEmail, err := impl.userService.GetEmailFromToken(token)
if err != nil {
log.Printf("AUDIT_LOG: user does not exists")
}
// Read the request body into a buffer
var bodyBuffer bytes.Buffer
_, err = io.Copy(&bodyBuffer, r.Body)
if err != nil {
log.Printf("AUDIT_LOG: error reading request body for urlPath: %s queryParams: %s userEmail: %s", r.URL.Path, r.URL.Query().Encode(), userEmail)
}
// Restore the request body for downstream handlers
r.Body = io.NopCloser(&bodyBuffer)
auditLogDto := &AuditLoggerDTO{
UrlPath: r.URL.Path,
UserEmail: userEmail,
UpdatedOn: time.Now(),
QueryParams: r.URL.Query().Encode(),
RequestPayload: bodyBuffer.Bytes(),
}
// Call the next handler in the chain.
next.ServeHTTP(d, r)
auditLogDto.ApiResponseCode = d.Status()
LogRequest(auditLogDto)
})
}
func LogRequest(auditLogDto *AuditLoggerDTO) {
log.Printf("AUDIT_LOG: urlPath: %s, queryParams: %s,updatedBy: %s, updatedOn: %s, apiResponseCode: %d,requestPayload: %s", auditLogDto.UrlPath, auditLogDto.QueryParams, auditLogDto.UserEmail, auditLogDto.UpdatedOn, auditLogDto.ApiResponseCode, auditLogDto.RequestPayload)
}