Skip to content

Commit

Permalink
ref: use slog.Duration to log
Browse files Browse the repository at this point in the history
  • Loading branch information
thoas committed Sep 25, 2023
1 parent 6a8fafa commit def85e8
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 22 deletions.
35 changes: 18 additions & 17 deletions middleware/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,51 +3,52 @@ package middleware
import (
"context"
"fmt"
"log/slog"
"runtime"
"time"

"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/thoas/picfit/config"
"github.com/thoas/picfit/constants"
"log/slog"
"runtime"
"time"
)

func NewLogger(cfg *config.Config, logger *slog.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
path := c.Request.URL.Path

requestID := uuid.New().String()
var (
ctx = c.Request.Context()
start = time.Now()
path = c.Request.URL.Path
requestID = uuid.New().String()
)
c.Header("X-Request-ID", requestID)
c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), constants.RequestIDCtx, requestID))
c.Request = c.Request.WithContext(context.WithValue(ctx, constants.RequestIDCtx, requestID))

ctx = c.Request.Context()

c.Next()

end := time.Now()
latency := end.Sub(start)

attributes := []slog.Attr{
slog.Int("status", c.Writer.Status()),
slog.String("method", c.Request.Method),
slog.Any("params", c.Request.URL.Query()),
slog.String("path", path),
slog.String("ip", c.ClientIP()),
slog.String("latency", latency.String()),
slog.Duration("duration", time.Since(start)),
slog.String("user-agent", c.Request.UserAgent()),
slog.Time("time", end.UTC()),
}

if len(c.Errors) > 0 {
for _, e := range c.Errors.Errors() {
logger.LogAttrs(c.Request.Context(), slog.LevelError, e, attributes...)
logger.LogAttrs(ctx, slog.LevelError, e, attributes...)
}
} else {
logger.LogAttrs(c.Request.Context(), slog.LevelInfo, path, attributes...)
logger.LogAttrs(ctx, slog.LevelInfo, path, attributes...)
}
if cfg.Debug {
logMemStats(c.Request.Context(), logger)

}
logMemStats(ctx, logger)
}
}

Expand All @@ -63,7 +64,7 @@ func logMemStats(ctx context.Context, logger *slog.Logger) {
slog.String("numgc", fmt.Sprintf("%v", m.NumGC)),
slog.Int("total-goroutine", runtime.NumGoroutine()),
}
logger.LogAttrs(ctx, slog.LevelInfo, "memory stats", attributes...)
logger.LogAttrs(ctx, slog.LevelInfo, "Memory stats", attributes...)
}

func bToMb(b uint64) uint64 {
Expand Down
10 changes: 5 additions & 5 deletions processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func (p *Processor) Store(ctx context.Context, log *slog.Logger, filepath string

endtime := time.Now()
log.InfoContext(ctx, "Save file to storage",
slog.String("duration", endtime.Sub(starttime).String()),
slog.Duration("duration", endtime.Sub(starttime)),
)

starttime = time.Now()
Expand All @@ -82,7 +82,7 @@ func (p *Processor) Store(ctx context.Context, log *slog.Logger, filepath string
).Observe(endtime.Sub(starttime).Seconds())

log.InfoContext(ctx, "Save key to store",
slog.String("duration", endtime.Sub(starttime).String()),
slog.Duration("duration", endtime.Sub(starttime)),
)

// Write children info only when we actually want to be able to delete things.
Expand Down Expand Up @@ -261,7 +261,7 @@ func (p *Processor) ProcessContext(c *gin.Context, opts ...Option) (*image.Image
filesize := util.ByteCountDecimal(int64(len(img.Content())))
endtime := time.Now()
log.InfoContext(ctx, "Image retrieved from storage",
slog.String("duration", endtime.Sub(starttime).String()),
slog.Duration("duration", endtime.Sub(starttime)),
slog.String("size", filesize),
slog.String("image", img.Filepath))

Expand Down Expand Up @@ -351,7 +351,7 @@ func (p *Processor) processImage(c *gin.Context, storeKey string) (*image.ImageF
)

log.InfoContext(ctx, "Retrieved image to process from storage",
slog.String("duration", endtime.Sub(starttime).String()))
slog.Duration("duration", endtime.Sub(starttime)))

parameters, err := p.NewParameters(ctx, file, qs)
if err != nil {
Expand Down Expand Up @@ -382,7 +382,7 @@ func (p *Processor) processImage(c *gin.Context, storeKey string) (*image.ImageF
)

log.InfoContext(ctx, "Image processed",
slog.String("duration", endtime.Sub(starttime).String()))
slog.Duration("duration", endtime.Sub(starttime)))

if err := p.Store(ctx, log, filepath, file); err != nil {
return nil, errors.Wrapf(err, "unable to store processed image: %s", filepath)
Expand Down

0 comments on commit def85e8

Please sign in to comment.