In Go applications, logging and monitoring are critical to health and observability. Best practices include choosing log levels based on importance and logging only necessary information. Use structured logging and centralized logging. Set up custom metrics and use monitoring tools like Prometheus. Set alert rules and integrate distributed tracing.
In the Go framework, logging and monitoring are important to the health and observability of the application Crucial. This article focuses on common logging and monitoring issues and provides best practices to help you effectively utilize these tools in your Go applications.
Configure logrus for structured logging
import ( "io" "github.com/sirupsen/logrus" ) func main() { // 创建一个带格式化程序的日志记录器 logger := logrus.New() logger.Formatter = &logrus.JSONFormatter{} // 记录一个结构化日志记录 logger.WithFields(logrus.Fields{ "level": "info", "module": "main", "message": "Application started", }).Info("Application started successfully") // 将日志记录写入文件 f, err := os.OpenFile("mylog.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { panic(err) } defer f.Close() logger.SetOutput(io.MultiWriter(f, os.Stdout)) }
Use Prometheus to collect custom indicators
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: "HTTP 请求总数", }, ) func main() { // 注册指标 prometheus.MustRegister(requestCount) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { // 增加请求计数 requestCount.Inc() // 发送响应 w.Write([]byte("Hello, world!")) }) // 导出指标 http.Handle("/metrics", promhttp.Handler()) http.ListenAndServe(":8080", nil) }
The above is the detailed content of Golang framework logging and monitoring common issues and best practices. For more information, please follow other related articles on the PHP Chinese website!