profilego

package module
v1.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2025 License: Apache-2.0 Imports: 13 Imported by: 2

README

profilego

GitHub tag (with filter) Go Reference Maintainability

Universal, safe, and easy-to-use Go profiling library that supports multiple profiling backends, provides robust concurrency safety, memory efficiency, and a delightful developer experience.

Features

  • Multiple Backends: Support for Pyroscope and pprof profiling backends
  • Thread-Safe: All operations are safe for concurrent use
  • Memory Efficient: Configurable memory limits to prevent excessive resource consumption
  • Secure: TLS support for secure communication with profiling servers
  • Easy Integration: Backward-compatible API with new enhanced functionality
  • Structured Logging: Uses Go's standard log/slog package for consistent logging

Installation

go get github.com/wasilak/profilego

Usage

Basic Usage (Legacy API)

The library maintains backward compatibility with the original API:

package main

import (
	"log"
	"time"
	"github.com/wasilak/profilego"
)

func main() {
	config := profilego.Config{
		ApplicationName: "my-app",
		ServerAddress:   "localhost:4040",
		Type:            "pyroscope", // or "pprof"
		Tags:            map[string]string{"version": "1.0.0"},
	}

	err := profilego.Init(config)
	if err != nil {
		log.Fatalf("Failed to initialize profiling: %v", err)
	}

	// Your application logic here
	time.Sleep(10 * time.Second)

	// Stop profiling before exiting
	err = profilego.Stop()
	if err != nil {
		log.Printf("Failed to stop profiling: %v", err)
	}
}
Advanced Usage (New API)

For more control, use the new configuration API:

package main

import (
	"log"
	"time"
	"github.com/wasilak/profilego"
	"github.com/wasilak/profilego/config"
	"github.com/wasilak/profilego/core"
)

func main() {
	// Initialize with new configuration API
	newConfig := config.Config{
		ApplicationName: "my-app",
		ServerAddress:   "localhost:4040",
		Backend:         core.PyroscopeBackend, // or core.PprofBackend
		Tags:            map[string]string{"env": "production", "version": "2.0"},
		ProfileTypes: []core.ProfileType{
			core.ProfileCPU,
			core.ProfileAllocObjects,
			core.ProfileGoroutines,
		},
		InitialState:    core.ProfilingEnabled,
		MemoryLimitMB:   50, // Set memory limit to 50MB
		EnableTLS:       true, // Enable TLS for secure communication
		SkipTLSVerify:   false, // Don't skip TLS verification in production
	}

	err := profilego.InitWithConfig(newConfig)
	if err != nil {
		log.Fatalf("Failed to initialize profiling: %v", err)
	}

	// Check if profiling is running
	if profilego.IsRunning() {
		log.Println("Profiling is active")
	}

	// Your application logic here
	time.Sleep(10 * time.Second)

	// Manually control profiling lifecycle
	err = profilego.Stop()
	if err != nil {
		log.Printf("Failed to stop profiling: %v", err)
	}
}

Configuration Options

The library provides extensive configuration options:

  • ApplicationName: Name of the application being profiled
  • Backend: Profiling backend (Pyroscope or pprof)
  • ServerAddress: Address of the profiling server
  • Tags: Key-value pairs for tagging profile data
  • ProfileTypes: Types of profiles to collect (CPU, memory, goroutines, etc.)
  • InitialState: Whether profiling starts enabled or disabled
  • MemoryLimitMB: Memory usage limit in MB
  • LogLevel: Logging level
  • Timeout: Timeout for profiler operations
  • EnableTLS: Enable TLS for server communication
  • TLSCertPath: Path to TLS certificate file
  • TLSKeyPath: Path to TLS key file
  • SkipTLSVerify: Skip TLS verification (not recommended for production)

Supported Profile Types

The library supports various profile types:

  • ProfileCPU: CPU profiling
  • ProfileAllocObjects: Allocated objects profiling
  • ProfileAllocSpace: Allocated space profiling
  • ProfileInuseObjects: In-use objects profiling
  • ProfileInuseSpace: In-use space profiling
  • ProfileGoroutines: Goroutine profiling
  • ProfileMutexCount: Mutex contention count
  • ProfileMutexDuration: Mutex contention duration
  • ProfileBlockCount: Block profiling count
  • ProfileBlockDuration: Block profiling duration

Memory Management

The library includes built-in memory management controls:

// Set memory limit to 100MB
newConfig.MemoryLimitMB = 100

// The profiler will check memory usage before starting
// and return an error if the limit would be exceeded

Security Features

TLS support is available for secure communication:

// Enable TLS for secure communication
newConfig.EnableTLS = true
newConfig.SkipTLSVerify = false // Only set to true for development
newConfig.TLSCertPath = "/path/to/cert.pem"
newConfig.TLSKeyPath = "/path/to/key.pem"

