Skip to content

Commit

Permalink
refactor: move out setting up logging into sep package
Browse files Browse the repository at this point in the history
  • Loading branch information
olexsmir committed Sep 19, 2024
1 parent 4e1a84e commit 71a54c2
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 56 deletions.
52 changes: 4 additions & 48 deletions cmd/server/main.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
//nolint:err113 // all errors are shown to the user so it's ok for them to be dynamic
package main

import (
Expand All @@ -14,6 +13,7 @@ import (
"github.com/olexsmir/onasty/internal/config"
"github.com/olexsmir/onasty/internal/hasher"
"github.com/olexsmir/onasty/internal/jwtutil"
"github.com/olexsmir/onasty/internal/logger"
"github.com/olexsmir/onasty/internal/mailer"
"github.com/olexsmir/onasty/internal/service/notesrv"
"github.com/olexsmir/onasty/internal/service/usersrv"
Expand All @@ -24,7 +24,6 @@ import (
"github.com/olexsmir/onasty/internal/store/psqlutil"
httptransport "github.com/olexsmir/onasty/internal/transport/http"
"github.com/olexsmir/onasty/internal/transport/http/httpserver"
"github.com/olexsmir/onasty/internal/transport/http/reqid"
)

func main() {
Expand All @@ -41,12 +40,12 @@ func run(ctx context.Context) error {
cfg := config.NewConfig()

// logger
baseLoger, err := setupBasicLoggerHandler(cfg)
logger, err := logger.NewCustomLogger(cfg.LogLevel, cfg.LogFormat, cfg.LogShowLine)
if err != nil {
return err
}

slog.SetDefault(slog.New(&CustomLogger{Handler: baseLoger}))
slog.SetDefault(logger)

// semi dev mode
if !cfg.IsDevMode() {
Expand Down Expand Up @@ -89,7 +88,7 @@ func run(ctx context.Context) error {
go func() {
slog.DebugContext(ctx, "starting http server", "port", cfg.ServerPort)
if err := srv.Start(); !errors.Is(err, http.ErrServerClosed) {
slog.Error("failed to start http server", "error", err)
slog.ErrorContext(ctx, "failed to start http server", "error", err)
}
}()

Expand All @@ -108,46 +107,3 @@ func run(ctx context.Context) error {

return nil
}

type CustomLogger struct {
slog.Handler
}

func (l *CustomLogger) Handle(ctx context.Context, r slog.Record) error {
if requestID := reqid.GetFromContext(ctx); requestID != "" {
r.AddAttrs(slog.String("request_id", requestID))
}

return l.Handler.Handle(ctx, r)
}

func setupBasicLoggerHandler(cfg *config.Config) (slog.Handler, error) {
loggerLevels := map[string]slog.Level{
"info": slog.LevelInfo,
"debug": slog.LevelDebug,
"error": slog.LevelError,
"warn": slog.LevelWarn,
}

logLevel, ok := loggerLevels[cfg.LogLevel]
if !ok {
return nil, errors.New("unknown log level")
}

handlerOptions := &slog.HandlerOptions{
Level: logLevel,
AddSource: cfg.LogShowLine,
}

var slogHandler slog.Handler
switch cfg.LogFormat {
case "json":
slogHandler = slog.NewJSONHandler(os.Stdout, handlerOptions)
case "text":
slogHandler = slog.NewTextHandler(os.Stdout, handlerOptions)
default:
return nil, errors.New("unknown log format")
}

return slogHandler, nil
}
17 changes: 9 additions & 8 deletions e2e/e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"github.com/olexsmir/onasty/internal/config"
"github.com/olexsmir/onasty/internal/hasher"
"github.com/olexsmir/onasty/internal/jwtutil"
"github.com/olexsmir/onasty/internal/logger"
"github.com/olexsmir/onasty/internal/mailer"
"github.com/olexsmir/onasty/internal/service/notesrv"
"github.com/olexsmir/onasty/internal/service/usersrv"
Expand Down Expand Up @@ -76,7 +77,6 @@ func (e *AppTestSuite) SetupSuite() {
e.postgresDB = db
e.stopPostgres = stop

e.setupLogger()
e.initDeps()
}

Expand All @@ -89,6 +89,11 @@ func (e *AppTestSuite) TearDownSuite() {
func (e *AppTestSuite) initDeps() {
cfg := e.getConfig()

logger, err := logger.NewCustomLogger(cfg.LogLevel, cfg.LogFormat, cfg.LogShowLine)
e.require.NoError(err)

slog.SetDefault(logger)

e.hasher = hasher.NewSHA256Hasher(cfg.PasswordSalt)
e.jwtTokenizer = jwtutil.NewJWTUtil(cfg.JwtSigningKey, time.Hour)
e.mailer = mailer.NewTestMailer()
Expand Down Expand Up @@ -168,13 +173,6 @@ func (e *AppTestSuite) prepPostgres() (*psqlutil.DB, stopDBFunc, error) {
return db, stop, driver.Close()
}

func (e *AppTestSuite) setupLogger() {
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelDebug,
AddSource: os.Getenv("LOG_SHOW_LINE") == "true",
})))
}

func (e *AppTestSuite) getConfig() *config.Config {
return &config.Config{ //nolint:exhaustruct
AppEnv: "testing",
Expand All @@ -185,5 +183,8 @@ func (e *AppTestSuite) getConfig() *config.Config {
JwtAccessTokenTTL: time.Hour,
JwtRefreshTokenTTL: 24 * time.Hour,
VerficationTokenTTL: 24 * time.Hour,
LogShowLine: os.Getenv("LOG_SHOW_LINE") == "true",
LogFormat: "text",
LogLevel: "debug",
}
}
54 changes: 54 additions & 0 deletions internal/logger/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package logger

import (
"context"
"errors"
"log/slog"
"os"

"github.com/olexsmir/onasty/internal/transport/http/reqid"

Check failure on line 9 in internal/logger/logger.go

View workflow job for this annotation

GitHub Actions / release

no required module provides package github.com/olexsmir/onasty/internal/transport/http/reqid; to add it:
)

type CustomLogger struct {
slog.Handler
}

//nolint:err113
func NewCustomLogger(lvl, format string, showLine bool) (*slog.Logger, error) {
loggerLevels := map[string]slog.Level{
"info": slog.LevelInfo,
"debug": slog.LevelDebug,
"error": slog.LevelError,
"warn": slog.LevelWarn,
}

logLevel, ok := loggerLevels[lvl]
if !ok {
return nil, errors.New("unknown log level")
}

handlerOptions := &slog.HandlerOptions{
Level: logLevel,
AddSource: showLine,
}

var slogHandler slog.Handler
switch format {
case "json":
slogHandler = slog.NewJSONHandler(os.Stdout, handlerOptions)
case "text":
slogHandler = slog.NewTextHandler(os.Stdout, handlerOptions)
default:
return nil, errors.New("unknown log format")
}

return slog.New(&CustomLogger{Handler: slogHandler}), nil
}

func (l *CustomLogger) Handle(ctx context.Context, r slog.Record) error {
if requestID := reqid.GetFromContext(ctx); requestID != "" {
r.AddAttrs(slog.String("request_id", requestID))
}

return l.Handler.Handle(ctx, r)
}

0 comments on commit 71a54c2

Please sign in to comment.