### Install slog-http Go Module Source: https://github.com/samber/slog-http/blob/main/README.md Installs the slog-http Go module using the `go get` command. This command fetches the module from its repository and adds it to your Go workspace, making it available for import and use in your Go projects. ```Shell go get github.com/samber/slog-http ``` -------------------------------- ### Implement Basic slog-http Middleware Source: https://github.com/samber/slog-http/blob/main/README.md Demonstrates a minimal setup for `slog-http` middleware with a standard Go HTTP server. This example shows how to initialize a `slog` logger, define basic HTTP routes, and apply `slog-http`'s `Recovery` and `New` logging middleware to handle requests and log their details, including an example of the output format. ```go import ( "net/http" os" "time" sloghttp "github.com/samber/slog-http" "log/slog" ) // Create a slog logger, which: // - Logs to stdout. logger := slog.New(slog.NewTextHandler(os.Stdout, nil)) // mux router mux := http.NewServeMux() // Routes mux.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello, World!")) })) mux.Handle("/error", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "I'm angry" http.StatusInternalServerError) })) // Middleware handler := sloghttp.Recovery(mux) handler = sloghttp.New(logger)(handler) // Start server http.ListenAndServe(":4242", handler) // output: // time=2023-10-15T20:32:58.926+02:00 level=INFO msg="Success" env=production request.time=2023-10-15T20:32:58.626+02:00 request.method=GET request.path=/ request.route="" request.ip=127.0.0.1:63932 request.length=0 response.time=2023-10-15T20:32:58.926+02:00 response.latency=100ms response.status=200 response.length=7 id=229c7fc8-64f5-4467-bc4a-940700503b0d ``` -------------------------------- ### Development and testing commands for Go slog-http Source: https://github.com/samber/slog-http/blob/main/README.md Provides common development commands for the `slog-http` project, including installing development dependencies and running unit tests. These commands are typically executed via `make`. ```bash # Install some dev dependencies make tools # Run tests make test # or make watch-test ``` -------------------------------- ### Apply Custom Logging Filters to HTTP Requests Source: https://github.com/samber/slog-http/blob/main/README.md Illustrates the use of `slog-http` filters to selectively log or ignore HTTP requests based on custom logic or predefined criteria. This example shows how to use a custom `Accept` filter and the `IgnoreStatus` filter to exclude specific status codes from logging. ```go logger := slog.New(slog.NewTextHandler(os.Stdout, nil)) mux := http.NewServeMux() // Middleware handler := sloghttp.Recovery(mux) handler = sloghttp.NewWithFilters( logger, sloghttp.Accept(func (w sloghttp.WrapResponseWriter, r *http.Request) bool { return xxx }), sloghttp.IgnoreStatus(401, 404), )(handler) // Start server http.ListenAndServe(":4242", handler) ``` -------------------------------- ### Apply Go slog-http middleware with a logger subgroup Source: https://github.com/samber/slog-http/blob/main/README.md Illustrates how to configure `slog-http` middleware to use a `slog` logger with a predefined subgroup (e.g., 'http'). This groups all HTTP-related log attributes under a common key, improving log readability and organization. It sets up a basic HTTP server with routes and applies the logging and recovery middleware. ```go logger := slog.New(slog.NewTextHandler(os.Stdout, nil)) // mux router mux := http.NewServeMux() // Routes mux.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello, World!")) })) mux.Handle("/error", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "I'm angry" http.StatusInternalServerError) })) // Middleware handler := sloghttp.Recovery(mux) handler = sloghttp.New(logger.WithGroup("http"))(handler) // Start server http.ListenAndServe(":4242", handler) ``` -------------------------------- ### Enable Verbose Request and Response Logging Source: https://github.com/samber/slog-http/blob/main/README.md Demonstrates how to configure `slog-http` to log detailed request and response information, including full bodies and headers. This is achieved by enabling `WithRequestBody`, `WithResponseBody`, `WithRequestHeader`, and `WithResponseHeader` options in the `Config` struct, useful for debugging and auditing. ```go logger := slog.New(slog.NewTextHandler(os.Stdout, nil)) config := sloghttp.Config{ WithRequestBody: true, WithResponseBody: true, WithRequestHeader: true, WithResponseHeader: true, } mux := http.NewServeMux() // Middleware handler := sloghttp.Recovery(mux) handler = sloghttp.NewWithConfig(logger, config)(handler) // Start server http.ListenAndServe(":4242", handler) ``` -------------------------------- ### Configure Go slog-http middleware with custom time formatting Source: https://github.com/samber/slog-http/blob/main/README.md Demonstrates how to initialize `slog-http` middleware with a custom `slog` logger that uses `slog-formatter` to apply specific time formats (RFC3339 UTC) to log entries. It sets up a basic HTTP server with routes and applies the logging and recovery middleware, showing the effect on the log output. ```go import ( "net/http" "log/slog" sloghttp "github.com/samber/slog-http" slogformatter "github.com/samber/slog-formatter" ) // Create a slog logger, which: // - Logs to stdout. // - RFC3339 with UTC time format. logger := slog.New( slogformatter.NewFormatterHandler( slogformatter.TimezoneConverter(time.UTC), slogformatter.TimeFormatter(time.DateTime, nil), )( slog.NewTextHandler(os.Stdout, nil), ), ) // mux router mux := http.NewServeMux() // Routes mux.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello, World!")) })) mux.Handle("/error", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "I'm angry" http.StatusInternalServerError) })) // Middleware handler := sloghttp.Recovery(mux) handler = sloghttp.New(logger)(handler) // Start server http.ListenAndServe(":4242", handler) ``` -------------------------------- ### Configure Go slog-http for JSON log output Source: https://github.com/samber/slog-http/blob/main/README.md Demonstrates how to configure the `slog-http` middleware to produce log output in JSON format. This is achieved by initializing the underlying `slog` logger with `slog.NewJSONHandler`, which is suitable for structured logging and integration with log aggregation systems. ```go logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) // mux router mux := http.NewServeMux() // Routes mux.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello, World!")) })) // Middleware handler := sloghttp.Recovery(mux) handler = sloghttp.New(logger)(handler) // Start server http.ListenAndServe(":4242", handler) ``` -------------------------------- ### Configure Global slog-http Parameters Source: https://github.com/samber/slog-http/blob/main/README.md Sets global parameters for the `slog-http` library, including keys for trace and span IDs, maximum request/response body sizes, and lists of hidden headers for sensitive information. These parameters affect the behavior of the middleware globally across all instances. ```go sloghttp.TraceIDKey = "trace_id" sloghttp.SpanIDKey = "span_id" sloghttp.RequestBodyMaxSize = 64 * 1024 // 64KB sloghttp.ResponseBodyMaxSize = 64 * 1024 // 64KB sloghttp.HiddenRequestHeaders = map[string]struct{}{ ... } sloghttp.HiddenResponseHeaders = map[string]struct{}{ ... } sloghttp.RequestIDHeaderKey = "X-Request-Id" ``` -------------------------------- ### Integrate Go slog-http middleware on a specific HTTP route Source: https://github.com/samber/slog-http/blob/main/README.md Shows how to apply the `slog-http` middleware to an individual HTTP route rather than globally. This allows for fine-grained control over logging, enabling specific routes to have their own logger configurations or to be logged independently. ```go logger := slog.New(slog.NewTextHandler(os.Stdout, nil)) // mux router mux := http.NewServeMux() // Routes mux.Handler("/", sloghttp.New(logger)( http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { return c.String(http.StatusOK, "Hello, World!") }, ), sloghttp.New(logger), )) // Start server http.ListenAndServe(":4242", handler) ``` -------------------------------- ### Define slog-http Configuration Structure Source: https://github.com/samber/slog-http/blob/main/README.md Defines the `Config` struct for `slog-http` middleware, allowing customization of log levels for different HTTP response categories (default, client error, server error), and inclusion of various request/response attributes like user agent, request ID, body, headers, and OpenTelemetry trace/span IDs. ```go type Config struct { DefaultLevel slog.Level ClientErrorLevel slog.Level ServerErrorLevel slog.Level WithUserAgent bool WithRequestID bool WithRequestBody bool WithRequestHeader bool WithResponseBody bool WithResponseHeader bool WithSpanID bool WithTraceID bool Filters []Filter } ``` -------------------------------- ### Integrate slog-http with OpenTelemetry Source: https://github.com/samber/slog-http/blob/main/README.md Illustrates how to configure `slog-http` to automatically include OpenTelemetry trace and span IDs in logs. This is achieved by setting `WithSpanID` and `WithTraceID` to `true` in the `Config` struct, enabling correlation of logs with distributed traces for enhanced observability. ```go logger := slog.New(slog.NewTextHandler(os.Stdout, nil)) config := sloghttp.Config{ WithSpanID: true, WithTraceID: true, } mux := http.NewServeMux() // Middleware handler := sloghttp.Recovery(mux) handler = sloghttp.NewWithConfig(logger, config)(handler) // Start server http.ListenAndServe(":4242", handler) ``` -------------------------------- ### Add custom attributes to Go slog-http log entries Source: https://github.com/samber/slog-http/blob/main/README.md Explains how to dynamically add custom attributes to log entries within an HTTP request handler using `sloghttp.AddCustomAttributes`. This allows for context-specific data to be included in logs, such as user IDs, transaction IDs, or other request-specific details. It also demonstrates adding a global attribute to the logger. ```go logger := slog.New(slog.NewTextHandler(os.Stdout, nil)) // Add an attribute to all log entries made through this logger. logger = logger.With("env", "production") // mux router mux := http.NewServeMux() // Routes mux.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { sloghttp.AddCustomAttributes(r, slog.String("foo", "bar")) w.Write([]byte("Hello, World!")) })) // Middleware handler := sloghttp.Recovery(mux) handler = sloghttp.New(logger)(handler) // Start server http.ListenAndServe(":4242", handler) ``` -------------------------------- ### Configure Custom Log Levels for HTTP Statuses Source: https://github.com/samber/slog-http/blob/main/README.md Shows how to customize log levels for different HTTP response categories (default, client errors, server errors) using the `DefaultLevel`, `ClientErrorLevel`, and `ServerErrorLevel` fields in the `slog-http` configuration. This allows fine-grained control over log verbosity based on response outcomes. ```go logger := slog.New(slog.NewTextHandler(os.Stdout, nil)) config := sloghttp.Config{ DefaultLevel: slog.LevelInfo, ClientErrorLevel: slog.LevelWarn, ServerErrorLevel: slog.LevelError, } mux := http.NewServeMux() // Middleware handler := sloghttp.Recovery(mux) handler = sloghttp.NewWithConfig(logger, config)(handler) // Start server http.ListenAndServe(":4242", handler) ``` -------------------------------- ### slog-http Available Filtering Options Source: https://github.com/samber/slog-http/blob/main/README.md Lists the various built-in filtering options provided by `slog-http` for controlling which HTTP requests are logged. These filters allow conditional logging based on methods, status codes, paths, and hosts, offering granular control over log output. ```APIDOC Available filters: - Accept / Ignore - AcceptMethod / IgnoreMethod - AcceptStatus / IgnoreStatus - AcceptStatusGreaterThan / IgnoreStatusGreaterThan - AcceptStatusLessThan / IgnoreStatusLessThan - AcceptStatusGreaterThanOrEqual / IgnoreStatusGreaterThanOrEqual - AcceptStatusLessThanOrEqual / IgnoreStatusLessThanOrEqual - AcceptPath / IgnorePath - AcceptPathContains / IgnorePathContains - AcceptPathPrefix / IgnorePathPrefix - AcceptPathSuffix / IgnorePathSuffix - AcceptPathMatch / IgnorePathMatch - AcceptHost / IgnoreHost - AcceptHostContains / IgnoreHostContains - AcceptHostPrefix / IgnoreHostPrefix - AcceptHostSuffix / IgnoreHostSuffix - AcceptHostMatch / IgnoreHostMatch ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.