Skip to content

Commit

Permalink
custom logger implemented
Browse files Browse the repository at this point in the history
  • Loading branch information
srivastava-yash committed Oct 28, 2024
1 parent 02e6dbc commit cbf12cd
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 0 deletions.
87 changes: 87 additions & 0 deletions internal/logger/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package logger

import (
"context"
"fmt"
"log"
"log/slog"
"server/config"
"strings"
"time"
)

type CustomLogHandler struct {
level slog.Level
attrs map[string]interface{}
group string
}

func NewCustomLogHandler(level slog.Level) *CustomLogHandler {
return &CustomLogHandler{
level: level,
attrs: make(map[string]interface{}),
}
}

func (h *CustomLogHandler) Enabled(_ context.Context, level slog.Level) bool {
return level >= h.level
}

func (h *CustomLogHandler) Handle(_ context.Context, record slog.Record) error {
if !h.Enabled(nil, record.Level) {
return nil
}

message := fmt.Sprintf("[%s] [%s] %s", time.Now().Format(time.RFC3339), record.Level, record.Message)

// Append attributes
for k, v := range h.attrs {
message += fmt.Sprintf(" | %s=%v", k, v)
}

// Log to standard output
log.Println(message)
return nil
}

func (h *CustomLogHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
newHandler := *h
newHandler.attrs = make(map[string]interface{})

for k, v := range h.attrs {
newHandler.attrs[k] = v
}

for _, attr := range attrs {
newHandler.attrs[attr.Key] = attr.Value.Any()
}
return &newHandler
}

func (h *CustomLogHandler) WithGroup(name string) slog.Handler {
newHandler := *h
newHandler.group = name
return &newHandler
}

func ParseLogLevel(levelStr string) slog.Level {
switch strings.ToLower(levelStr) {
case "debug":
return slog.LevelDebug
case "info":
return slog.LevelInfo
case "warn", "warning":
return slog.LevelWarn
case "error":
return slog.LevelError
default:
return slog.LevelInfo
}
}

func New() *slog.Logger {
levelStr := config.AppConfig.Logging.Level
level := ParseLogLevel(levelStr)
handler := NewCustomLogHandler(level)
return slog.New(handler)
}
2 changes: 2 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@ import (
"os"
"server/config"
"server/internal/db"
"server/internal/logger"
"server/internal/server"
"sync"

_ "github.com/joho/godotenv/autoload"
)

func main() {
slog.SetDefault(logger.New())
diceDBAdminClient, err := db.InitDiceClient(config.AppConfig, true)
if err != nil {
slog.Error("Failed to initialize DiceDB Admin client: %v", slog.Any("err", err))
Expand Down

0 comments on commit cbf12cd

Please sign in to comment.