Ever spent hours staring at a blank terminal wondering what went wrong? With logging and monitoring, you can catch bugs before they turn into nightmares!
Why Logging Matters? (Because "It Works on My Machine" Isn't a Debugging Strategy!)
- Track Errors – Find bugs fast.
- Monitor Performance – Know when your app is slow.
- Audit Events – Keep logs of important actions.
Simple Logging with Go’s Built-in log
Package (Because fmt.Println()
is Not Logging!)
package main
import (
"log"
)
func main() {
log.Println("This is a log message!")
}
Why use log
?
- Adds timestamps automatically.
- Can redirect logs to files.
Logging to a File:
file, err := os.OpenFile("app.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
log.Fatal(err)
}
log.SetOutput(file)
log.Println("Logging to a file now!")
Advanced Logging with logrus
(Because You Deserve Pretty Logs!)
logrus
is a popular structured logging package:
go get github.com/sirupsen/logrus
Example usage:
import (
"github.com/sirupsen/logrus"
)
func main() {
logrus.SetFormatter(&logrus.JSONFormatter{})
logrus.WithFields(logrus.Fields{
"user": "Alice",
"action": "login",
}).Info("User logged in!")
}
Why logrus
?
- Supports JSON logs.
- Customizable log levels (Info, Warning, Error, etc.).
Monitoring with Prometheus (Because You Can’t Fix What You Can’t Measure!)
Step 1: Install Prometheus Client
go get github.com/prometheus/client_golang/prometheus
Step 2: Add a Metric
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"net/http"
)
var requestCount = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Total number of HTTP requests",
},
)
func main() {
prometheus.MustRegister(requestCount)
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":8080", nil)
}
Open http://localhost:8080/metrics
and see live stats!
Log Aggregation with Loki + Grafana (Because Logs Shouldn’t Be Scattered Everywhere!)
- Loki – Stores logs efficiently.
- Grafana – Visualizes logs beautifully.
Step 1: Run Loki & Grafana (Docker Version)
docker run -d --name=loki -p 3100:3100 grafana/loki:latest
docker run -d --name=grafana -p 3000:3000 grafana/grafana
Step 2: Add Logs to Loki
go get github.com/grafana/loki-client-go/loki
Use the client to push logs to Loki, then visualize them in Grafana!
Logging and monitoring aren’t just for production—they’re your superpowers for writing better software.
0 Comments