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

Add Logger middleware #231

Merged
merged 5 commits into from
Dec 18, 2024
Merged
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
85 changes: 85 additions & 0 deletions backend/internal/middleware/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// Package middleware provides Echo middleware functions for the SPUR backend
package middleware

import (
"github.com/labstack/echo/v4"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)

type contextKey string
const loggerContextKey contextKey = "logger"

/*
Logger provides a simplified interface for structured logging throughout the application.
It automatically includes request context (request ID, path, method) in all log entries
while providing a clean interface for developers.

Usage in handlers:
logger := middleware.GetLogger(c)
logger.Info("starting process")
logger.Error(err, "process failed")
logger.Warn("suspicious activity", optionalError)
*/
type Logger struct {
baseLogger *zerolog.Logger
}

func (l *Logger) Info(msg string) {
l.baseLogger.Info().Msg(msg)
}

func (l *Logger) Error(err error, msg string) {
l.baseLogger.Error().Err(err).Msg(msg)
}

func (l *Logger) Warn(msg string, err ...error) {
logger := l.baseLogger.Warn()
if len(err) > 0 && err[0] != nil {
logger = logger.Err(err[0])
}
logger.Msg(msg)
}

/*
GetLogger retrieves the request-scoped logger from the echo context.
If no logger is found, returns a default logger.

The returned logger automatically includes request context in all log entries.
*/
func GetLogger(c echo.Context) *Logger {
if l, ok := c.Get(string(loggerContextKey)).(*Logger); ok {
return l
}
defaultLogger := log.With().Logger()
return &Logger{baseLogger: &defaultLogger}
}

/*
LoggerMiddleware initializes a request-scoped logger and stores it in the context.
The logger includes request ID, method, and path in all subsequent log entries.
*/
func LoggerMiddleware() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
// Get request ID from header OR response header (in case middleware set it)
requestID := c.Request().Header.Get(echo.HeaderXRequestID)
if requestID == "" {
requestID = c.Response().Header().Get(echo.HeaderXRequestID)
}

// Create logger with request context
baseLogger := log.With().
Str("request_id", requestID).
Str("method", c.Request().Method).
Str("path", c.Request().URL.Path).
Logger()

c.Set(string(loggerContextKey), &Logger{
baseLogger: &baseLogger,
})

return next(c)
}
}
}
1 change: 1 addition & 0 deletions backend/internal/server/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ Setup all the global middlewares used in the server.
*/
func (s *Server) setupMiddlewares() {
s.Echo.Use(middleware.RequestID())
s.Echo.Use(middleware.LoggerMiddleware())
}
108 changes: 108 additions & 0 deletions backend/internal/tests/logger_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
package tests

import (
"bytes"
"encoding/json"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/stretchr/testify/assert"
customMiddleware "KonferCA/SPUR/internal/middleware"
"net/http"
"net/http/httptest"
"testing"
)

/*
TestLogger verifies that the logger middleware:
1. Properly creates and stores logger in context
2. Includes request context in all log entries
3. Provides working Info/Error/Warn methods
4. Returns default logger when context is empty
*/
func TestLogger(t *testing.T) {
// capture log output for testing
var buf bytes.Buffer
log.Logger = zerolog.New(&buf)

// setup echo
e := echo.New()

// setup request ID middleware with a config that ensures ID generation
e.Use(middleware.RequestIDWithConfig(middleware.RequestIDConfig{
Generator: func() string {
return "test-request-id"
},
}))
e.Use(customMiddleware.LoggerMiddleware())

// create test handler that uses our logger
e.GET("/test", func(c echo.Context) error {
logger := customMiddleware.GetLogger(c)
logger.Info("test info message")
logger.Warn("test warning")
logger.Error(echo.NewHTTPError(400, "test error"), "test error message")
return c.String(http.StatusOK, "test response")
})

// create and process request
req := httptest.NewRequest(http.MethodGet, "/test", nil)
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)

// verify response
assert.Equal(t, http.StatusOK, rec.Code)

// verify logs
logs := bytes.Split(bytes.TrimSpace(buf.Bytes()), []byte("\n"))
assert.Equal(t, 3, len(logs), "should have 3 log entries")

// verify each log entry
var logEntry map[string]interface{}

// check info log
err := json.Unmarshal(logs[0], &logEntry)
assert.NoError(t, err)
assert.Equal(t, "info", logEntry["level"])
assert.Equal(t, "test info message", logEntry["message"])
assert.Equal(t, "test-request-id", logEntry["request_id"])
assert.Equal(t, "/test", logEntry["path"])

// check warning log
err = json.Unmarshal(logs[1], &logEntry)
assert.NoError(t, err)
assert.Equal(t, "warn", logEntry["level"])
assert.Equal(t, "test warning", logEntry["message"])
assert.Equal(t, "test-request-id", logEntry["request_id"])

// check error log
err = json.Unmarshal(logs[2], &logEntry)
assert.NoError(t, err)
assert.Equal(t, "error", logEntry["level"])
assert.Equal(t, "test error message", logEntry["message"])
assert.Equal(t, "test-request-id", logEntry["request_id"])
assert.NotEmpty(t, logEntry["error"])
}

/*
TestLoggerWithoutContext verifies that GetLogger returns
a default logger when called without proper context
*/
func TestLoggerWithoutContext(t *testing.T) {
var buf bytes.Buffer
log.Logger = zerolog.New(&buf)

e := echo.New()
c := e.NewContext(nil, nil)

logger := customMiddleware.GetLogger(c)
assert.NotNil(t, logger, "should return default logger")

logger.Info("test message")

var logEntry map[string]interface{}
err := json.Unmarshal(buf.Bytes(), &logEntry)
assert.NoError(t, err)
assert.Equal(t, "test message", logEntry["message"])
}
Loading