Sobes.tech
Middle

Wie integriert man den Standard-Profiler in seine Go-Anwendung?

sobes.tech KI

Antwort von AI

Das Paket net/http/pprof stellt HTTP-Handler für Profildaten bereit.

Importieren Sie es:

import (
	"net/http"
	_ "net/http/pprof" // Es ist wichtig, '_' für die Initialisierung mit Nebeneffekten zu verwenden
)

Starten Sie einen HTTP-Server in einer separaten Goroutine:

go func() {
	// Server auf der lokalen Adresse und dem Standard-pprof-Port starten
	if err := http.ListenAndServe("localhost:6060", nil); err != nil {
		// Fehler beim Serverstart behandeln, z.B. protokollieren
		// log.Printf("pprof-Server fehlgeschlagen: %v", err)
	}
}()

Sie können jetzt auf Profildaten unter http://localhost:6060/debug/pprof/ zugreifen.

Hauptendpunkte:

  • /debug/pprof/: Hauptseite mit der Liste der verfügbaren Profile.
  • /debug/pprof/heap: Heap-Profil.
  • /debug/pprof/goroutine: Aktive Goroutine-Profile.
  • /debug/pprof/block: Profil von Blockierungen.
  • /debug/pprof/threadcreate: Profil der Thread-Erstellung des Betriebssystems.
  • /debug/pprof/cmdline: Befehlszeile der Anwendung.
  • /debug/pprof/profile: CPU-Profil (standardmäßig 30 Sekunden Daten sammeln).
  • /debug/pprof/trace: Trace-Profil der Ausführung (standardmäßig 1 Sekunde Daten sammeln).

Zur Analyse von CPU-, Heap- und Blockierungsprofilen wird in der Regel das Tool go tool pprof verwendet:

go tool pprof http://localhost:6060/debug/pprof/profile # CPU-Profil für 30 Sekunden
go tool pprof http://localhost:6060/debug/pprof/heap # Heap-Profil

Zur Analyse von Trace-Daten wird das Tool go tool trace verwendet:

go tool trace http://localhost:6060/debug/pprof/trace

Wichtig: Denken Sie an die Sicherheit und öffnen Sie den pprof-Port nicht öffentlich ohne Autorisierung in der Produktion.