Home
Softono
monigo

monigo

Open source Apache-2.0 CSS
409
Stars
19
Forks
4
Issues
4
Watchers
1 month
Last Commit

About monigo

MoniGo is a performance monitoring library for Go apps, offering real-time insights into service-level and function-level metrics. With an intuitive UI, it enables developers to track and optimize performance. Get your Go app's dashboard up in just 10 seconds!

Platforms

Web Self-hosted

Languages

CSS

monigo-icon

MoniGo - Runtime Observability for Go Applications

Go Report Card GoDoc License GitHub last commit Tests Visitors

MoniGo is a lightweight, embeddable observability library for Go services. It collects runtime metrics (CPU, memory, goroutines, disk/network I/O), traces function execution with pprof profiling, stores time-series data, and serves a real-time dashboard - all from a single go get.

monigo-gif

Features

  • Function-Level Tracing - Profile any function with CPU/memory pprof, adaptive sampling, and reflection-based argument capture
  • Pluggable Storage - Persistent disk (tstorage) or volatile in-memory backends
  • Real-Time Dashboard - Embedded web UI with system metrics, health scoring, goroutine inspection, and downloadable reports
  • Prometheus & OpenTelemetry - Built-in /metrics endpoint and OTLP/gRPC export
  • Router Integration - Works with net/http, Gin, Echo, Chi, Fiber, Gorilla Mux
  • Dashboard Security - Basic Auth, API Key, IP Whitelist, Rate Limiting middleware
  • Headless Mode - Run as a background telemetry agent without the dashboard
  • Builder API - Type-safe, chainable configuration with validation

Installation

go get github.com/iyashjayesh/monigo@latest

Requires Go 1.22+.

Quick Start

package main

import (
    "log"
    "math"
    "net/http"

    "github.com/iyashjayesh/monigo"
)

func main() {
    m := monigo.NewBuilder().
        WithServiceName("my-api").
        WithPort(8080).
        WithStorageType("memory").
        WithSamplingRate(100).
        Build()

    go func() {
        if err := m.Start(); err != nil {
            log.Fatalf("monigo: %v", err)
        }
    }()

    http.HandleFunc("/compute", func(w http.ResponseWriter, r *http.Request) {
        monigo.TraceFunction(r.Context(), heavyWork)
        w.Write([]byte("done"))
    })

    log.Fatal(http.ListenAndServe(":9000", nil))
}

func heavyWork() {
    var sum float64
    for i := 0; i < 1e8; i++ {
        sum += math.Sqrt(float64(i))
    }
}

Dashboard: http://localhost:8080 - Your app: http://localhost:9000

Configuration

All configuration is done via the builder pattern:

m := monigo.NewBuilder().
    WithServiceName("order-service").       // Required
    WithPort(8080).                         // Dashboard port (default: 8080)
    WithStorageType("disk").                // "disk" or "memory" (default: "disk")
    WithRetentionPeriod("7d").              // Data retention (default: "7d")
    WithDataPointsSyncFrequency("5m").      // Metric flush interval (default: "5m")
    WithSamplingRate(100).                  // Trace 1 in N calls (default: 100)
    WithMaxCPUUsage(90).                    // Health threshold (default: 95%)
    WithMaxMemoryUsage(90).                 // Health threshold (default: 95%)
    WithMaxGoRoutines(500).                 // Health threshold (default: 100)
    WithHeadless(false).                    // true = no dashboard (default: false)
    WithTimeZone("UTC").                    // Timezone (default: "Local")
    WithLogLevel(slog.LevelInfo).           // Log level
    WithOTelEndpoint("localhost:4317").      // OTLP gRPC endpoint
    WithOTelHeaders(map[string]string{      // OTel auth headers
        "Authorization": "Bearer <token>",
    }).
    Build()

Function Tracing

// Simple function
monigo.TraceFunction(ctx, myFunc)

// Function with arguments
monigo.TraceFunctionWithArgs(ctx, processOrder, orderID, userID)

// Function with single return
result := monigo.TraceFunctionWithReturn(ctx, calculateTotal, items).(float64)

// Function with multiple returns
results := monigo.TraceFunctionWithReturns(ctx, validateInput, data)
val := results[0].(string)
err := results[1].(error)

Each traced call captures: execution time, memory delta, goroutine delta, and (at sampling rate) CPU/memory pprof profiles.

Dashboard Security

mw, stop := monigo.RateLimitMiddleware(100, time.Minute)
defer stop()

