In modern software development, especially for production-level applications, monitoring and logging are crucial components of the DevOps pipeline. They help developers understand application behavior, diagnose issues, and ensure high availability. This tutorial will guide you through setting up effective monitoring and logging in Go applications.
Go has several popular logging libraries:
For this tutorial, we'll use logrus due to its simplicity and flexibility.
go get github.com/sirupsen/logrus
Here's a simple example of how to set up logging in your Go application:
package main
import (
"github.com/sirupsen/logrus"
)
func main() {
// Set the log level
logrus.SetLevel(logrus.InfoLevel)
// Log a message with fields
logrus.WithFields(logrus.Fields{
"animal": "walrus",
"size": 10,
}).Info("A group of walrus emerges from the ocean")
// Log an error
err := someFunctionThatMightFail()
if err != nil {
logrus.WithError(err).Error("Failed to do something")
}
}
func someFunctionThatMightFail() error {
return fmt.Errorf("something went wrong")
}
Popular monitoring solutions include:
For this tutorial, we'll use Prometheus with Grafana.
You can download Prometheus from its official website or use Docker:
docker run -d --name prometheus -p 9090:9090 prom/prometheus
Create a prometheus.yml configuration file to scrape metrics from your Go application.
global:
scrape_interval: 15s
scrape_configs:
- job_name: 'go_app'
static_configs:
- targets: ['localhost:8080']
Use the prometheus/client_golang library to expose metrics:
go get github.com/prometheus/client_golang/prometheus
go get github.com/prometheus/client_golang/prometheus/promhttp
Here's how you can set up a simple HTTP server to expose metrics:
package main
import (
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
httpRequestsTotal = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Total number of HTTP requests.",
},
[]string{"method", "path"},
)
)
func init() {
// Register the metrics with Prometheus's default registry.
prometheus.MustRegister(httpRequestsTotal)
}
func handler(w http.ResponseWriter, r *http.Request) {
httpRequestsTotal.WithLabelValues(r.Method, r.URL.Path).Inc()
w.Write([]byte("Hello, world!"))
}
func main() {
http.HandleFunc("/", handler)
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":8080", nil)
}
Install Grafana using Docker:
docker run -d --name grafana -p 3000:3000 grafana/grafana
Access Grafana at http://localhost:3000 and add Prometheus as a data source.
You can create custom dashboards to visualize metrics from your Go application. Use the Prometheus query language (PromQL) to fetch and display metrics.
Effective monitoring and logging are essential for maintaining the health and reliability of your Go applications. By following this tutorial, you've learned how to set up basic logging with logrus and expose metrics using Prometheus. Combining these tools with Grafana provides a robust solution for monitoring and analyzing your application's performance.
Remember, continuous improvement is key in DevOps. Regularly review and refine your monitoring and logging strategies to adapt to the evolving needs of your applications.