Skip to content

Commit

Permalink
chore: make http logs use the same log.Logger as the app
Browse files Browse the repository at this point in the history
  • Loading branch information
YuukanOO committed Nov 17, 2023
1 parent 63ee556 commit 68aecc0
Show file tree
Hide file tree
Showing 6 changed files with 61 additions and 14 deletions.
2 changes: 1 addition & 1 deletion cmd/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ func (c *configuration) PostLoad() error {
return validation.Check(validation.Of{
"data.deployment_dir_template": validation.Value(c.Data.DeploymentDirTemplate, &c.deploymentDirTemplate, template.New("").Parse),
"runners.poll_interval": validation.Value(c.Runners.PollInterval, &c.pollInterval, time.ParseDuration),
"runners.deployment": validation.Is(c.Runners.Deployment, numbers.Min(0)),
"runners.deployment": validation.Is(c.Runners.Deployment, numbers.Min(1)),
"balancer.domain": domainUrlErr,
"balancer.acme.email": validation.If(domainUrlErr == nil && c.domain.UseSSL(), func() error {
return validation.Value(c.AcmeEmail(), &acmeEmail, auth.EmailFrom)
Expand Down
37 changes: 37 additions & 0 deletions cmd/serve/middlewares.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@ package serve

import (
"errors"
"fmt"
"net/http"
"strings"
"time"

"github.com/YuukanOO/seelf/internal/auth/domain"
httputils "github.com/YuukanOO/seelf/pkg/http"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
)
Expand Down Expand Up @@ -95,6 +98,40 @@ func (s *server) transactional(ctx *gin.Context) {
}
}

func (s *server) requestLogger(ctx *gin.Context) {
start := time.Now()

path := ctx.Request.URL.Path
raw := ctx.Request.URL.RawQuery

if raw != "" {
path = path + "?" + raw
}

ctx.Next()

s.logger.Debugw(path,
"status", ctx.Writer.Status(),
"method", ctx.Request.Method,
"elapsed", time.Since(start))
}

func (s *server) recoverer(ctx *gin.Context) {
defer func() {
if err := recover(); err != nil {
asErr, ok := err.(error)

if !ok {
asErr = fmt.Errorf("%v", err)
}

httputils.HandleError(s, ctx, asErr)
}
}()

ctx.Next()
}

func needsTransaction(ctx *gin.Context) bool {
switch ctx.Request.Method {
case http.MethodHead,
Expand Down
19 changes: 14 additions & 5 deletions cmd/serve/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -305,11 +305,9 @@ func (s *server) startCheckup() error {
}

func (s *server) configureRouter() {
if !s.options.IsVerbose() {
gin.SetMode(gin.ReleaseMode)
}
gin.SetMode(gin.ReleaseMode)

s.router = gin.Default()
s.router = gin.New()
s.router.SetTrustedProxies(nil)

// Configure the session store
Expand All @@ -319,7 +317,18 @@ func (s *server) configureRouter() {
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
})
s.router.Use(sessions.Sessions(sessionName, store), s.transactional)

middlewares := []gin.HandlerFunc{
s.recoverer,
sessions.Sessions(sessionName, store),
s.transactional,
}

if s.options.IsVerbose() {
middlewares = append([]gin.HandlerFunc{s.requestLogger}, middlewares...)
}

s.router.Use(middlewares...)

// Let's register every routes now!
v1 := s.router.Group("/api/v1")
Expand Down
9 changes: 4 additions & 5 deletions internal/deployment/infra/backend/docker/docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
_ "embed"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"slices"
Expand Down Expand Up @@ -320,15 +321,13 @@ func (d *docker) instantiateClientAndCompose(logger domain.DeploymentLogger) (co
return d.cli, d.compose, nil
}

var cliOpts []command.DockerCliOption
stream := io.Discard

if logger != nil {
cliOpts = append(cliOpts, command.WithCombinedStreams(logger))
stream = logger
}

dockerCli, err := command.NewDockerCli(cliOpts...)

// FIXME: should the dockerCli.Client() be closed by the caller?
dockerCli, err := command.NewDockerCli(command.WithCombinedStreams(stream))

if err != nil {
return nil, nil, err
Expand Down
2 changes: 2 additions & 0 deletions pkg/apperr/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
var ErrNotFound = New("not_found") // Common error used when a resource could not be found.

// Represents an application error with an optional detail.
// Application errors represent an expected error from the domain perspective.
// Infrastructure errors should use the standard errors package.
type Error struct {
Code string `json:"code"`
Detail error `json:"detail,omitempty"`
Expand Down
6 changes: 3 additions & 3 deletions pkg/http/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func Bind[TIn any](s Server, handler func(*gin.Context, TIn) error) gin.HandlerF
}

if err := handler(ctx, cmd); err != nil {
handleError(s, ctx, err)
HandleError(s, ctx, err)
}
}
}
Expand All @@ -39,7 +39,7 @@ func Bind[TIn any](s Server, handler func(*gin.Context, TIn) error) gin.HandlerF
func Send(s Server, handler func(*gin.Context) error) gin.HandlerFunc {
return func(ctx *gin.Context) {
if err := handler(ctx); err != nil {
handleError(s, ctx, err)
HandleError(s, ctx, err)
}
}
}
Expand Down Expand Up @@ -79,7 +79,7 @@ func Ok[TOut any](ctx *gin.Context, data TOut) error {
}

// Handle the given non-nil error and sets the status code based on error type.
func handleError(s Server, ctx *gin.Context, err error) {
func HandleError(s Server, ctx *gin.Context, err error) {
var (
status int = http.StatusInternalServerError
data any = ErrUnexpected
Expand Down

0 comments on commit 68aecc0

Please sign in to comment.