Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Taskfile.dist.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,4 @@ tasks:
docs:
dir: docs
cmds:
- npm run dev
- bun run dev
2 changes: 1 addition & 1 deletion demo-app/cmd/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func main() {
})

// Add middleware to HTTP server. It will add trace ID to logs and responce headers
api.Use(httpserver.NewTraceIDMiddleware(nil, ""))
api.Use(log.NewTraceIDMiddleware(nil, ""))

// Create handler group
subApiGroup := httpserver.NewHandlerGroup()
Expand Down
2 changes: 1 addition & 1 deletion demo-app/cmd/auth/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func main() {
app.RegisterDomain("auth", "main", authDomain)

api := httpserver.New("8080", 3*time.Second)
api.Use(httpserver.NewTraceIDMiddleware(nil, ""))
api.Use(log.NewTraceIDMiddleware(nil, ""))
api.Use(httpserver.NewRecoverMiddleware())

api.HandleGroup("/auth", authDomain.HandleGroup)
Expand Down
31 changes: 31 additions & 0 deletions demo-app/cmd/wide-events/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package main

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

"github.com/platforma-dev/platforma/log3"
)

func main() {
logger := log3.NewWideEventLogger(
os.Stdout,
log3.NewDefaultSampler(3*time.Second, 200, 0.1),
"json",
nil,
)

ev := log3.NewEvent("test_event")

ev.AddStep(slog.LevelInfo, "some step")
ev.AddError(errors.New("some error"))
ev.AddAttrs(map[string]any{
"attr1": 1,
"attr2": true,
})

logger.WriteEvent(context.Background(), ev)
}
2 changes: 1 addition & 1 deletion docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"type": "module",
"version": "0.0.1",
"scripts": {
"dev": "astro dev",
"dev": "astro dev --host",
"start": "astro dev",
"build": "astro build",
"preview": "astro preview",
Expand Down
2 changes: 1 addition & 1 deletion log/log.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Package log provides structured logging functionality with context support.
package log
package log //nolint:revive

import (
"context"
Expand Down
12 changes: 5 additions & 7 deletions httpserver/traceid.go → log/traceid.go
Original file line number Diff line number Diff line change
@@ -1,26 +1,24 @@
package httpserver
package log

Check failure on line 1 in log/traceid.go

View workflow job for this annotation

GitHub Actions / lint

var-naming: avoid package names that conflict with Go standard library package names (revive)

import (
"context"
"net/http"

"github.com/platforma-dev/platforma/log"

"github.com/google/uuid"
)

// TraceIDMiddleware is a middleware that adds a trace ID to the request context and response headers.
// TraceIDMiddleware adds a trace ID to request context and response headers.
type TraceIDMiddleware struct {
contextKey any
header string
}

// NewTraceIDMiddleware returns a new TraceID middleware.
// If key is nil, log.TraceIdKey is used.
// If key is nil, TraceIDKey is used.
// If header is empty, "Platforma-Trace-Id" is used.
func NewTraceIDMiddleware(contextKey any, header string) *TraceIDMiddleware {
if contextKey == nil {
contextKey = log.TraceIDKey
contextKey = TraceIDKey
}

if header == "" {
Expand All @@ -30,7 +28,7 @@
return &TraceIDMiddleware{contextKey: contextKey, header: header}
}

// Wrap implements the Middleware interface by adding trace ID to requests.
// Wrap adds trace ID to requests.
func (m *TraceIDMiddleware) Wrap(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
traceID := uuid.NewString()
Expand Down
18 changes: 8 additions & 10 deletions httpserver/traceid_test.go → log/traceid_test.go
Original file line number Diff line number Diff line change
@@ -1,27 +1,26 @@
package httpserver_test
package log_test

import (
"net/http"
"net/http/httptest"
"testing"

"github.com/platforma-dev/platforma/httpserver"
"github.com/platforma-dev/platforma/log"
platformalog "github.com/platforma-dev/platforma/log"
)

func TestTraceIdMiddleware(t *testing.T) {
func TestTraceIDMiddleware(t *testing.T) {
t.Parallel()

t.Run("default params", func(t *testing.T) {
t.Parallel()

m := httpserver.NewTraceIDMiddleware(nil, "")
wrappedHandler := m.Wrap(&handler{serveHTTP: func(w http.ResponseWriter, r *http.Request) {
i, ok := r.Context().Value(log.TraceIDKey).(string)
m := platformalog.NewTraceIDMiddleware(nil, "")
wrappedHandler := m.Wrap(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
i, ok := r.Context().Value(platformalog.TraceIDKey).(string)
if ok {
w.Header().Add("TraceIdFromContext", i)
}
}})
}))

r := httptest.NewRequest(http.MethodGet, "/", nil)
w := httptest.NewRecorder()
Expand All @@ -34,8 +33,7 @@ func TestTraceIdMiddleware(t *testing.T) {
}

if len(resp.Header.Get("TraceIdFromContext")) == 0 {
t.Fatalf("trsce id from cotext expected, got: %s", resp.Header)
t.Fatalf("trace id from context expected, got: %s", resp.Header)
}

})
}
42 changes: 42 additions & 0 deletions log2/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Package log2 provides wide-event logging with tail sampling.
package log2

import (
"io"
"log/slog"
"os"
"time"
)

const (
defaultFormat = "json"
defaultKeepStatus = 500
defaultMaxSteps = 100
defaultRandomKeepRate = 0.05
defaultSlowThreshold = 2 * time.Second
)

// Config configures logger behavior.
type Config struct {
Writer io.Writer
Format string
Level slog.Level
ContextKeys map[string]any
Sampler TailSampler
MaxSteps int
}

// DefaultConfig returns default logger configuration.
func DefaultConfig() Config {
return Config{
Writer: os.Stdout,
Format: defaultFormat,
Level: slog.LevelInfo,
Sampler: NewDefaultTailSampler(DefaultTailSamplerConfig{
SlowThreshold: defaultSlowThreshold,
RandomKeepRate: defaultRandomKeepRate,
KeepStatusAtLeast: defaultKeepStatus,
}),
MaxSteps: defaultMaxSteps,
}
}
31 changes: 31 additions & 0 deletions log2/context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package log2

import "context"

type contextKey string

// LogEventContextKey is used to store Event in context.
const LogEventContextKey contextKey = "platformaLogEvent"

// EventFromContext gets an event from context.
func EventFromContext(ctx context.Context) (*Event, bool) {
if ctx == nil {
return nil, false
}

ev, ok := ctx.Value(LogEventContextKey).(*Event)
if !ok || ev == nil {
return nil, false
}

return ev, true
}

// WithEvent stores an event in context.
func WithEvent(ctx context.Context, ev *Event) context.Context {
if ctx == nil {
ctx = context.Background()
}

return context.WithValue(ctx, LogEventContextKey, ev)
}
Loading