Skip to content

Commit

Permalink
perf: logger print trace info
Browse files Browse the repository at this point in the history
  • Loading branch information
OldSmokeGun committed Nov 29, 2023
1 parent 71e3db2 commit b4c6ec4
Show file tree
Hide file tree
Showing 6 changed files with 68 additions and 17 deletions.
5 changes: 4 additions & 1 deletion internal/app/adapter/server/http/middleware/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/pkg/errors"

"go-scaffold/internal/app/domain"
)
Expand Down Expand Up @@ -98,7 +99,9 @@ func Auth(config AuthConfig) echo.MiddlewareFunc {
}

user, err := config.TokenValidator.ValidateToken(c.Request().Context(), token)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
return err
} else if err != nil {
return echo.NewHTTPError(http.StatusUnauthorized, "malformed token").SetInternal(err)
}

Expand Down
2 changes: 1 addition & 1 deletion internal/app/adapter/server/http/middleware/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
func Logger(logger *slog.Logger) echo.MiddlewareFunc {
return middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
LogValuesFunc: func(c echo.Context, v middleware.RequestLoggerValues) error {
logger.Info("request",
logger.InfoContext(c.Request().Context(), "request",
slog.String("id", v.RequestID),
slog.String("remote_ip", v.RemoteIP),
slog.String("host", v.Host),
Expand Down
4 changes: 2 additions & 2 deletions internal/app/adapter/server/http/router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,10 @@ func New(
func (r *router) useMiddlewares(e *echo.Echo) {
e.HTTPErrorHandler = imiddleware.ErrorHandler(e.Debug, r.logger)
e.JSONSerializer = imiddleware.JSONSerializer()
e.Use(middleware.RequestID())
e.Use(imiddleware.Recover(r.logger))
e.Use(imiddleware.Logger(r.logger))
e.Use(middleware.RequestID())
e.Use(otelecho.Middleware(r.appName.String()))
e.Use(imiddleware.Logger(r.logger))
}

func (r *router) useRoutes(e *echo.Echo) {
Expand Down
5 changes: 3 additions & 2 deletions internal/command/base.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import (
"go-scaffold/pkg/ioutils"
"go-scaffold/pkg/log"
iklog "go-scaffold/pkg/log/kratos"
tlog "go-scaffold/pkg/log/otel"
otlog "go-scaffold/pkg/log/otel"
"go-scaffold/pkg/trace"
)

Expand Down Expand Up @@ -155,7 +155,7 @@ func (c *baseCmd) initTrace(cmd *cobra.Command) {
traceConfig.Endpoint,
trace.WithServiceName(appName.String()),
trace.WithEnv(appEnv.String()),
trace.WithErrorLogger(tlog.NewLogger(c.logger)),
trace.WithErrorLogger(otlog.NewLogger(c.logger)),
)
if err != nil {
panic(err)
Expand All @@ -168,6 +168,7 @@ func (c *baseCmd) initTrace(cmd *cobra.Command) {
))

c.trace = tracing
c.logger = log.NewWithHandler(otlog.NewHandler(c.logger.Handler()))
}

func (c *baseCmd) closeConfig() {
Expand Down
27 changes: 16 additions & 11 deletions pkg/log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,40 +79,45 @@ func WithAttrs(attrs []slog.Attr) Option {

// New build *slog.Logger
func New(options ...Option) *slog.Logger {
logger := &config{
c := &config{
level: DefaultLevel,
format: DefaultFormat,
writer: DefaultWriter,
}

for _, opf := range options {
opf(logger)
for _, option := range options {
option(c)
}

ops := &slog.HandlerOptions{
AddSource: true,
Level: logger.level.Convert(),
Level: c.level.Convert(),
ReplaceAttr: ReplaceAttr,
}

var handler slog.Handler
if logger.format == Text {
handler = slog.NewTextHandler(logger.writer, ops)
if c.format == Text {
handler = slog.NewTextHandler(c.writer, ops)
} else {
handler = slog.NewJSONHandler(logger.writer, ops)
handler = slog.NewJSONHandler(c.writer, ops)
}

if logger.group != "" {
handler = handler.WithGroup(logger.group)
if c.group != "" {
handler = handler.WithGroup(c.group)
}

if len(logger.attrs) > 0 {
handler = handler.WithAttrs(logger.attrs)
if len(c.attrs) > 0 {
handler = handler.WithAttrs(c.attrs)
}

return slog.New(handler)
}

// NewWithHandler build *slog.Logger with slog Handler
func NewWithHandler(handler slog.Handler) *slog.Logger {
return slog.New(handler)
}

// Format log format
type Format string

Expand Down
42 changes: 42 additions & 0 deletions pkg/log/otel/handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package otel

import (
"context"
"log/slog"

sdktrace "go.opentelemetry.io/otel/trace"
)

const (
TraceIDLogKey = "trace_id"
SpanIDLogKey = "span_id"
)

// Handler slog handler
type Handler struct {
slog.Handler
}

func NewHandler(handler slog.Handler) *Handler {
return &Handler{Handler: handler}
}

func (h *Handler) Handle(ctx context.Context, record slog.Record) error {
spanCtx := sdktrace.SpanContextFromContext(ctx)

var attrs []slog.Attr

if spanCtx.HasTraceID() {
attrs = append(attrs, slog.String(TraceIDLogKey, spanCtx.TraceID().String()))
}

if spanCtx.HasSpanID() {
attrs = append(attrs, slog.String(SpanIDLogKey, spanCtx.SpanID().String()))
}

if len(attrs) > 0 {
record.Add("trace", slog.GroupValue(attrs...))
}

return h.Handler.Handle(ctx, record)
}

0 comments on commit b4c6ec4

Please sign in to comment.