### Initialize and use context-aware logging with slox Source: https://github.com/vilsol/slox/blob/main/README.md Demonstrates how to inject attributes and groups into a context using slox and perform a logging operation. This approach allows loggers to carry state through the call stack without passing explicit logger instances. ```go package main import ( "context" "log/slog" "github.com/Vilsol/slox" ) func main() { ctx := context.Background() ctx = slox.With(ctx, "foo", "bar") ctx = slox.WithGroup(ctx, "my-group") ctx = slox.With(ctx, slog.Int("one", 1), "hello", "world") slox.Info(ctx, "message") } ``` -------------------------------- ### Implement HTTP Middleware for Request-Scoped Logging Source: https://context7.com/vilsol/slox/llms.txt Shows how to integrate slox into HTTP middleware to automatically inject request metadata like request IDs and paths into the logging context. This ensures all subsequent handlers have access to the enriched logger via the request context. ```go func loggingMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() ctx = slox.With(ctx, "request_id", r.Header.Get("X-Request-ID"), "method", r.Method, "path", r.URL.Path, "remote_addr", r.RemoteAddr, ) start := time.Now() slox.Info(ctx, "request started") next.ServeHTTP(w, r.WithContext(ctx)) slox.Info(ctx, "request completed", "duration_ms", time.Since(start).Milliseconds()) }) } ``` -------------------------------- ### Log Warning Messages with Slox.Warn Source: https://context7.com/vilsol/slox/llms.txt Logs a message at the WARN level. This is used for potentially harmful situations that deserve attention but do not prevent operation. It accepts a context, a message, and optional key-value pairs for context. ```go package main import ( "context" "log/slog" "os" "github.com/Vilsol/slox" ) func main() { handler := slog.NewTextHandler(os.Stdout, nil) ctx := slox.Into(context.Background(), slog.New(handler)) ctx = slox.With(ctx, "component", "cache") slox.Warn(ctx, "cache miss rate high", "miss_rate", 0.75, "threshold", 0.5, "action", "consider increasing cache size", ) // Output: time=... level=WARN msg="cache miss rate high" component=cache miss_rate=0.75 threshold=0.5 action="consider increasing cache size" } ``` -------------------------------- ### Log Info Messages with Slox.Info Source: https://context7.com/vilsol/slox/llms.txt Logs a message at the INFO level. This is used for general operational information about application state and events. It takes a context, a message, and optional key-value pairs for context. ```go package main import ( "context" "log/slog" "os" "github.com/Vilsol/slox" ) func main() { handler := slog.NewTextHandler(os.Stdout, nil) ctx := slox.Into(context.Background(), slog.New(handler)) ctx = slox.With(ctx, "app", "payment-service") slox.Info(ctx, "payment processed", "transaction_id", "txn-001", "amount", 99.99, "currency", "USD", ) // Output: time=... level=INFO msg="payment processed" app=payment-service transaction_id=txn-001 amount=99.99 currency=USD } ``` -------------------------------- ### Log ERROR level messages with slox Source: https://context7.com/vilsol/slox/llms.txt Demonstrates how to log an error message with associated contextual attributes using the slox.Error function. It requires a context enriched with a logger and provides structured output including error details and custom fields. ```go package main import ( "context" "errors" "log/slog" "os" "github.com/Vilsol/slox" ) func main() { handler := slog.NewTextHandler(os.Stdout, nil) ctx := slox.Into(context.Background(), slog.New(handler)) ctx = slox.With(ctx, "handler", "CreateUser") err := errors.New("duplicate email address") slox.Error(ctx, "failed to create user", "error", err.Error(), "email", "user@example.com", "retry_possible", true, ) } ``` -------------------------------- ### Retrieve Logger from Context with slox.From (Go) Source: https://context7.com/vilsol/slox/llms.txt The `slox.From` function safely extracts an `slog.Logger` from a `context.Context`. If no logger is found in the context, or if the context is nil, it gracefully returns the `slog.Default()` logger. This allows for flexible access to the current logging context. ```go package main import ( "context" "log/slog" "os" "github.com/Vilsol/slox" ) func main() { // Create and inject a custom logger handler := slog.NewTextHandler(os.Stdout, nil) logger := slog.New(handler) ctx := slox.Into(context.Background(), logger) // Retrieve the logger from context for direct use retrievedLogger := slox.From(ctx) retrievedLogger.Info("direct logger access", "method", "From") // Returns default logger when context has no logger emptyCtx := context.Background() defaultLogger := slox.From(emptyCtx) defaultLogger.Info("using default logger") // Safely handles nil context nilLogger := slox.From(nil) nilLogger.Info("nil context returns default logger") } ``` -------------------------------- ### Efficiently Log Attributes with Slox.LogAttrs Source: https://context7.com/vilsol/slox/llms.txt A more efficient version of Log that accepts only slog.Attr values. Use this when optimal performance is needed and you are working with pre-constructed attributes. It takes a context, log level, message, and a variable number of slog.Attr. ```go package main import ( "context" "log/slog" "os" "time" "github.com/Vilsol/slox" ) func main() { handler := slog.NewTextHandler(os.Stdout, nil) ctx := slox.Into(context.Background(), slog.New(handler)) ctx = slox.With(ctx, "service", "metrics") // Use LogAttrs for performance-critical logging slox.LogAttrs(ctx, slog.LevelInfo, "metrics collected", slog.Int("requests", 1000), slog.Float64("avg_latency_ms", 45.2), slog.Time("collected_at", time.Now()), slog.Duration("window", 5*time.Minute), ) // Output: time=... level=INFO msg="metrics collected" service=metrics requests=1000 avg_latency_ms=45.2 collected_at=... window=5m0s } ``` -------------------------------- ### Add Attributes to Context Logger with slox.With (Go) Source: https://context7.com/vilsol/slox/llms.txt The `slox.With` function returns a new context with the specified attributes (key-value pairs or `slog.Attr`) attached to the logger. Subsequent log calls using this context will automatically include these attributes, simplifying the process of adding contextual information like service names or request IDs. ```go package main import ( "context" "log/slog" "os" "github.com/Vilsol/slox" ) func main() { handler := slog.NewTextHandler(os.Stdout, nil) ctx := slox.Into(context.Background(), slog.New(handler)) // Add attributes using key-value pairs ctx = slox.With(ctx, "service", "user-api", "environment", "production") // Add attributes using slog.Attr for type safety ctx = slox.With(ctx, slog.Int("port", 8080), slog.Bool("tls", true)) // All logs now include these attributes slox.Info(ctx, "server starting") // Output: time=... level=INFO msg="server starting" service=user-api environment=production port=8080 tls=true slox.Error(ctx, "connection failed", "error", "timeout") // Output: time=... level=ERROR msg="connection failed" service=user-api environment=production port=8080 tls=true error=timeout } ``` -------------------------------- ### Inject Logger into Context with slox.Into (Go) Source: https://context7.com/vilsol/slox/llms.txt The `slox.Into` function injects a provided `slog.Logger` into a `context.Context`. This is the primary method for making a custom logger available throughout your application's call chain via context propagation. It requires a `context.Context` and an `slog.Logger` as input and returns the updated context. ```go package main import ( "context" "log/slog" "os" "github.com/Vilsol/slox" ) func main() { // Create a custom JSON logger handler := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ Level: slog.LevelDebug, }) logger := slog.New(handler) // Inject the logger into the context ctx := context.Background() ctx = slox.Into(ctx, logger) // Now all slox calls using this context will use the custom logger slox.Info(ctx, "application started", "version", "1.0.0") // Output: {"time":"...","level":"INFO","msg":"application started","version":"1.0.0"} } ``` -------------------------------- ### Log Debug Messages with Slox.Debug Source: https://context7.com/vilsol/slox/llms.txt Logs a message at the DEBUG level. This is used for detailed diagnostic information during development and troubleshooting. It requires a context, a message, and can include key-value pairs for additional context. ```go package main import ( "context" "log/slog" "os" "github.com/Vilsol/slox" ) func main() { // Enable debug level handler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ Level: slog.LevelDebug, }) ctx := slox.Into(context.Background(), slog.New(handler)) ctx = slox.With(ctx, "function", "processOrder") slox.Debug(ctx, "entering function", "order_id", "ord-789") slox.Debug(ctx, "validation complete", "items_count", 3) slox.Debug(ctx, "exiting function", "success", true) // Output: // time=... level=DEBUG msg="entering function" function=processOrder order_id=ord-789 // time=... level=DEBUG msg="validation complete" function=processOrder items_count=3 // time=... level=DEBUG msg="exiting function" function=processOrder success=true } ``` -------------------------------- ### Check Log Level Enabled Status with Slox Source: https://context7.com/vilsol/slox/llms.txt Checks if a logger in the context emits log records at a specified level. This is useful for optimizing performance by skipping expensive computations when a log level is disabled. It takes a context and a log level as input. ```go package main import ( "context" "log/slog" "os" "github.com/Vilsol/slox" ) func main() { // Create logger with INFO level minimum handler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ Level: slog.LevelInfo, }) ctx := slox.Into(context.Background(), slog.New(handler)) // Check if debug logging is enabled before expensive operations if slox.Enabled(ctx, slog.LevelDebug) { expensiveData := computeExpensiveDebugInfo() slox.Debug(ctx, "debug details", "data", expensiveData) } // INFO and above are enabled if slox.Enabled(ctx, slog.LevelInfo) { slox.Info(ctx, "this will be logged") } } func computeExpensiveDebugInfo() string { return "expensive computation result" } ``` -------------------------------- ### Emit Log Record with Slox Source: https://context7.com/vilsol/slox/llms.txt Emits a log record at a specified level with a given message and attributes. This function provides full control over the log level for dynamic logging scenarios. It accepts a context, log level, message, and a variable number of attributes. ```go package main import ( "context" "log/slog" "os" "github.com/Vilsol/slox" ) func main() { handler := slog.NewTextHandler(os.Stdout, nil) ctx := slox.Into(context.Background(), slog.New(handler)) ctx = slox.With(ctx, "component", "scheduler") // Log at dynamic level based on conditions level := slog.LevelInfo if isHighPriority() { level = slog.LevelWarn } slox.Log(ctx, level, "job executed", "job_id", "job-456", "duration_ms", 150) // Output: time=... level=INFO msg="job executed" component=scheduler job_id=job-456 duration_ms=150 } func isHighPriority() bool { return false } ``` -------------------------------- ### Add Group to Context Logger with slox.WithGroup (Go) Source: https://context7.com/vilsol/slox/llms.txt The `slox.WithGroup` function returns a new context with a named group added to the logger. Attributes added after this call will be nested under this group name, allowing for structured and hierarchical logging. This is useful for organizing logs related to specific operations or data structures. ```go package main import ( "context" "log/slog" "os" "github.com/Vilsol/slox" ) func main() { handler := slog.NewTextHandler(os.Stdout, nil) ctx := slox.Into(context.Background(), slog.New(handler)) // Add top-level attributes ctx = slox.With(ctx, "request_id", "abc-123") // Start a group for request metadata ctx = slox.WithGroup(ctx, "request") ctx = slox.With(ctx, "method", "POST", "path", "/users") // Nested group for user data ctx = slox.WithGroup(ctx, "user") ctx = slox.With(ctx, "id", 42, "role", "admin") slox.Info(ctx, "processing request") // Output: time=... level=INFO msg="processing request" request_id=abc-123 request.method=POST request.path=/users request.user.id=42 request.user.role=admin } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.