API Reference
Full reference for all exported functions in the statly package.
Initialization
Init(options)
Initialize the SDK. Call once at application startup.
func Init(options Options) errorParameters:
options- Configuration struct (see Configuration)
Returns: Error if already initialized or DSN is invalid.
Example:
import statly "github.com/KodyDennon/statly-go"
err := statly.Init(statly.Options{
DSN: "https://sk_live_xxx@statly.live/your-org",
Environment: "production",
})
if err != nil {
log.Fatal(err)
}Capturing Events
CaptureException(err)
Capture an error.
func CaptureException(err error) stringReturns: Event ID (UUID string)
Example:
_, err := riskyOperation()
if err != nil {
eventID := statly.CaptureException(err)
log.Printf("Captured event: %s", eventID)
}CaptureExceptionWithContext(err, ctx)
Capture an error with additional context.
func CaptureExceptionWithContext(err error, ctx map[string]interface{}) stringExample:
_, err := processOrder(orderID)
if err != nil {
statly.CaptureExceptionWithContext(err, map[string]interface{}{
"order_id": orderID,
"user_id": userID,
})
}CaptureMessage(message, level)
Capture a message event.
func CaptureMessage(message string, level Level) stringLevels:
statly.LevelDebugstatly.LevelInfostatly.LevelWarningstatly.LevelErrorstatly.LevelFatal
Example:
statly.CaptureMessage("Server started", statly.LevelInfo)
statly.CaptureMessage("High memory usage", statly.LevelWarning)CaptureMessageWithContext(message, level, ctx)
Capture a message with additional context.
func CaptureMessageWithContext(message string, level Level, ctx map[string]interface{}) stringPanic Recovery
Recover()
Recover from panics in the current goroutine. Use with defer.
func Recover()Behavior:
- Recovers the panic
- Captures it as an event with stack trace
- Flushes pending events
- Re-panics
Example:
func main() {
statly.Init(statly.Options{DSN: "..."})
defer statly.Close()
defer statly.Recover()
panic("something went wrong")
}RecoverWithContext(ctx)
Recover with additional context.
func RecoverWithContext(ctx map[string]interface{})Example:
func handleRequest(userID string) {
defer statly.RecoverWithContext(map[string]interface{}{
"user_id": userID,
"handler": "handleRequest",
})
// Code that might panic
}Context Management
SetUser(user)
Set user context for all future events.
func SetUser(user User)
type User struct {
ID string
Email string
Username string
IPAddr string
Data map[string]interface{} // Custom fields
}Example:
statly.SetUser(statly.User{
ID: "user_123",
Email: "user@example.com",
Username: "johndoe",
Data: map[string]interface{}{
"plan": "enterprise",
},
})SetTag(key, value)
Set a single tag.
func SetTag(key, value string)SetTags(tags)
Set multiple tags at once.
func SetTags(tags map[string]string)SetExtra(key, value)
Set extra context data.
func SetExtra(key string, value interface{})Breadcrumbs
AddBreadcrumb(crumb)
Add a breadcrumb to the trail.
func AddBreadcrumb(crumb Breadcrumb)
type Breadcrumb struct {
Message string
Category string
Level Level
Type string
Data map[string]interface{}
Timestamp time.Time // Auto-set if zero
}Example:
statly.AddBreadcrumb(statly.Breadcrumb{
Message: "User logged in",
Category: "auth",
Level: statly.LevelInfo,
})
statly.AddBreadcrumb(statly.Breadcrumb{
Message: "GET /api/orders",
Category: "http",
Level: statly.LevelInfo,
Data: map[string]interface{}{
"status": 200,
"duration_ms": 45,
},
})Scope Management
CurrentScope()
Get a clone of the current scope.
func CurrentScope() *ScopeWithScope(fn)
Execute function with a temporary scope.
func WithScope(fn func(*Scope))Note: In the current implementation, modifications to the scope inside WithScope are not persisted after the function returns.
Example:
statly.WithScope(func(scope *statly.Scope) {
scope.SetTag("request_id", requestID)
scope.SetUser(statly.User{ID: userID})
// These are local to this scope
})Lifecycle
Flush()
Wait for all pending events to be sent.
func Flush()Example:
statly.CaptureMessage("Shutting down", statly.LevelInfo)
statly.Flush() // Block until event is sentClose()
Flush and shut down the SDK.
func Close()Example:
func main() {
statly.Init(statly.Options{DSN: "..."})
defer statly.Close()
// Application code
}GetClient()
Get the SDK client instance.
func GetClient() *ClientTypes
Options
type Options struct {
DSN string
Environment string
Release string
Debug bool
SampleRate float64
MaxBreadcrumbs int
BeforeSend func(*Event) *Event
Transport Transport
ServerName string
FlushTimeout time.Duration
}Event
type Event struct {
EventID string
Timestamp time.Time
Level Level
Platform string // "go"
Message string
Exception []ExceptionValue
Contexts map[string]interface{}
Tags map[string]string
Extra map[string]interface{}
User *EventUser
Breadcrumbs []BreadcrumbValue
SDK SDKInfo
Environment string
Release string
ServerName string
Request *RequestInfo
}Level
type Level string
const (
LevelDebug Level = "debug"
LevelInfo Level = "info"
LevelWarning Level = "warning"
LevelError Level = "error"
LevelFatal Level = "fatal"
)Logger
The Logger provides structured logging with automatic scrubbing, batching, and session management.
NewLogger(options)
Create a new logger instance.
func NewLogger(options LoggerOptions) *LoggerExample:
import statly "github.com/KodyDennon/statly-go"
logger := statly.NewLogger(statly.LoggerOptions{
DSN: "https://sk_live_xxx@statly.live/your-org",
Environment: "production",
LoggerName: "api-server",
})
defer logger.Close()Logging Methods
Trace(message, data)
Log at trace level (ultra-detailed debugging).
logger.Trace("Entering function", map[string]interface{}{"args": []int{1, 2, 3}})Debug(message, data)
Log at debug level.
logger.Debug("Processing request", map[string]interface{}{"requestId": "req_123"})Info(message, data)
Log at info level.
logger.Info("User logged in", map[string]interface{}{"userId": "user_123"})Warn(message, data)
Log at warning level.
logger.Warn("Rate limit approaching", map[string]interface{}{"current": 95, "limit": 100})Error(message, data)
Log at error level.
logger.Error("Payment failed", map[string]interface{}{"orderId": "ord_456", "error": "Card declined"})Fatal(message, data)
Log at fatal level.
logger.Fatal("Database connection lost", map[string]interface{}{"host": "db.example.com"})Audit(message, data)
Log at audit level (security/compliance).
logger.Audit("User role changed", map[string]interface{}{"userId": "user_123", "newRole": "admin"})Child(options)
Create a child logger with inherited settings and additional context.
func (l *Logger) Child(options ChildLoggerOptions) *LoggerExample:
requestLogger := logger.Child(statly.ChildLoggerOptions{
Context: map[string]interface{}{"requestId": "req_123"},
LoggerName: "request-handler",
})
requestLogger.Info("Processing request", nil) // Includes requestIdSetUser(user)
Set user context for the logger.
func (l *Logger) SetUser(user LoggerUser)Example:
logger.SetUser(statly.LoggerUser{
ID: "user_123",
Email: "jane@example.com",
Name: "Jane Doe",
})Flush()
Flush all pending logs to the server.
func (l *Logger) Flush()Example:
// Before shutdown
logger.Flush()Close()
Flush and close the logger.
func (l *Logger) Close()Example:
func main() {
logger := statly.NewLogger(statly.LoggerOptions{DSN: "..."})
defer logger.Close()
// Application code
}LoggerOptions
type LoggerOptions struct {
DSN string
Environment string
Release string
LoggerName string
SessionID string // Auto-generated if empty
User *LoggerUser
DefaultContext map[string]interface{}
MinLevel LogLevel // Minimum level (default: Trace)
SampleRates map[LogLevel]float64
ScrubPatterns []*regexp.Regexp // Additional patterns to scrub
BatchSize int // Batch size (default: 50)
FlushInterval time.Duration // Flush interval (default: 5s)
MaxQueueSize int // Max queue size (default: 1000)
}LogLevel
type LogLevel int
const (
LogLevelTrace LogLevel = iota
LogLevelDebug
LogLevelInfo
LogLevelWarn
LogLevelError
LogLevelFatal
LogLevelAudit
)LoggerUser
type LoggerUser struct {
ID string
Email string
Name string
Data map[string]interface{} // Custom fields
}Sample Rates
Configure per-level sampling to control log volume:
logger := statly.NewLogger(statly.LoggerOptions{
DSN: "...",
SampleRates: map[statly.LogLevel]float64{
statly.LogLevelTrace: 0.01, // 1% of trace logs
statly.LogLevelDebug: 0.1, // 10% of debug logs
statly.LogLevelInfo: 0.5, // 50% of info logs
statly.LogLevelWarn: 1.0, // 100% of warnings
statly.LogLevelError: 1.0, // 100% of errors
statly.LogLevelFatal: 1.0, // 100% of fatal
},
})Secret Scrubbing
The logger automatically scrubs sensitive data. Add custom patterns:
logger := statly.NewLogger(statly.LoggerOptions{
DSN: "...",
ScrubPatterns: []*regexp.Regexp{
regexp.MustCompile(`my-custom-secret-[a-z0-9]+`),
regexp.MustCompile(`internal-token-\d+`),
},
})HTTP Middleware
Use the logger middleware to automatically log requests:
// Gin
router.Use(logger.GinMiddleware())
// Echo
e.Use(logger.EchoMiddleware())
// Standard http
http.Handle("/", logger.Middleware(handler))Each request logs:
- Request method and path
- Status code
- Duration
- User agent
- Client IP