m := monigo.NewBuilder().
    WithServiceName("secure-api").
    WithPort(8080).
    WithDashboardMiddleware(
        monigo.BasicAuthMiddleware("admin", "s3cret"),
        mw,
    ).
    WithAPIMiddleware(
        monigo.APIKeyMiddleware("my-api-key"),
    ).
    Build()

Router Integration

MoniGo integrates with any Go HTTP router:

// Standard net/http
mux := http.NewServeMux()
monigo.RegisterDashboardHandlers(mux)

// Fiber
app.All("/monigo/*", adaptor.HTTPHandler(monigo.GetUnifiedHandler()))

// Gin / Echo / Chi - use GetAPIHandlers() map
for path, handler := range monigo.GetAPIHandlers() {
    router.GET(path, gin.WrapF(handler))
}

See example/router-integration/ for complete examples.

API Endpoints

Method Path Description
GET /monigo/api/v1/metrics Current service statistics
GET /monigo/api/v1/service-info Service metadata
POST /monigo/api/v1/service-metrics Query time-series data
GET /monigo/api/v1/go-routines-stats Goroutine stack analysis
GET /monigo/api/v1/function Function trace summary
GET /monigo/api/v1/function-details pprof reports for a function
POST /monigo/api/v1/reports Aggregated report data
GET /metrics Prometheus scrape endpoint

Architecture

┌─────────────────────────────────────────────────┐
│                  Your Application                │
│                                                  │
│  monigo.TraceFunction(ctx, fn)                   │
│  monigo.Start() / monigo.Initialize()            │
└───────────┬─────────────────────┬────────────────┘
            │                     │
    ┌───────▼───────┐    ┌───────▼────────┐
    │   core/       │    │   monigo.go    │
    │  Metrics      │    │  Dashboard     │
    │  Collection   │    │  HTTP Server   │
    │  Health Score │    │  Middleware     │
    │  Profiling    │    │  Router Integ. │
    └───────┬───────┘    └───────┬────────┘
            │                     │
    ┌───────▼─────────────────────▼────────┐
    │           timeseries/                 │
    │  tstorage (disk) │ InMemoryStorage   │
    └───────┬──────────────────────────────┘
            │
    ┌───────▼───────────────────────────────┐
    │           exporters/                   │
    │  Prometheus Collector │ OTel Exporter  │
    └───────────────────────────────────────┘
            │
    ┌───────▼───────────────────────────────┐
    │           internal/                    │
    │  registry │ pipeline │ exporter │ log  │
    └───────────────────────────────────────┘

Package responsibilities:

Package Role
monigo (root) Public API, dashboard server, middleware, builder
core System metric collection, function tracing, health scoring
common Utilities, unit conversion, process info
timeseries Storage abstraction (disk + in-memory)
exporters Prometheus collector, OTel OTLP exporter
internal/registry Thread-safe metric registry
internal/pipeline Async metric export pipeline
internal/exporter Exporter interface + fan-out
internal/logger Race-safe structured logger (slog)
models Shared data structures
api HTTP handlers for all endpoints

What Works Well

  • Zero-dependency embedding - Single go get, no sidecar, no agent
  • Goroutine-safe metrics - Atomic sampling, mutex-protected maps, sync.Once singletons
  • Adaptive profiling - Sampling prevents pprof overhead in hot paths
  • Clean builder API - Validation at build time catches misconfiguration early
  • Race-free logger - atomic.Pointer eliminates the common slog data race

Examples

Example Path
Basic usage example/main.go
Function tracing example/function-trace-example/
Gin integration example/router-integration/gin-integration/
Echo integration example/router-integration/echo-integration/
Fiber integration example/router-integration/fiber-integration/
Standard mux example/router-integration/standard-mux-integration/
Gorilla mux example/router-integration/gorilla-mux-integration/
Basic auth example/security-examples/basic-auth/
API key auth example/security-examples/api-key/
IP whitelist example/security-examples/ip-whitelist-example/
Custom auth example/security-examples/custom-auth/

Documentation

Full guides and API reference: iyashjayesh.github.io/monigo-website

Topic Link
Introduction & Features Docs
Configuration (Builder API) Docs
Function Tracing Docs
Router Integration Docs
Dashboard Security Docs
Migration (v1 → v2) Docs

Contributing

We welcome contributions. Please see CONTRIBUTING.md for guidelines.

If you find MoniGo useful, consider giving it a star.

License

Apache 2.0 - see LICENSE.

Contact

For questions or feedback: open an issue or reach out at [email protected] / LinkedIn.

Star History

Star History Chart