### Run Go GC Analyzer Examples Source: https://github.com/kyungseok-lee/go-gc-analyzer/blob/main/README.md Instructions on how to execute the different example programs included with the go-gc-analyzer library. These examples demonstrate basic usage, advanced features, and monitoring capabilities. ```bash # Basic example go run examples/basic/main.go # Advanced features go run examples/advanced/main.go # Monitoring service go run examples/monitoring/main.go ``` -------------------------------- ### Install go-gc-analyzer Source: https://github.com/kyungseok-lee/go-gc-analyzer/blob/main/README_ko.md Installs the go-gc-analyzer library using the go get command. ```bash go get github.com/kyungseok-lee/go-gc-analyzer ``` -------------------------------- ### Install Go GC Analyzer Source: https://github.com/kyungseok-lee/go-gc-analyzer/blob/main/README.md Installs the go-gc-analyzer library into your Go project's workspace using the go get command. ```bash go get github.com/kyungseok-lee/go-gc-analyzer ``` -------------------------------- ### Go GC Analyzer Development Setup and Guidelines Source: https://github.com/kyungseok-lee/go-gc-analyzer/blob/main/README.md Steps for setting up a development environment for the go-gc-analyzer project and guidelines for contributing. This includes forking, branching, making changes, testing, committing, and submitting pull requests, along with coding standards. ```bash 1. Fork the repository 2. Create your feature branch (`git checkout -b feature/amazing-feature`) 3. Make your changes 4. Add tests for your changes 5. Run the test suite (`go test ./...`) 6. Commit your changes (`git commit -am 'Add amazing feature'`) 7. Push to the branch (`git push origin feature/amazing-feature`) 8. Open a Pull Request ``` -------------------------------- ### Run Monitoring Server Source: https://github.com/kyungseok-lee/go-gc-analyzer/blob/main/README_ko.md Starts a built-in HTTP monitoring server for the Go GC Analyzer, providing endpoints for metrics, health checks, analysis, and more. ```bash go run examples/monitoring/main.go ``` -------------------------------- ### Go GC Analyzer Integration with Prometheus/Grafana Source: https://github.com/kyungseok-lee/go-gc-analyzer/blob/main/README.md Example Go code demonstrating how to export metrics from the go-gc-analyzer library in a format compatible with Prometheus and Grafana. This involves creating a reporter and generating metrics. ```go reporter := analyzer.NewReporter(analysis, metrics, nil) err := reporter.GenerateGrafanaMetrics(w) ``` -------------------------------- ### Basic GC Analysis with CollectForDuration Source: https://github.com/kyungseok-lee/go-gc-analyzer/blob/main/README.md Demonstrates collecting GC metrics for a specified duration and performing a basic analysis. It shows how to retrieve GC frequency, average pause time, average heap size, and GC overhead. ```go package main import ( "context" "fmt" "time" "os" "github.com/kyungseok-lee/go-gc-analyzer/pkg/gcanalyzer" ) func main() { // Collect GC metrics for 10 seconds ctx := context.Background() metrics, err := gcanalyzer.CollectForDuration(ctx, 10*time.Second, time.Second) if err != nil { panic(err) } // Analyze the collected metrics analysis, err := gcanalyzer.Analyze(metrics) if err != nil { panic(err) } // Print analysis results fmt.Printf("GC Frequency: %.2f GCs/second\n", analysis.GCFrequency) fmt.Printf("Average Pause Time: %v\n", analysis.AvgPauseTime) fmt.Printf("Average Heap Size: %s\n", formatBytes(analysis.AvgHeapSize)) fmt.Printf("GC Overhead: %.2f%%\n", analysis.GCOverhead) // Generate a report gcanalyzer.GenerateSummaryReport(analysis, os.Stdout) } ``` -------------------------------- ### Go GC Analyzer Testing Commands Source: https://github.com/kyungseok-lee/go-gc-analyzer/blob/main/README.md A collection of essential commands for testing the go-gc-analyzer library. This includes running the full test suite, enabling verbose output, executing benchmarks, detecting race conditions, and generating coverage reports. ```bash # Run all tests go test ./... # Run with verbose output go test -v ./... # Run benchmarks go test -bench=. ./tests # Run with race detection go test -race ./... # Generate coverage report go test -coverprofile=coverage.out ./... go tool cover -html=coverage.out ``` -------------------------------- ### GC Performance Optimization Tips Source: https://github.com/kyungseok-lee/go-gc-analyzer/blob/main/README.md Offers practical strategies for optimizing Go garbage collection performance based on analysis results. Tips are categorized by common issues like high GC frequency, long pause times, high GC overhead, and memory leaks. ```APIDOC High GC Frequency: - Reduce allocation rate by reusing objects - Use object pools for frequently allocated objects - Increase `GOGC` value to trigger GC less frequently - Optimize data structures to reduce pointer indirection Long Pause Times: - Reduce heap size if possible - Minimize large object allocations - Use streaming processing instead of batching - Consider concurrent GC tuning (Go 1.19+) High GC Overhead: - Profile allocation hotspots with `go tool pprof` - Implement object pooling - Use value types instead of pointer types where possible - Optimize slice and map usage patterns Memory Leaks: - Check for goroutine leaks - Ensure proper cleanup of resources - Use weak references where appropriate - Monitor memory growth trends over time ``` -------------------------------- ### Continuous GC Monitoring with Callbacks Source: https://github.com/kyungseok-lee/go-gc-analyzer/blob/main/README.md Sets up continuous GC monitoring using a MonitorConfig, allowing for real-time metric collection and GC event handling via callbacks. It demonstrates how to log high GC CPU usage or long GC pauses. ```go package main import ( "context" "log" "time" "github.com/kyungseok-lee/go-gc-analyzer/pkg/gcanalyzer" ) func main() { config := &gcanalyzer.MonitorConfig{ Interval: time.Second, MaxSamples: 300, // Keep 5 minutes of data OnMetric: func(m *gcanalyzer.GCMetrics) { if m.GCCPUFraction > 0.1 { log.Printf("High GC CPU usage: %.2f%%", m.GCCPUFraction*100) } }, OnGCEvent: func(e *gcanalyzer.GCEvent) { if e.Duration > 10*time.Millisecond { log.Printf("Long GC pause: %v", e.Duration) } }, } monitor := gcanalyzer.NewMonitor(config) ctx := context.Background() err := monitor.Start(ctx) if err != nil { panic(err) } // Let it run for a while time.Sleep(1 * time.Minute) monitor.Stop() // Analyze collected data metrics := monitor.GetMetrics() if len(metrics) >= 2 { analysis, _ := gcanalyzer.Analyze(metrics) fmt.Printf("Analysis complete: %d recommendations\n", len(analysis.Recommendations)) for _, rec := range analysis.Recommendations { fmt.Printf("- %s\n", rec) } } } ``` -------------------------------- ### Basic GC Metrics Collection and Analysis Source: https://github.com/kyungseok-lee/go-gc-analyzer/blob/main/README_ko.md Demonstrates collecting GC metrics for a specified duration and interval, analyzing the collected data, and printing key GC statistics and a summary report. ```go package main import ( "context" "fmt" "os" "time" "github.com/kyungseok-lee/go-gc-analyzer/pkg/gcanalyzer" ) func main() { // 10초간 GC 메트릭 수집 ctx := context.Background() metrics, err := gcanalyzer.CollectForDuration(ctx, 10*time.Second, time.Second) if err != nil { panic(err) } // 수집된 메트릭 분석 analysis, err := gcanalyzer.Analyze(metrics) if err != nil { panic(err) } // 분석 결과 출력 fmt.Printf("GC 빈도: %.2f GCs/초\n", analysis.GCFrequency) fmt.Printf("평균 일시 정지 시간: %v\n", analysis.AvgPauseTime) fmt.Printf("평균 힙 크기: %s\n", formatBytes(analysis.AvgHeapSize)) fmt.Printf("GC 오버헤드: %.2f%%\n", analysis.GCOverhead) // 리포트 생성 gcanalyzer.GenerateSummaryReport(analysis, os.Stdout) } // Helper function to format bytes, assumed to be defined elsewhere or implicitly available func formatBytes(bytes uint64) string { // Placeholder for actual byte formatting logic return fmt.Sprintf("%d bytes", bytes) } ``` -------------------------------- ### Monitor Configuration Struct Source: https://github.com/kyungseok-lee/go-gc-analyzer/blob/main/README.md Defines the configuration options for the GC monitoring process. This includes setting the collection interval, maximum samples to retain, and callback functions for alerts and metrics. ```go type MonitorConfig struct { // Collection interval (default: 1 second) Interval time.Duration // Maximum samples to keep in memory (default: 1000) MaxSamples int // Alert callback function OnAlert func(*Alert) // Metric collection callback OnMetric func(*GCMetrics) // GC event callback OnGCEvent func(*GCEvent) } ``` -------------------------------- ### GC Metrics Understanding Source: https://github.com/kyungseok-lee/go-gc-analyzer/blob/main/README.md Provides guidance on interpreting common GC metrics and their implications for application performance. It categorizes metrics like GC Frequency, Pause Times, GC Overhead, and Memory Efficiency into performance levels. ```APIDOC GC Frequency: - Low (< 1 GC/s): Excellent, minimal GC pressure - Medium (1-5 GC/s): Good, normal application behavior - High (> 5 GC/s): Consider optimization, reduce allocation rate Pause Times: - Excellent (< 1ms): Low-latency applications - Good (1-10ms): Most applications - Needs attention (> 10ms): May impact responsiveness - Critical (> 100ms): Immediate optimization needed GC Overhead: - Excellent (< 5%): Minimal GC impact - Good (5-15%): Acceptable for most applications - High (15-25%): Consider tuning - Critical (> 25%): Significant performance impact Memory Efficiency: - Excellent (> 80%): Efficient memory usage - Good (60-80%): Normal usage - Poor (< 60%): Memory fragmentation or inefficient allocation patterns ``` -------------------------------- ### Monitoring Server Endpoints Source: https://github.com/kyungseok-lee/go-gc-analyzer/blob/main/README.md Lists the available HTTP endpoints for the built-in monitoring server, providing access to GC metrics, health checks, analysis, and Prometheus metrics. ```APIDOC Monitoring Server Endpoints: - GET /metrics: Retrieves current GC metrics in JSON format. - GET /health: Returns the health check status of the application. - GET /analysis: Provides a full GC analysis report. - GET /prometheus: Exposes GC metrics in Prometheus exposition format. - GET /trend: Shows memory usage trends over time. - GET /distribution: Displays the distribution of GC pause times. ``` -------------------------------- ### GCAnalysis Struct Definition Source: https://github.com/kyungseok-lee/go-gc-analyzer/blob/main/README.md Contains comprehensive analysis results for garbage collection. It includes metrics like GC frequency, average pause times, heap size, allocation rate, and performance recommendations. ```go type GCAnalysis struct { Period time.Duration // Analysis period GCFrequency float64 // GCs per second AvgPauseTime time.Duration // Average pause time P95PauseTime time.Duration // 95th percentile pause time P99PauseTime time.Duration // 99th percentile pause time AvgHeapSize uint64 // Average heap size AllocRate float64 // Allocation rate (bytes/second) GCOverhead float64 // GC CPU overhead percentage MemoryEfficiency float64 // Memory efficiency percentage Recommendations []string // Performance recommendations // ... more fields } ``` -------------------------------- ### GC Collection Functions Source: https://github.com/kyungseok-lee/go-gc-analyzer/blob/main/README.md Provides functions to collect garbage collection metrics. It supports collecting a single snapshot or collecting metrics over a specified duration with a given interval. ```go // Collect a single snapshot func CollectOnce() *GCMetrics // Collect for a specific duration func CollectForDuration(ctx context.Context, duration, interval time.Duration) ([]*GCMetrics, error) ``` -------------------------------- ### Go GC Analyzer JSON Serialization Source: https://github.com/kyungseok-lee/go-gc-analyzer/blob/main/README.md Illustrates how to serialize analysis results from the go-gc-analyzer library into JSON format. This is useful for integrating the library's output with other systems or APIs. ```go analysis, _ := gcAnalyzer.Analyze() data, _ := json.Marshal(analysis) ``` -------------------------------- ### Alert Thresholds Struct Source: https://github.com/kyungseok-lee/go-gc-analyzer/blob/main/README.md Specifies the thresholds for triggering alerts during GC monitoring. It includes limits for GC frequency, pause times, GC overhead, and minimum health scores. ```go type AlertThresholds struct { MaxGCFrequency float64 // GCs per second MaxPauseTime time.Duration // Maximum pause time MaxGCOverhead float64 // Maximum GC CPU percentage MinHealthScore int // Minimum health score } ``` -------------------------------- ### GCMetrics Struct Definition Source: https://github.com/kyungseok-lee/go-gc-analyzer/blob/main/README.md Represents a snapshot of GC metrics at a specific point in time. It includes details like the number of GCs, total pause time, heap allocation, and CPU fraction used by GC. ```go type GCMetrics struct { NumGC uint32 // Number of GCs PauseTotalNs uint64 // Total pause time in nanoseconds HeapAlloc uint64 // Current heap allocation TotalAlloc uint64 // Total bytes allocated Sys uint64 // Total bytes from OS GCCPUFraction float64 // Fraction of CPU time in GC Timestamp time.Time // Collection timestamp // ... more fields } ``` -------------------------------- ### Go GC Analyzer Health Check Generation Source: https://github.com/kyungseok-lee/go-gc-analyzer/blob/main/README.md Shows how to generate a health check status using the go-gc-analyzer library's reporter. This output can be consumed by health monitoring systems to determine the application's status. ```go healthCheck := reporter.GenerateHealthCheck() if healthCheck.Status != "healthy" { // Alert or take action } ``` -------------------------------- ### GC Reporting Functions Source: https://github.com/kyungseok-lee/go-gc-analyzer/blob/main/README.md Enables the generation of various reports based on GC analysis results and collected metrics. Supports text, JSON, and summary reports, as well as health check status. ```go // Generate various report formats func GenerateTextReport(analysis *GCAnalysis, metrics []*GCMetrics, events []*GCEvent, w io.Writer) error func GenerateJSONReport(analysis *GCAnalysis, metrics []*GCMetrics, events []*GCEvent, w io.Writer, indent bool) error func GenerateSummaryReport(analysis *GCAnalysis, w io.Writer) error // Generate health check func GenerateHealthCheck(analysis *GCAnalysis) *HealthCheckStatus ``` -------------------------------- ### GC Analysis Functions Source: https://github.com/kyungseok-lee/go-gc-analyzer/blob/main/README.md Offers functions to perform analysis on collected GC metrics. These functions can analyze metrics alone or in conjunction with GC events to provide insights and data trends. ```go // Perform analysis on metrics func Analyze(metrics []*GCMetrics) (*GCAnalysis, error) // Perform analysis with both metrics and events func AnalyzeWithEvents(metrics []*GCMetrics, events []*GCEvent) (*GCAnalysis, error) // Get memory trend data func GetMemoryTrend(metrics []*GCMetrics) []MemoryPoint // Get pause time distribution func GetPauseTimeDistribution(events []*GCEvent) map[string]int ``` -------------------------------- ### Continuous GC Monitoring Source: https://github.com/kyungseok-lee/go-gc-analyzer/blob/main/README_ko.md Sets up a continuous GC monitor with custom callbacks for GC events and metrics. It logs high GC CPU usage or long GC pauses and performs analysis on collected data after a period. ```go package main import ( "context" "fmt" "log" "time" "github.com/kyungseok-lee/go-gc-analyzer/pkg/gcanalyzer" ) func main() { config := &gcanalyzer.MonitorConfig{ Interval: time.Second, MaxSamples: 300, // 5분간의 데이터 보관 OnMetric: func(m *gcanalyzer.GCMetrics) { if m.GCCPUFraction > 0.1 { log.Printf("높은 GC CPU 사용률: %.2f%%", m.GCCPUFraction*100) } }, OnGCEvent: func(e *gcanalyzer.GCEvent) { if e.Duration > 10*time.Millisecond { log.Printf("긴 GC 일시 정지: %v", e.Duration) } }, } monitor := gcanalyzer.NewMonitor(config) ctx := context.Background() err := monitor.Start(ctx) if err != nil { panic(err) } // 1분간 실행 time.Sleep(1 * time.Minute) monitor.Stop() // 수집된 데이터 분석 metrics := monitor.GetMetrics() if len(metrics) >= 2 { analysis, _ := gcanalyzer.Analyze(metrics) fmt.Printf("분석 완료: %d개의 권장사항\n", len(analysis.Recommendations)) for _, rec := range analysis.Recommendations { fmt.Printf("- %s\n", rec) } } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.