Skip to content

Commit

Permalink
Merge pull request #22 from veqryn/add-sloghttp-example
Browse files Browse the repository at this point in the history
Add sloghttp example
  • Loading branch information
veqryn committed Apr 1, 2024
2 parents e44c955 + 8749625 commit 9b054af
Show file tree
Hide file tree
Showing 5 changed files with 119 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
package main

import (
"log/slog"
"net/http"
"os"

slogctx "github.com/veqryn/slog-context"
sloghttp "github.com/veqryn/slog-context/http"
)

func init() {
// Create the *slogctx.Handler middleware
h := slogctx.NewHandler(
slog.NewJSONHandler(os.Stdout, nil), // The next or final handler in the chain
&slogctx.HandlerOptions{
// Prependers will first add the any sloghttp.With attributes,
// then anything else Prepended to the ctx
Prependers: []slogctx.AttrExtractor{
sloghttp.ExtractAttrCollection, // our sloghttp middleware extractor
slogctx.ExtractPrepended, // for all other prepended attributes
},
},
)
slog.SetDefault(slog.New(h))
}

func main() {
slog.Info("Starting server. Please run: curl localhost:8080/hello?id=24680")

// Wrap our final handler inside our middlewares.
// AttrCollector -> Request Logging -> Final Endpoint Handler (helloUser)
handler := sloghttp.AttrCollection(
httpLoggingMiddleware(
http.HandlerFunc(helloUser),
),
)

// Demonstrate the sloghttp middleware with a http server
http.Handle("/hello", handler)
err := http.ListenAndServe(":8080", nil)
if err != nil {
panic(err)
}
}

// This is a stand-in for a middleware that might be capturing and logging out
// things like the response code, request body, response body, url, method, etc.
// It doesn't have access to any of the new context objects's created within the
// next handler. But it should still log with any of the attributes added to our
// sloghttp.Middleware, via sloghttp.With.
func httpLoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Add some logging context/baggage before the handler
r = r.WithContext(sloghttp.With(r.Context(), "path", r.URL.Path))

// Call the next handler
next.ServeHTTP(w, r)

// Log out that we had a response. This would be where we could add
// things such as the response status code, body, etc.

// Should also have both "path" and "id", but not "foo".
// Having "id" included in the log is the whole point of this package!
slogctx.Info(r.Context(), "Response", "method", r.Method)
/*
{
"time": "2024-04-01T00:06:11Z",
"level": "INFO",
"msg": "Response",
"path": "/hello",
"id": "24680",
"method": "GET"
}
*/
})
}

// This is our final api endpoint handler
func helloUser(w http.ResponseWriter, r *http.Request) {
// Stand-in for a User ID.
// Add it to our middleware's context
id := r.URL.Query().Get("id")

// sloghttp.With will add the "id" to to the middleware, because it is a
// synchronized map. It will show up in all log calls up and down the stack,
// until the request sloghttp middleware exits.
ctx := sloghttp.With(r.Context(), "id", id)

// The regular slogctx.With will add "foo" only to the Returned context,
// which will limits its scope to the rest of this function (helloUser) and
// any functions called by helloUser and passed this context.
// The original caller of helloUser and all the middlewares will NOT see
// "foo", because it is only part of the newly returned ctx.
ctx = slogctx.With(ctx, "foo", "bar")

// Log some things.
// Should also have both "path", "id", and "foo"
slogctx.Info(ctx, "saying hello...")
/*
{
"time": "2024-04-01T00:06:11Z",
"level": "INFO",
"msg": "saying hello...",
"path": "/hello",
"id": "24680",
"foo": "bar"
}
*/

// Response
_, _ = w.Write([]byte("Hello User #" + id))
}
2 changes: 1 addition & 1 deletion examples/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ module github.com/veqryn/slog-context/examples
go 1.21

require (
github.com/veqryn/slog-context v0.6.0
github.com/veqryn/slog-context v0.7.0
github.com/veqryn/slog-context/otel v0.6.0
go.opentelemetry.io/otel v1.24.0
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.24.0
Expand Down
4 changes: 2 additions & 2 deletions examples/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/veqryn/slog-context v0.6.0 h1:RV0DL6SIXwTjKu5hUfZlreitiQ47HG6BA7G/aQINK9A=
github.com/veqryn/slog-context v0.6.0/go.mod h1:E+qpdyiQs2YKRxFnX1JjpdFE1z3Ka94Kem2q9ZG6Jjo=
github.com/veqryn/slog-context v0.7.0 h1:Ne7ajlR6Mjs2rQQtpg8k0eO6krR5wzpareh5VpV+V2s=
github.com/veqryn/slog-context v0.7.0/go.mod h1:E+qpdyiQs2YKRxFnX1JjpdFE1z3Ka94Kem2q9ZG6Jjo=
github.com/veqryn/slog-context/otel v0.6.0 h1:LwVMzfKMFhVpIKPASwa4IkzgL8+/bmyrFWJYrBIkpf0=
github.com/veqryn/slog-context/otel v0.6.0/go.mod h1:0l6vQ7IqZHKq1MH7pyhNlbdUutBcuiGYJluAPLQ33Nk=
go.opentelemetry.io/otel v1.24.0 h1:0LAOdjNmQeSTzGBzduGe/rU4tZhMwL5rWgtp9Ku5Jfo=
Expand Down
2 changes: 1 addition & 1 deletion otel/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ module github.com/veqryn/slog-context/otel
go 1.21

require (
github.com/veqryn/slog-context v0.6.0
github.com/veqryn/slog-context v0.7.0
go.opentelemetry.io/otel v1.24.0
go.opentelemetry.io/otel/trace v1.24.0
)
Expand Down
4 changes: 2 additions & 2 deletions otel/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/veqryn/slog-context v0.6.0 h1:RV0DL6SIXwTjKu5hUfZlreitiQ47HG6BA7G/aQINK9A=
github.com/veqryn/slog-context v0.6.0/go.mod h1:E+qpdyiQs2YKRxFnX1JjpdFE1z3Ka94Kem2q9ZG6Jjo=
github.com/veqryn/slog-context v0.7.0 h1:Ne7ajlR6Mjs2rQQtpg8k0eO6krR5wzpareh5VpV+V2s=
github.com/veqryn/slog-context v0.7.0/go.mod h1:E+qpdyiQs2YKRxFnX1JjpdFE1z3Ka94Kem2q9ZG6Jjo=
go.opentelemetry.io/otel v1.24.0 h1:0LAOdjNmQeSTzGBzduGe/rU4tZhMwL5rWgtp9Ku5Jfo=
go.opentelemetry.io/otel v1.24.0/go.mod h1:W7b9Ozg4nkF5tWI5zsXkaKKDjdVjpD4oAt9Qi/MArHo=
go.opentelemetry.io/otel/trace v1.24.0 h1:CsKnnL4dUAr/0llH9FKuc698G04IrpWV0MQA/Y1YELI=
Expand Down

0 comments on commit 9b054af

Please sign in to comment.