Hey there, fellow developers! π Today, I want to share a practical guide on integrating Prometheus metrics with GoFrame applications. Whether you're new to monitoring or looking to enhance your existing setup, this guide will walk you through everything you need to know.
What We'll Cover
- Setting up Prometheus metrics in GoFrame
- Different types of metrics you can collect
- Real-world examples
- Best practices for metric collection
Why Prometheus?
Before we dive in, let's quickly understand why Prometheus is a solid choice for monitoring:
- Pull-based metrics collection
- Powerful query language (PromQL)
- Great integration with Grafana for visualization
- Active community and ecosystem
Getting Started
First, let's install the required component:
go get github.com/gogf/gf/contrib/metrics/prometheus/v2
Basic Configuration
Add this to your config.yaml
:
metrics:
prometheus:
Address: ":8080"
Route: "/metrics"
π‘ Pro tip: While :8080
works for development, consider using a different port in production to avoid conflicts with your main application.
Setting Up Metrics Collection
Here's the basic setup code:
import "github.com/gogf/gf/contrib/metrics/prometheus/v2"
func init() {
prometheus.Init()
}
Your First Metrics
Let's add some basic metrics to track API performance:
// Track request counts
prometheus.Counter.Inc("app_request_total", map[string]string{
"path": r.URL.Path,
"code": r.Response.Status,
})
// Track request duration
prometheus.Histogram.Observe("app_request_duration",
float64(r.LeaveTime-r.EnterTime)/1000,
map[string]string{
"path": r.URL.Path,
})
Different Types of Metrics
Here's where it gets interesting! Prometheus offers several metric types, each suited for different use cases:
Counters
Perfect for tracking total number of events:
// Track download count
prometheus.Counter.Inc("app_downloads_total",
map[string]string{"type": "pdf"})
Gauges
Great for values that go up and down:
// Track active users
prometheus.Gauge.Set("app_active_users", 100)
Histograms
Ideal for measuring distributions:
// Track API response times
prometheus.Histogram.Observe("app_response_time",
0.42,
map[string]string{"endpoint": "/api/users"})
Advanced Usage: Custom Collectors
Need something more specific? You can create custom collectors:
type UserMetrics struct {
UserTotal prometheus.Gauge
UserOnline prometheus.Gauge
}
func (c *UserMetrics) Collect(ch chan<- prometheus.Metric) {
// Get real-time data
c.UserTotal.Set(getUserCount())
c.UserOnline.Set(getOnlineCount())
ch <- c.UserTotal
ch <- c.UserOnline
}
// Add Describe method implementation...
Useful PromQL Queries
Here are some queries you might find useful:
# Request rate per second
rate(app_request_total[5m])
# 95th percentile latency
histogram_quantile(0.95, rate(app_request_duration_bucket[5m]))
# Error rate
sum(rate(app_request_total{code=~"5.."}[5m]))
/
sum(rate(app_request_total[5m]))
Best Practices
Choose Good Metric Names: Use prefixes like
app_
and follow the naming conventionnamespace_subsystem_name
Useful Labels: Add labels that help in troubleshooting, but don't overdo it:
map[string]string{
"service": "user-api",
"environment": "production",
"region": "us-west"
}
- Watch Cardinality: Be careful with labels that have many possible values (like user IDs)
Real-World Example
Here's a complete example combining everything we've learned:
package metrics
import (
"github.com/gogf/gf/contrib/metrics/prometheus/v2"
"github.com/prometheus/client_golang/prometheus"
)
type APIMetrics struct {
requestCount prometheus.Counter
requestLatency prometheus.Histogram
activeUsers prometheus.Gauge
}
func NewAPIMetrics() *APIMetrics {
m := &APIMetrics{
requestCount: prometheus.NewCounter(prometheus.CounterOpts{
Name: "app_requests_total",
Help: "Total API requests processed",
}),
// Add other metrics...
}
prometheus.MustRegister(m.requestCount)
return m
}
// Usage in your handler
func (m *APIMetrics) TrackRequest(path string, duration float64) {
m.requestCount.Inc()
m.requestLatency.Observe(duration)
}
What's Next?
Now that you have metrics set up, consider:
- Setting up Grafana dashboards
- Configuring alerts
- Adding more specific metrics for your use case
Wrapping Up
Monitoring is crucial for maintaining healthy applications in production. With GoFrame and Prometheus, you have a powerful combination for keeping track of your application's health and performance.
Have you implemented monitoring in your GoFrame applications? What metrics have you found most useful? Let me know in the comments!
Happy monitoring! π
If you found this helpful, don't forget to:
- Like and share this post
- Follow me for more Go-related content
- Check out my other articles on Go development
What metrics do you track in your applications? Share your experiences below! π
Top comments (0)