Skip to content

Latest commit

 

History

History
196 lines (153 loc) · 5.46 KB

go.md

File metadata and controls

196 lines (153 loc) · 5.46 KB

Go integration

Startup

import (
    "log/slog"
    "os"
    "os/signal"
    "syscall"

    "github.com/griffinwebnet/sh-trail/trail"
)

level, _ := trail.ParseLevel(os.Getenv("LOG_LEVEL"))   // "" is Debug
tr, err := trail.Init(trail.Options{
    Service: "my-api",
    Level:   level,
    File:    os.Getenv("LOG_FILE"),
})
if err != nil {
    return err
}
defer tr.Close()

// Route standard-library logging into the same trail, so startup, migrations
// and background work land in one file, and a slog call made during a request
// inherits that request's correlation for free.
slog.SetDefault(slog.New(trail.SlogHandler(level)))

DEBUG=true or SH_TRAIL_DEBUG=1 mirrors every record to stdout in addition to the file. trail.SetDebug(true) does the same at runtime.

Rotation

The package does not rotate. Reopen lets logrotate use its create mode, which loses no writes, unlike copytruncate, which races with them.

go func() {
    ch := make(chan os.Signal, 1)
    signal.Notify(ch, syscall.SIGHUP)
    for range ch {
        if err := tr.Reopen(); err != nil {
            slog.Error("reopen log", "error", err)
        }
    }
}()
/var/log/myapp/api.log {
    daily
    rotate 14
    create 0640 myapp myapp
    postrotate
        systemctl reload myapp
    endscript
}

The router

srv := &http.Server{Handler: httpmw.Wrap(mux)}

Wrap sits outermost. It works with any router, it only needs an http.Handler, and with net/http's ServeMux it records the matched route template rather than the raw path, so /sites/42 and /sites/97 are one line item instead of two thousand.

Options, all optional:

httpmw.Wrap(mux, httpmw.Options{
    Skip:     func(r *http.Request) bool { return r.URL.Path == "/healthz" },
    Actor:    func(r *http.Request) trail.Actor { ... },   // usually not needed
    RecordIn: true,   // also record arrivals; useful when requests hang
})

Identity

The package cannot know how your application resolves users, so tell it, from your own auth middleware, once:

trail.SetActor(ctx, trail.Actor{
    ID:     strconv.FormatInt(sess.UserID, 10),
    Tenant: strconv.FormatInt(sess.TenantID, 10),
})

Identity set part-way through a request appears on the closing record too. That is deliberate and non-obvious: a login does not know its user until the password verifies, and the request record is written after the handler returns.

Detail, where it pays

Baseline coverage needs none of this. Add it to flows where "a request happened" is not enough:

func (h *Handlers) Create(w http.ResponseWriter, r *http.Request) {
    ctx := r.Context()

    trail.Step(ctx, "store.quota_check ok", "used", used, "limit", limit)

    if used >= limit {
        trail.Outcome(ctx, "THING_REJECTED_QUOTA_EXCEEDED", "used", used)
        httpx.Error(w, 429, "quota", "Quota exceeded.")
        return
    }
    trail.Outcome(ctx, "THING_CREATED")
}

For a sub-operation worth timing on its own:

ctx, op := trail.Begin(ctx, "patrol.start")
defer op.End()          // no-op after OK/Fail; turns a forgotten return into INCOMPLETE
op.Step("route.loaded", "checkpoints", n)
op.OK("PATROL_STARTED")

Fail(code, err) logs at Error when err is non-nil and Warn when it is nil — a wrong password is expected behaviour, and if rejections log at Error then Error stops meaning anything.

Outcome codes

<DOMAIN>_<DISPOSITION>_<REASON>. REJECTED for a deliberate refusal, FAILED for a malfunction.

AUTH_OK
AUTH_REJECTED_BAD_PASSWORD
AUTH_REJECTED_UNKNOWN_USER
AUTH_FAILED_STORE_UNAVAILABLE

Define them as constants next to the handlers that emit them. They are your vocabulary; the package never invents one.

The trail may say more than the response does. Distinguishing AUTH_REJECTED_UNKNOWN_USER from AUTH_REJECTED_BAD_PASSWORD is exactly what makes a support call answerable, while both must produce a byte-identical 401 so the endpoint is not a user-enumeration oracle. That asymmetry is the point.

Secrets

op.Step("session.create ok", "ref", trail.Ref(token))   // ref=72254378

Ref is sha256(secret)[:8], enough to match the same token across records, useless to anyone reading them. Never log a password, a raw token, or an Authorization header, not even truncated.

Browser events

mux.Handle("POST /api/v1/events", ingest.Handler(ingest.Options{
    Actor: func(r *http.Request) trail.Actor { ... },   // optional attribution
    Allow: func(r *http.Request) bool { ... },          // optional rate limit
}))

Mount it without authentication. The events worth having most, a refused permission prompt, a crash on the sign-in screen, happen before anyone is signed in, and requiring a session discards exactly those. The handler always answers 204: a frontend must never break because its telemetry was rejected.

Your audit table

Record is the seam. Implement Sink, filter, write your own schema:

func (s auditSink) Write(r trail.Record) error {
    if r.Outcome == "" || r.Kind == trail.KindClient {
        return nil    // operational detail and telemetry are not audit rows
    }
    ...
}

Keep it low volume. Authentication, permission and account changes belong in a table; button presses and query timings belong in the file. The volume difference is roughly 50×.

Sink errors are swallowed by design, a logging pipeline that can fail a request is worse than one that occasionally loses a line, and the reporting channel is the thing that just broke.