### Install go-logger Library Source: https://context7.com/pr0ger/go-logger/llms.txt This command installs the go-logger library using the go get command. Ensure you have Go installed and configured in your environment. ```bash go get -u go.pr0ger.dev/logger ``` -------------------------------- ### Configure SentryCore Logging in Go Source: https://context7.com/pr0ger/go-logger/llms.txt Initializes Sentry and configures a logger with SentryCore. This setup allows for custom log levels for breadcrumbs and events, maps specific zap fields to Sentry user properties (ID, Email, Username, IPAddress, Name, Segment), and extracts generic zap fields as Sentry tags. The example logs an error with user and tag data, showing how fields like 'amount' are retained in extras. ```go package main import ( "github.com/getsentry/sentry-go" "go.pr0ger.dev/logger" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) func main() { _ = sentry.Init(sentry.ClientOptions{Dsn: "https://your-dsn@sentry.io/project"}) core := logger.NewSentryCore( sentry.CurrentHub(), // BreadcrumbLevel: minimum level for breadcrumb capture (default: Debug) logger.BreadcrumbLevel(zapcore.InfoLevel), // EventLevel: minimum level for Sentry event creation (default: Error) logger.EventLevel(zapcore.WarnLevel), // UserTags: map zap fields to Sentry user properties logger.UserTags(logger.SentryUserTagMap{ ID: "userId", // zap field "userId" -> Sentry User.ID Email: "email", // zap field "email" -> Sentry User.Email Username: "username", // zap field "username" -> Sentry User.Username IPAddress: "ip", // zap field "ip" -> Sentry User.IPAddress Name: "displayName", // zap field "displayName" -> Sentry User.Name Segment: "plan", // zap field "plan" -> Sentry User.Segment }), // GenericTags: zap fields to extract as Sentry tags logger.GenericTags("environment", "version", "service", "region"), ) log := zap.New(core) // These fields are extracted as Sentry user and tags log.Error("payment failed", zap.String("userId", "user-123"), zap.String("email", "user@example.com"), zap.String("environment", "production"), zap.String("version", "2.1.0"), zap.String("service", "payment-api"), zap.Float64("amount", 99.99), // Remains in extras ) } ``` -------------------------------- ### Go: Create and Configure Zap Logger with Sentry Integration Source: https://github.com/pr0ger/go-logger/blob/master/README.md This snippet demonstrates how to set up a Zap logger integrated with Sentry. It involves creating a local core for stdout/stderr logging, wrapping it with a Sentry core, and then initializing the Zap logger. This setup allows for simultaneous logging to local destinations and Sentry, with specific handling for request breadcrumbs. ```go import ( "fmt" "net/http" "go.pr0ger.dev/logger" "go.uber.org/zap" "github.com/getsentry/sentry-go" ) // Create core for logging to stdout/stderr localCore := logger.NewCore(true) // Create core splitter to logging both to local and sentry // zapcore.NewTee also can be used, but is not recommended if you want to use RequestLogger middleware core := logger.NewSentryCoreWrapper(localCore, sentry.CurrentHub()) // And create logger log := zap.New(core) log.Debug("this event will be logged to stdout but will not appear in request breadcrumbs") // Create an HTTP client with our transport client := http.Client{ Transport: logger.NewBreadcrumbTransport(sentry.LevelInfo, http.DefaultTransport), } // We need to pass current context to HTTP request so transport will know where to log // Example usage within an HTTP handler: handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log := logger.Ctx(r.Context()) log.Debug("some debug logs from request") req, _ := http.NewRequestWithContext(r.Context(), http.MethodGet, "https://go.pr0ger.dev/logger", nil) resp, err := client.Do(req) if err != nil { log.Warn("request failed", zap.Error(err)) } else { log.Info(fmt.Sprintf("Response status: %s", resp.Status)) resp.Body.Close() } log.Error("let's assume we have an error here") }) // And use it with our middleware server := &http.Server{ Addr: ":8080", Handler: logger.RequestLogger(log)(handler), } _ = server.ListenAndServe() ``` -------------------------------- ### Create Local Logging Core with go-logger Source: https://context7.com/pr0ger/go-logger/llms.txt Demonstrates creating a zap core with sensible defaults for local logging. It splits output between stdout (info and below) and stderr (error and above), using JSON encoding for production or console encoding for development. ```go package main import ( "go.pr0ger.dev/logger" "go.uber.org/zap" ) func main() { // Create core for development with console output devCore := logger.NewCore(true) devLogger := zap.New(devCore) devLogger.Info("info message goes to stdout") devLogger.Error("error message goes to stderr") // Create core for production with JSON output prodCore := logger.NewCore(false) prodLogger := zap.New(prodCore) prodLogger.Info("json formatted info", zap.String("key", "value")) // Output: {"level":"info","ts":1699999999.999,"msg":"json formatted info","key":"value"} } ``` -------------------------------- ### Create Combined Local and Sentry Core with go-logger Source: https://context7.com/pr0ger/go-logger/llms.txt Demonstrates creating a zap core that duplicates log entries to both a local core (stdout/stderr) and Sentry. This is the recommended approach for production use with the RequestLogger middleware. It allows for both local visibility and remote error tracking. ```go package main import ( "github.com/getsentry/sentry-go" "go.pr0ger.dev/logger" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) func main() { _ = sentry.Init(sentry.ClientOptions{ Dsn: "https://your-dsn@sentry.io/project", }) // Create local core for console/file output localCore := logger.NewCore(true) // Wrap with Sentry core combinedCore := logger.NewSentryCoreWrapper( localCore, sentry.CurrentHub(), logger.BreadcrumbLevel(zapcore.DebugLevel), logger.EventLevel(zapcore.ErrorLevel), ) log := zap.New(combinedCore) // Goes to both stdout AND stored as Sentry breadcrumb log.Debug("application starting", zap.String("version", "1.0.0")) // Goes to stdout as breadcrumb + creates Sentry event log.Error("critical failure", zap.Error(err)) } ``` -------------------------------- ### Context Management for Loggers and Sentry Hubs (Go) Source: https://context7.com/pr0ger/go-logger/llms.txt Provides functions to store and retrieve loggers and Sentry hubs from the request context, enabling request-scoped logging. Functions include Ctx, WithLogger, Hub, and WithHub. It also includes helpers for managing request IDs within the context. Dependencies include 'context', 'github.com/getsentry/sentry-go', 'go.pr0ger.dev/logger', and 'go.uber.org/zap'. ```go package main import ( "context" "github.com/getsentry/sentry-go" "go.pr0ger.dev/logger" "go.uber.org/zap" ) func main() { _ = sentry.Init(sentry.ClientOptions{Dsn: "https://your-dsn@sentry.io/project"}) log := zap.NewExample() // Store logger in context ctx := logger.WithLogger(context.Background(), log) // Retrieve logger from context (returns no-op logger if not found) ctxLog := logger.Ctx(ctx) ctxLog.Info("logged from context") // Store Sentry hub in context hub := sentry.NewHub(sentry.CurrentHub().Client(), sentry.NewScope()) ctx = logger.WithHub(ctx, hub) // Retrieve hub from context (returns CurrentHub() if not found) ctxHub := logger.Hub(ctx) ctxHub.CaptureMessage("message from context hub") // Request ID helpers ctx = logger.WithRequestID(ctx, "req-12345") requestId := logger.RequestID(ctx) // "req-12345" } // Use in service layers func processOrder(ctx context.Context, orderID string) error { log := logger.Ctx(ctx) log.Info("processing order", zap.String("orderId", orderID)) // All logs inherit request context and breadcrumbs if err := validateOrder(ctx, orderID); err != nil { log.Error("validation failed", zap.Error(err)) return err } return nil } ``` -------------------------------- ### Create Sentry-Only Logging Core with go-logger Source: https://context7.com/pr0ger/go-logger/llms.txt Shows how to create a zap core that sends all log entries to Sentry. Debug-level logs are stored as breadcrumbs, while error-level and above are sent as events. Supports configuration options for customizing log levels and tag mappings. ```go package main import ( "github.com/getsentry/sentry-go" "github.com/pkg/errors" "go.pr0ger.dev/logger" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) func main() { _ = sentry.Init(sentry.ClientOptions{ Dsn: "https://your-dsn@sentry.io/project", Transport: sentry.NewHTTPSyncTransport(), }) // Basic Sentry core core := logger.NewSentryCore(sentry.CurrentHub()) log := zap.New(core) log.Debug("stored as breadcrumb", zap.Int("userId", 42)) log.Info("also a breadcrumb") log.Error("creates Sentry event with breadcrumb trail") // With custom options customCore := logger.NewSentryCore( sentry.CurrentHub(), logger.BreadcrumbLevel(zapcore.InfoLevel), // Only info+ as breadcrumbs logger.EventLevel(zapcore.WarnLevel), // Warn+ create events logger.UserTags(logger.SentryUserTagMap{ ID: "user_id", Email: "user_email", Username: "username", }), logger.GenericTags("environment", "version"), ) customLog := zap.New(customCore) customLog.Warn("this creates event", zap.String("user_id", "123"), zap.String("user_email", "user@example.com"), zap.String("environment", "production"), ) // Errors with stack traces err := errors.Wrap(errors.New("database error"), "failed to fetch user") log.Error("operation failed", zap.Error(err)) // Sentry receives full error chain with stack traces } ``` -------------------------------- ### HTTP Request Logging Middleware with Sentry Integration (Go) Source: https://context7.com/pr0ger/go-logger/llms.txt This middleware injects a request-scoped logger and Sentry hub into the request context. It automatically captures request metadata, provides isolated breadcrumb trails, and supports distributed tracing. Dependencies include the 'github.com/getsentry/sentry-go' and 'go.pr0ger.dev/logger' packages. ```go package main import ( "net/http" "github.com/getsentry/sentry-go" "go.pr0ger.dev/logger" "go.uber.org/zap" ) func main() { _ = sentry.Init(sentry.ClientOptions{ Dsn: "https://your-dsn@sentry.io/project", TracesSampleRate: 1.0, }) // Create combined local + Sentry logger localCore := logger.NewCore(true) core := logger.NewSentryCoreWrapper(localCore, sentry.CurrentHub()) log := zap.New(core) // Define your handler handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Get request-scoped logger from context log := logger.Ctx(r.Context()) log.Debug("processing request") log.Info("user authenticated", zap.String("userId", "123")) // Any error here will have request breadcrumbs attached log.Error("something went wrong", zap.Error(err)) w.Write([]byte("ok")) }) // Wrap with RequestLogger middleware server := &http.Server{ Addr: ":8080", Handler: logger.RequestLogger(log)(handler), } // Automatically logs on request completion: // - Request duration // - Response status code // - Response size // - HTTP method and URL // - Client IP server.ListenAndServe() } ``` -------------------------------- ### Create Isolated Logger Instance (Go) Source: https://context7.com/pr0ger/go-logger/llms.txt The ForkedLogger function creates a new logger with an isolated Sentry hub, which is beneficial for background goroutines requiring their own distinct breadcrumb trail separate from the parent request. This utility helps in maintaining separate Sentry scopes for different execution contexts. It depends on 'go.uber.org/zap' and 'go.pr0ger.dev/logger'. ```go package main import ( "github.com/getsentry/sentry-go" "go.pr0ger.dev/logger" "go.uber.org/zap" ) func main() { _ = sentry.Init(sentry.ClientOptions{Dsn: "https://your-dsn@sentry.io/project"}) localCore := logger.NewCore(true) core := logger.NewSentryCoreWrapper(localCore, sentry.CurrentHub()) mainLogger := zap.New(core) mainLogger.Info("main logger breadcrumb") // Create forked logger for background work backgroundLogger := logger.ForkedLogger(mainLogger) go func() { // This goroutine has isolated breadcrumbs backgroundLogger.Debug("background task started") backgroundLogger.Info("processing item") backgroundLogger.Error("background error") // Event has only background breadcrumbs }() mainLogger.Error("main error") // Event has only main breadcrumbs } ``` -------------------------------- ### Add Custom Fields to Request Logger Middleware (Go) Source: https://context7.com/pr0ger/go-logger/llms.txt This middleware allows adding custom fields to the request-scoped logger based on request data. It must be used after the RequestLogger middleware. It takes a function that returns a slice of zap.Field, which are then included in all log messages for that request. Dependencies include 'go.pr0ger.dev/logger' and 'go.uber.org/zap'. ```go package main import ( "net/http" "github.com/getsentry/sentry-go" "go.pr0ger.dev/logger" "go.uber.org/zap" ) func main() { _ = sentry.Init(sentry.ClientOptions{Dsn: "https://your-dsn@sentry.io/project"}) localCore := logger.NewCore(true) core := logger.NewSentryCoreWrapper(localCore, sentry.CurrentHub()) log := zap.New(core) handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log := logger.Ctx(r.Context()) // Logger now includes requestId and tenantId in all messages log.Info("handling request") w.Write([]byte("ok")) }) // Chain middlewares withFields := logger.WithExtraFields(func(r *http.Request) []zap.Field { return []zap.Field{ zap.String("requestId", r.Header.Get("X-Request-ID")), zap.String("tenantId", r.Header.Get("X-Tenant-ID")), } }) server := &http.Server{ Addr: ":8080", Handler: logger.RequestLogger(log)(withFields(handler)), } server.ListenAndServe() } ``` -------------------------------- ### HTTP Client Transport for Breadcrumb Tracking (Go) Source: https://context7.com/pr0ger/go-logger/llms.txt The NewBreadcrumbTransport is an HTTP RoundTripper that records outgoing HTTP requests as Sentry breadcrumbs and adds distributed tracing headers. It should be used with http.Client to track external API calls. Dependencies include the 'github.com/getsentry/sentry-go' and 'go.pr0ger.dev/logger' packages. It takes a Sentry level and an underlying transport as input, and automatically captures request details like URL, method, status code, and errors. ```go package main import ( "context" "net/http" "github.com/getsentry/sentry-go" "go.pr0ger.dev/logger" ) func main() { _ = sentry.Init(sentry.ClientOptions{ Dsn: "https://your-dsn@sentry.io/project", TracesSampleRate: 1.0, }) // Create HTTP client with breadcrumb transport client := &http.Client{ Transport: logger.NewBreadcrumbTransport( sentry.LevelInfo, // Log level for breadcrumbs http.DefaultTransport, // Underlying transport (nil uses default) ), } // Create context with Sentry hub ctx := logger.WithHub(context.Background(), sentry.CurrentHub()) // Make request - automatically recorded as breadcrumb req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.example.com/users", nil) resp, err := client.Do(req) // Breadcrumb captures: // - URL // - HTTP method // - Status code // - Response status text // - Any error message if err != nil { sentry.CaptureException(err) // Error event includes HTTP breadcrumb return } defer resp.Body.Close() } // In HTTP handlers, use request context for proper breadcrumb association func apiHandler(w http.ResponseWriter, r *http.Request) { client := &http.Client{ Transport: logger.NewBreadcrumbTransport(sentry.LevelInfo, nil), } // Use request context - breadcrumbs attached to this request's Sentry scope req, _ := http.NewRequestWithContext(r.Context(), http.MethodPost, "https://api.example.com/notify", nil) resp, err := client.Do(req) log := logger.Ctx(r.Context()) if err != nil { log.Error("external API failed", zap.Error(err)) // Sentry event includes breadcrumb trail with all HTTP calls return } defer resp.Body.Close() log.Info("notification sent", zap.Int("status", resp.StatusCode)) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.