Thread Safety

All public methods are safe for concurrent use:

// Multiple goroutines can safely call profiling methods
go func() {
    profilego.IsRunning() // Safe to call from multiple goroutines
}()

go func() {
    profilego.Start() // Safe to call from multiple goroutines
}()

Contributing

We welcome contributions! Please see our contribution guidelines for more information.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddTag added in v1.3.0

func AddTag(key, value string) error

AddTag adds a key-value pair tag to the current profiling context This is a no-op for pprof backend as it doesn't support runtime tagging

func Context added in v1.3.0

func Context() context.Context

Context returns the context associated with the profiler This context is cancelled when Stop() is called

func Init deprecated

func Init(config Config, additionalAttrs ...any) error

Deprecated: Use InitWithConfig instead. This legacy function is maintained for backward compatibility but new code should use the more flexible InitWithConfig function with the new configuration format.

func InitWithConfig added in v1.1.0

func InitWithConfig(ctx context.Context, cfg config.Config) (context.Context, error)

InitWithConfig initializes profiling with the new configuration format. If ctx is nil, context.Background() is used. Returns the context used by the profiler for use throughout the application.

func IsRunning added in v1.1.0

func IsRunning() bool

IsRunning returns whether profiling is currently active

func SetTracerProvider added in v1.3.0

func SetTracerProvider(ctx context.Context, tp trace.TracerProvider) error

SetTracerProvider wraps and registers a TracerProvider globally. This is a convenience function combining WrapTracerProvider and otel.SetTracerProvider.

For Pyroscope backend, wraps the provided TracerProvider with Pyroscope integration. For other backends, registers the provider unchanged.

func Start added in v1.1.0

func Start() error

Start profiling if not already running

func Stop added in v1.1.0

func Stop(ctx ...context.Context) error

Stop stops profiling gracefully If ctx is provided, it's used for shutdown operations; otherwise the global context is used

func TagWrapper added in v1.3.0

func TagWrapper(ctx context.Context, key, value string, fn func(context.Context) error) error

TagWrapper executes a function with additional profiling tags The tags are only applied during the execution of the function The provided context is passed to the function For pprof backend, this simply executes the function without adding tags If ctx is nil, the global profiler context is used

func WrapTracerProvider added in v1.3.0

func WrapTracerProvider(ctx context.Context, tp trace.TracerProvider) (trace.TracerProvider, error)

WrapTracerProvider wraps a standard TracerProvider with Pyroscope profiling when using the Pyroscope backend. For other backends, returns the original provider.

This function is optional and allows users to integrate with OpenTelemetry without directly importing github.com/grafana/otel-profiling-go

If profiler is not initialized, returns an error. If backend is not Pyroscope, returns the original provider unchanged.

Types

type Config deprecated added in v1.0.6

type Config struct {
	ApplicationName string            `json:"application_name" validate:"required"`  // ApplicationName specifies the name of the application.
	ServerAddress   string            `json:"server_address"`                        // ServerAddress specifies the address of the profiling server.
	Type            string            `json:"type" validate:"oneof=pyroscope pprof"` // Type specifies the type of profiler.
	Tags            map[string]string `json:"tags"`                                  // Tags specifies the tags to be added to the profiler.
}

Deprecated: Use config.Config instead. This legacy configuration struct is maintained for backward compatibility but new code should use the more flexible config.Config struct with the new configuration format.

type ProfilingLogger

type ProfilingLogger struct{}

ProfilingLogger implements the logging interface required by profiling libraries

func (ProfilingLogger) DebugContext added in v1.1.0

func (p ProfilingLogger) DebugContext(ctx context.Context, msg string, args ...interface{})

DebugContext logs debug using the slog package with context

func (ProfilingLogger) Debugf

func (p ProfilingLogger) Debugf(msg string, params ...interface{})

func (ProfilingLogger) ErrorContext added in v1.1.0

func (p ProfilingLogger) ErrorContext(ctx context.Context, msg string, args ...interface{})

ErrorContext logs error using the slog package with context

func (ProfilingLogger) Errorf

func (p ProfilingLogger) Errorf(msg string, params ...interface{})

func (ProfilingLogger) InfoContext added in v1.1.0

func (p ProfilingLogger) InfoContext(ctx context.Context, msg string, args ...interface{})

InfoContext logs info using the slog package with context

func (ProfilingLogger) Infof

func (p ProfilingLogger) Infof(msg string, params ...interface{})

For backward compatibility with pyroscope library, implement the original methods using context functions

Directories

Path Synopsis
examples
advanced command
basic command
deprecated command
tagging command
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL