Documentation
¶
Overview ¶
Package xrayhq is a lightweight, drop-in observability library for Go web applications. It provides request tracing, database query instrumentation, external call tracking, and a real-time dashboard — all with zero external dependencies for storage.
xrayhq captures detailed per-request traces including latency, TTFB, request/response bodies, headers, DB queries (database/sql, GORM), Redis commands, MongoDB operations, and outbound HTTP calls. It automatically detects N+1 queries, slow routes, high error rates, memory spikes, and panics via a built-in alert engine.
Quick Start ¶
func main() {
xrayhq.Init(xrayhq.WithPort(":9090"))
handler := xrayhq.Wrap(yourMux)
http.ListenAndServe(":8080", handler)
}
The dashboard is then available at http://localhost:9090.
Framework Support ¶
xrayhq includes middleware for Chi, Echo, Gin, and Fiber in addition to the standard net/http middleware.
Index ¶
- func AddDBQuery(ctx context.Context, q DBQuery)
- func AddExternalCall(ctx context.Context, c ExternalCall)
- func AddMongoOp(ctx context.Context, op MongoOp)
- func AddRedisOp(ctx context.Context, op RedisOp)
- func ChiMiddleware(next http.Handler) http.Handler
- func EchoMiddleware() echo.MiddlewareFunc
- func FiberAddDBQuery(c *fiber.Ctx, q DBQuery)
- func FiberMiddleware() fiber.Handler
- func GinMiddleware() gin.HandlerFunc
- func Init(opts ...Option)
- func MongoMonitor() *event.CommandMonitor
- func NewDashboardServer(collector *Collector, config *Config) *http.Server
- func RedisHook() redis.Hook
- func SetRoutePattern(r *http.Request, pattern string)
- func Wrap(handler http.Handler) http.Handler
- func WrapFunc(handler http.HandlerFunc) http.Handler
- func WrapHTTPClient(client *http.Client) *http.Client
- type Alert
- type AlertEngine
- type Collector
- func (c *Collector) AddAlert(a Alert)
- func (c *Collector) GetAlerts() []Alert
- func (c *Collector) GetAllRequests() []*RequestTrace
- func (c *Collector) GetRecentRequests(limit int) []*RequestTrace
- func (c *Collector) GetRequestByID(id string) *RequestTrace
- func (c *Collector) GetRequestsForRoute(method, pattern string, limit int) []*RequestTrace
- func (c *Collector) GetRoute(method, pattern string) *RouteMetrics
- func (c *Collector) GetRoutes() []*RouteMetrics
- func (c *Collector) Record(trace *RequestTrace)
- func (c *Collector) RequestCount() int
- func (c *Collector) SubscribeSSE() chan *RequestTrace
- func (c *Collector) UnsubscribeSSE(ch chan *RequestTrace)
- func (c *Collector) Uptime() time.Duration
- type Config
- type DBPoolStats
- type DBQuery
- type DashboardServer
- type ExternalCall
- type GORMPlugin
- type Mode
- type MongoOp
- type Option
- func WithBasicAuth(user, pass string) Option
- func WithBufferSize(size int) Option
- func WithCaptureBody(capture bool) Option
- func WithCaptureHeaders(capture bool) Option
- func WithHighErrorRate(pct float64) Option
- func WithLatencyCap(n int) Option
- func WithMemorySpikeThreshold(bytes uint64) Option
- func WithMode(mode Mode) Option
- func WithNPlusOneThreshold(n int) Option
- func WithPort(port string) Option
- func WithSamplingRate(rate float64) Option
- func WithSlowQueryThreshold(d time.Duration) Option
- func WithSlowRouteThreshold(d time.Duration) Option
- type RedisOp
- type RequestTrace
- type RouteMetrics
- func (rm *RouteMetrics) AvgLatency() time.Duration
- func (rm *RouteMetrics) ErrorRate() float64
- func (rm *RouteMetrics) P50() time.Duration
- func (rm *RouteMetrics) P95() time.Duration
- func (rm *RouteMetrics) P99() time.Duration
- func (rm *RouteMetrics) Percentile(p float64) time.Duration
- func (rm *RouteMetrics) Record(trace *RequestTrace)
- func (rm *RouteMetrics) Snapshot() *RouteMetrics
- func (rm *RouteMetrics) Status() string
- type Severity
- type WrappedDB
- func (w *WrappedDB) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
- func (w *WrappedDB) PoolStats() DBPoolStats
- func (w *WrappedDB) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
- func (w *WrappedDB) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AddDBQuery ¶
func AddExternalCall ¶
func AddExternalCall(ctx context.Context, c ExternalCall)
func AddMongoOp ¶
func AddRedisOp ¶
func ChiMiddleware ¶
ChiMiddleware is a Chi-compatible middleware that captures request data.
func EchoMiddleware ¶
func EchoMiddleware() echo.MiddlewareFunc
EchoMiddleware returns an Echo middleware that captures request data.
func FiberAddDBQuery ¶
FiberAddDBQuery adds a DB query to the Fiber request trace.
func FiberMiddleware ¶
FiberMiddleware returns a Fiber middleware that captures request data.
func GinMiddleware ¶
func GinMiddleware() gin.HandlerFunc
GinMiddleware returns a Gin middleware that captures request data.
func Init ¶
func Init(opts ...Option)
Init initializes xrayhq with the given options and starts the dashboard server.
func MongoMonitor ¶
func MongoMonitor() *event.CommandMonitor
MongoMonitor returns a *event.CommandMonitor that instruments MongoDB operations.
func NewDashboardServer ¶
func SetRoutePattern ¶
SetRoutePattern sets the route pattern on the trace in context. Framework adapters call this to record the matched route pattern.
Types ¶
type AlertEngine ¶
type AlertEngine struct {
// contains filtered or unexported fields
}
func NewAlertEngine ¶
func NewAlertEngine(collector *Collector, config *Config) *AlertEngine
func (*AlertEngine) Evaluate ¶
func (e *AlertEngine) Evaluate(trace *RequestTrace)
type Collector ¶
type Collector struct {
// contains filtered or unexported fields
}
func GetCollector ¶
func GetCollector() *Collector
GetCollector returns the default collector (for advanced usage).
func NewCollector ¶
func (*Collector) GetAllRequests ¶
func (c *Collector) GetAllRequests() []*RequestTrace
func (*Collector) GetRecentRequests ¶
func (c *Collector) GetRecentRequests(limit int) []*RequestTrace
func (*Collector) GetRequestByID ¶
func (c *Collector) GetRequestByID(id string) *RequestTrace
func (*Collector) GetRequestsForRoute ¶
func (c *Collector) GetRequestsForRoute(method, pattern string, limit int) []*RequestTrace
func (*Collector) GetRoute ¶
func (c *Collector) GetRoute(method, pattern string) *RouteMetrics
func (*Collector) GetRoutes ¶
func (c *Collector) GetRoutes() []*RouteMetrics
func (*Collector) Record ¶
func (c *Collector) Record(trace *RequestTrace)
func (*Collector) RequestCount ¶
func (*Collector) SubscribeSSE ¶
func (c *Collector) SubscribeSSE() chan *RequestTrace
func (*Collector) UnsubscribeSSE ¶
func (c *Collector) UnsubscribeSSE(ch chan *RequestTrace)
type Config ¶
type Config struct {
Port string
BufferSize int
Mode Mode
SamplingRate float64
CaptureBody bool
CaptureHeaders bool
BasicAuthUser string
BasicAuthPass string
SlowQueryThreshold time.Duration
SlowRouteP95Threshold time.Duration
HighErrorRatePercent float64
NPlusOneThreshold int
MemorySpikeBytes uint64
LatencyCap int
}
func DefaultConfig ¶
func DefaultConfig() *Config
type DBPoolStats ¶
type DashboardServer ¶
type DashboardServer struct {
// contains filtered or unexported fields
}
type ExternalCall ¶
type GORMPlugin ¶
type GORMPlugin struct{}
GORMPlugin implements gorm.Plugin for query instrumentation.
func NewGORMPlugin ¶
func NewGORMPlugin() *GORMPlugin
func (*GORMPlugin) Initialize ¶
func (p *GORMPlugin) Initialize(db *gorm.DB) error
func (*GORMPlugin) Name ¶
func (p *GORMPlugin) Name() string
type Option ¶
type Option func(*Config)
func WithBasicAuth ¶
func WithBufferSize ¶
func WithCaptureBody ¶
func WithCaptureHeaders ¶
func WithHighErrorRate ¶
func WithLatencyCap ¶
func WithNPlusOneThreshold ¶
func WithSamplingRate ¶
func WithSlowQueryThreshold ¶
func WithSlowRouteThreshold ¶
type RequestTrace ¶
type RequestTrace struct {
ID string
Method string
Path string
RoutePattern string
QueryParams string
RequestHeaders map[string]string
RequestBody []byte
ResponseStatus int
ResponseHeaders map[string]string
ResponseBody []byte
RequestSize int64
ResponseSize int64
ClientIP string
UserAgent string
StartTime time.Time
EndTime time.Time
Latency time.Duration
TTFB time.Duration
HandlerTime time.Duration
GoroutinesBefore int
GoroutinesAfter int
MemAllocBefore uint64
MemAllocAfter uint64
DBQueries []DBQuery
TotalDBTime time.Duration
ExternalCalls []ExternalCall
TotalExtTime time.Duration
RedisOps []RedisOp
TotalRedisTime time.Duration
MongoOps []MongoOp
TotalMongoTime time.Duration
Panicked bool
PanicValue interface{}
PanicStack string
Alerts []Alert
}
func FiberTraceFromContext ¶
func FiberTraceFromContext(c *fiber.Ctx) *RequestTrace
FiberTraceFromContext retrieves the trace from Fiber locals.
func TraceFromContext ¶
func TraceFromContext(ctx context.Context) *RequestTrace
type RouteMetrics ¶
type RouteMetrics struct {
Pattern string
Method string
TotalRequests int64
ErrorCount int64 // 5xx responses
TotalLatency time.Duration
Latencies []time.Duration // for percentile calculation - capped at 10000
StatusCodes map[int]int64
AvgDBQueries float64
MinLatency time.Duration
MaxLatency time.Duration
LastRequestTime time.Time
// contains filtered or unexported fields
}
func NewRouteMetrics ¶
func NewRouteMetrics(pattern, method string, latencyCap int) *RouteMetrics
func (*RouteMetrics) AvgLatency ¶
func (rm *RouteMetrics) AvgLatency() time.Duration
func (*RouteMetrics) ErrorRate ¶
func (rm *RouteMetrics) ErrorRate() float64
func (*RouteMetrics) P50 ¶
func (rm *RouteMetrics) P50() time.Duration
func (*RouteMetrics) P95 ¶
func (rm *RouteMetrics) P95() time.Duration
func (*RouteMetrics) P99 ¶
func (rm *RouteMetrics) P99() time.Duration
func (*RouteMetrics) Percentile ¶
func (rm *RouteMetrics) Percentile(p float64) time.Duration
func (*RouteMetrics) Record ¶
func (rm *RouteMetrics) Record(trace *RequestTrace)
func (*RouteMetrics) Snapshot ¶
func (rm *RouteMetrics) Snapshot() *RouteMetrics
func (*RouteMetrics) Status ¶
func (rm *RouteMetrics) Status() string
type WrappedDB ¶
WrappedDB wraps a *sql.DB to capture query metrics.
func (*WrappedDB) ExecContext ¶
func (*WrappedDB) PoolStats ¶
func (w *WrappedDB) PoolStats() DBPoolStats
PoolStats returns the current DB pool statistics.