Documentation
¶
Index ¶
- Constants
- Variables
- func CapturePanicGlobal()
- func EchoMiddleware() echo.MiddlewareFunc
- func FlushLogs(ctx context.Context)
- func GinMiddleware() gin.HandlerFunc
- func HTTPMiddleware(next http.Handler) http.Handler
- func Init(cfg *Config) error
- func InitSimple() error
- func InitWithConfig(apiURL, service, token string) error
- func Log(ctx context.Context, level LogLevel, message string, attrs map[string]string)
- func LogSync(ctx context.Context, level LogLevel, message string, attrs map[string]string) error
- func NewSampler(cfg *Config) sdktrace.Sampler
- func ReportError(err error)
- func ReportErrorWithDetails(err error, file string, line int)
- func ReportException(message string)
- func ReportExceptionFromEcho(c echo.Context, message string)
- func ReportExceptionFromGin(c *gin.Context, message string)
- func ReportExceptionWithContext(ctx context.Context, err error)
- func SubmitApplicationError(name, message, file string, line, statusCode int, ...)
- type Client
- func (c *Client) CaptureCPUProfile(ctx context.Context, duration time.Duration) error
- func (c *Client) CaptureHeapProfile(ctx context.Context) error
- func (c *Client) CapturePanic()
- func (c *Client) GetMeter() metric.Meter
- func (c *Client) GetTracer() trace.Tracer
- func (c *Client) ReportCustomError(name, message, file string, line int) error
- func (c *Client) ReportCustomErrorWithHTTP(name, message, file string, line int, ...) error
- func (c *Client) ReportError(err error) error
- func (c *Client) ReportErrorWithDetails(err error, file string, line int) error
- func (c *Client) SetToken(token string)
- func (c *Client) Shutdown(ctx context.Context) error
- func (c *Client) SubmitApplicationError(name, message, file string, line, statusCode int, ...)
- type Config
- type HTTPStatusError
- type LogLevel
- type LogsSamplingConfig
- type Sampler
- type SamplingConfig
- type TracesSamplingConfig
Constants ¶
const KeyExceptionMessage = "middlemonitor_exception_message"
KeyExceptionMessage is the context key for storing the real error message when returning a 500 without exposing details to the client. The middleware reads this value and forwards it to Middle Monitor so the Errors view shows the actual cause rather than a generic "HTTP 500".
Echo: c.Set(middlemonitor.KeyExceptionMessage, err.Error()); return c.JSON(500, map[string]any{}) Gin: c.Set(middlemonitor.KeyExceptionMessage, err.Error()); c.JSON(500, map[string]any{})
Variables ¶
var ( ErrNotInitialized = errors.New("client not initialized") ErrConfigMissing = errors.New("config not initialized") ErrConfigRequired = errors.New("endpoint and token required") // client.go ErrResourceCreate = errors.New("failed to create resource") ErrTraceExport = errors.New("failed to create trace exporter") ErrMetricExport = errors.New("failed to create metric exporter") ErrConfigLoad = errors.New("failed to load config") ErrClientCreate = errors.New("failed to create client") ErrTracerShutdown = errors.New("failed to shutdown tracer provider") ErrMeterShutdown = errors.New("failed to shutdown meter provider") ErrShutdown = errors.New("shutdown failed") // log.go ErrMarshal = errors.New("marshal failed") ErrRequestCreate = errors.New("failed to create request") ErrLogSend = errors.New("failed to send logs") ErrLogExport = errors.New("log export failed") // profile.go ErrPprofRequest = errors.New("failed to create pprof request") ErrProfileInProgress = errors.New("cpu profile already in progress") ErrProfileFetch = errors.New("failed to fetch profile") ErrProfileRead = errors.New("failed to read profile") ErrProfileEmpty = errors.New("empty profile data") ErrMultipartBuild = errors.New("multipart build failed") ErrUploadRequest = errors.New("failed to create upload request") ErrProfileUpload = errors.New("profile upload failed") // config.go ErrSamplingConfig = errors.New("failed to parse sampling config") ErrSamplingValue = errors.New("invalid sampling value") ErrSamplingRange = errors.New("sampling must be between -1 and 1") ErrLogLevel = errors.New("invalid log level") ErrMinHTTPStatus = errors.New("invalid min http status") ErrBoolValue = errors.New("invalid boolean value") ErrErrorSubmit = errors.New("failed to submit error to backend") )
Functions ¶
func CapturePanicGlobal ¶
func CapturePanicGlobal()
CapturePanicGlobal captures a panic using the global client. Usage: defer middlemonitor.CapturePanicGlobal()
func EchoMiddleware ¶
func EchoMiddleware() echo.MiddlewareFunc
EchoMiddleware returns an Echo middleware that automatically creates traces and logs with OpenTelemetry Usage: e.Use(middlemonitor.EchoMiddleware())
func FlushLogs ¶
FlushLogs sends any buffered logs immediately. Call before shutdown to avoid losing logs.
func GinMiddleware ¶
func GinMiddleware() gin.HandlerFunc
GinMiddleware returns a Gin middleware that automatically creates traces and logs with OpenTelemetry Usage: r.Use(middlemonitor.GinMiddleware())
func HTTPMiddleware ¶ added in v0.1.3
HTTPMiddleware instruments any net/http handler: traces with OpenTelemetry, captures panics, and reports 5xx responses to the Errors view. It plugs into http.ServeMux, gorilla/mux (r.Use(middlemonitor.HTTPMiddleware)), chi, or a raw http.Handler chain.
net/http exposes no route template, so the raw URL path is used as the route for span names and sampling rules.
Usage: http.ListenAndServe(addr, middlemonitor.HTTPMiddleware(mux))
func Init ¶
Init initializes the global Middle-Monitor client with OpenTelemetry. It is safe to call more than once: the first successful client wins. A FAILED attempt is not remembered, so a caller can retry once the configuration is fixed — with sync.Once, one early failure used to disable the SDK for the whole process lifetime while returning nil to every later caller.
func InitWithConfig ¶
InitWithConfig initializes with explicit configuration (backward compatibility)
func Log ¶
Log sends a log record to Middle-Monitor. It buffers logs and flushes periodically. level: DEBUG, INFO, WARN, ERROR, FATAL, PANIC
func NewSampler ¶
NewSampler creates a new sampler with the given configuration
func ReportError ¶
func ReportError(err error)
ReportError reports an error using the global client.
func ReportErrorWithDetails ¶
ReportErrorWithDetails reports an error with file and line using the global client.
func ReportException ¶
func ReportException(message string)
ReportException sends the given message to Middle Monitor (e.g. from a background job). File/line are taken from the call stack. No HTTP code or URL — use ReportExceptionWithContext when in a request.
func ReportExceptionFromEcho ¶
ReportExceptionFromEcho reports an exception with only the message. Method, URL and file/line are read from the Echo context and the call stack; the HTTP code is assumed 500 (server error).
Example:
if err != nil {
middlemonitor.ReportExceptionFromEcho(c, err.Error())
return c.JSON(http.StatusInternalServerError, map[string]interface{}{})
}
func ReportExceptionFromGin ¶
ReportExceptionFromGin reports an exception with only the message. Method, URL and file/line are read from the Gin context and the call stack; the HTTP code is assumed 500 (server error).
Example:
if err != nil {
middlemonitor.ReportExceptionFromGin(c, err.Error())
c.JSON(http.StatusInternalServerError, map[string]interface{}{})
return
}
func ReportExceptionWithContext ¶
ReportExceptionWithContext reports an error to Middle Monitor. Pass the request context (e.g. c.Request().Context()) when inside an HTTP handler: method, URL and status 500 are then recovered automatically from the context set by the middleware. Outside a request, pass nil: only message and file/line from the stack are sent.
Example (Echo):
if err != nil {
middlemonitor.ReportExceptionWithContext(c.Request().Context(), err)
return c.JSON(http.StatusInternalServerError, map[string]interface{}{})
}
Example (Gin): middlemonitor.ReportExceptionWithContext(c.Request.Context(), err)
func SubmitApplicationError ¶
func SubmitApplicationError(name, message, file string, line, statusCode int, httpMethod, httpURL, requestBody string)
SubmitApplicationError reports an error to the Errors view using the global client.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client represents a Middle-Monitor OpenTelemetry client
func GetGlobalClient ¶
func GetGlobalClient() *Client
GetGlobalClient returns the global client, or nil when the SDK is not configured. Callers must handle nil: it is the normal state of an application that has not opted into Middle-Monitor.
func NewClientWithConfig ¶
NewClientWithConfig creates a new OpenTelemetry-based client from Config
func (*Client) CaptureCPUProfile ¶
CaptureCPUProfile collects a CPU profile for the given duration and uploads it to the Middle-Monitor API. It profiles this process directly; set Config.PprofURL to scrape an external pprof server instead.
func (*Client) CaptureHeapProfile ¶
CaptureHeapProfile collects a heap profile and uploads it to the Middle-Monitor API. It profiles this process directly; set Config.PprofURL to scrape an external pprof server instead.
func (*Client) CapturePanic ¶
func (c *Client) CapturePanic()
CapturePanic captures a panic and reports it to Middle-Monitor Usage: defer client.CapturePanic()
func (*Client) ReportCustomError ¶
ReportCustomError reports a named error with details.
func (*Client) ReportCustomErrorWithHTTP ¶
func (c *Client) ReportCustomErrorWithHTTP(name, message, file string, line int, httpMethod, httpURL, httpHeaders, httpBody string) error
ReportCustomErrorWithHTTP reports a named error with HTTP context.
func (*Client) ReportError ¶
ReportError reports an error to Middle-Monitor using OpenTelemetry.
func (*Client) ReportErrorWithDetails ¶
ReportErrorWithDetails reports an error with custom file and line using OpenTelemetry.
type Config ¶
type Config struct {
// OTLP endpoint (OTEL Collector or backend)
Endpoint string
// Insecure disables TLS (use HTTP instead of HTTPS). Set true for http:// or localhost.
Insecure bool
// Service information
Service string
Token string
// Export protocol (grpc or http, default: http)
Protocol string
// PprofURL points CaptureCPUProfile/CaptureHeapProfile at an external pprof
// HTTP server (e.g. http://localhost:6060) instead of profiling this
// process. Empty (the default) profiles in-process, with no socket to expose.
PprofURL string
// DisableHTTPErrorReporting stops the HTTP middlewares from submitting 5xx
// responses to the Errors view. Set it when the application already reports
// its own errors: otherwise every failure is recorded twice, once by the
// application with the real cause and once by the middleware with whatever
// the response body happens to carry. Panics are still always reported.
DisableHTTPErrorReporting bool
// Sampling configuration
Sampling SamplingConfig
}
Config represents the Middle-Monitor SDK configuration
func ConfigFromEnv ¶
ConfigFromEnv creates configuration from environment variables
func GetGlobalConfig ¶
func GetGlobalConfig() *Config
GetGlobalConfig returns the global configuration, or nil when the SDK is not configured.
type HTTPStatusError ¶ added in v0.1.2
HTTPStatusError carries a non-OK status code from an HTTP response.
func (*HTTPStatusError) Error ¶ added in v0.1.2
func (e *HTTPStatusError) Error() string
type LogsSamplingConfig ¶
type LogsSamplingConfig struct {
// Log levels to capture (default: [ERROR, FATAL, PANIC])
Levels []LogLevel
// Capture logs for HTTP status >= this code (default: 500)
// 4xx are customer-facing; only 5xx (and panics) are reported by default.
// 0 = disable HTTP status filtering
MinHTTPStatus int
// Capture all logs linked to a trace with error (default: true)
CaptureOnTraceError bool
// Routes to always capture logs (default: empty = all)
AlwaysCaptureRoutes []string
// Routes to never capture logs (default: ["/health", "/metrics", "/ready"])
NeverCaptureRoutes []string
}
LogsSamplingConfig configures log sampling
type Sampler ¶
type Sampler struct {
// contains filtered or unexported fields
}
Sampler implements OpenTelemetry sampling with custom rules
func (*Sampler) Description ¶
Description implements sdktrace.Sampler
func (*Sampler) ShouldSample ¶
func (s *Sampler) ShouldSample(params sdktrace.SamplingParameters) sdktrace.SamplingResult
ShouldSample implements sdktrace.Sampler
type SamplingConfig ¶
type SamplingConfig struct {
// Sampling for traces
Traces TracesSamplingConfig
// Sampling for logs
Logs LogsSamplingConfig
}
SamplingConfig configures sampling for traces and logs
func DefaultSamplingConfig ¶
func DefaultSamplingConfig() SamplingConfig
DefaultSamplingConfig returns the default sampling configuration.
type TracesSamplingConfig ¶
type TracesSamplingConfig struct {
// Percentage of traces to sample (0.0 - 1.0)
// -1 means auto (uses the default percentage)
Percentage float64
// Always sample traces with errors (default: true)
AlwaysSampleErrors bool
// Routes to always sample (default: empty = all)
AlwaysSampleRoutes []string
// Routes to never sample (default: ["/health", "/metrics", "/ready"])
NeverSampleRoutes []string
}
TracesSamplingConfig configures trace sampling