Skip to content

Commit

Permalink
feat: structured logging
Browse files Browse the repository at this point in the history
use slog for logging
request logger middleware will log path if it's enabled by a parameter
  • Loading branch information
Ajnasz committed Jun 13, 2024
1 parent 24e1ef6 commit b62264b
Show file tree
Hide file tree
Showing 9 changed files with 27 additions and 23 deletions.
11 changes: 8 additions & 3 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package api
import (
"database/sql"
"fmt"
"log"
"log/slog"
"net/http"
"net/url"
"path"
Expand Down Expand Up @@ -58,7 +58,7 @@ func NewSecretHandler(config HandlerConfig) SecretHandler {
func (s SecretHandler) Post(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" && r.URL.Path != "" {
http.Error(w, "Not found", http.StatusNotFound)
log.Println("Not found", r.URL.Path)
slog.Info("Not found", "url", r.URL.Path)
return
}

Expand Down Expand Up @@ -168,6 +168,7 @@ func (s SecretHandler) RegisterHandlers(mux *http.ServeMux, apiRoot string) {
http.StripPrefix(
apiRoot,
middlewares.SetupLogging(
false,
middlewares.SetupHeaders(http.HandlerFunc(s.Get)),
),
),
Expand All @@ -177,6 +178,7 @@ func (s SecretHandler) RegisterHandlers(mux *http.ServeMux, apiRoot string) {
http.StripPrefix(
path.Join("/", apiRoot),
middlewares.SetupLogging(
true,
middlewares.SetupHeaders(http.HandlerFunc(s.Post)),
),
),
Expand All @@ -187,6 +189,7 @@ func (s SecretHandler) RegisterHandlers(mux *http.ServeMux, apiRoot string) {
http.StripPrefix(
apiRoot,
middlewares.SetupLogging(
false,
middlewares.SetupHeaders(http.HandlerFunc(s.Delete)),
),
),
Expand All @@ -197,6 +200,7 @@ func (s SecretHandler) RegisterHandlers(mux *http.ServeMux, apiRoot string) {
http.StripPrefix(
apiRoot,
middlewares.SetupLogging(
false,
middlewares.SetupHeaders(http.HandlerFunc(s.Options)),
),
),
Expand All @@ -208,11 +212,12 @@ func (s SecretHandler) RegisterHandlers(mux *http.ServeMux, apiRoot string) {
http.StripPrefix(
apiRoot,
middlewares.SetupLogging(
false,
middlewares.SetupHeaders(http.HandlerFunc(s.GenerateEncryptionKey)),
),
),
)

mux.Handle("/", middlewares.SetupLogging(middlewares.SetupHeaders(http.HandlerFunc(s.NotFound))))
mux.Handle("/", middlewares.SetupLogging(true, middlewares.SetupHeaders(http.HandlerFunc(s.NotFound))))

}
11 changes: 5 additions & 6 deletions api/middlewares/middlewares.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
package middlewares

import (
"fmt"
"log"
"log/slog"
"net/http"
)

func SetupLogging(h http.Handler) http.Handler {
func SetupLogging(withPath bool, h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet || r.Method == http.MethodDelete || r.Method == http.MethodOptions {
log.Println(fmt.Sprintf("%s: %s", r.Method, "/***"))
if withPath {
slog.Info("handle", "method", r.Method, "path", r.URL.Path)
} else {
log.Println(fmt.Sprintf("%s: %s", r.Method, r.URL.Path))
slog.Info("handle", "method", r.Method)
}
h.ServeHTTP(w, r)
})
Expand Down
4 changes: 2 additions & 2 deletions cmd/prepare/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package main
import (
"context"
"flag"
"fmt"
"log/slog"

_ "github.com/lib/pq"

Expand Down Expand Up @@ -32,6 +32,6 @@ func prepareDatabase(ctx context.Context) error {

func main() {
if err := prepareDatabase(context.Background()); err != nil {
fmt.Println(err)
slog.Error("Failed to prepare database", "error", err)
}
}
5 changes: 3 additions & 2 deletions cmd/sekret.link/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"database/sql"
"flag"
"fmt"
"log/slog"
"net/http"
"net/url"
"os"
Expand Down Expand Up @@ -58,7 +59,7 @@ func scheduleDeleteExpired(ctx context.Context, db *sql.DB) error {
for {
select {
case <-ctx.Done():
fmt.Println("Stop deleting expired entries")
slog.Info("Stop deleting expired entries")
return nil
case <-ticker.C:
if err := manager.DeleteExpired(ctx); err != nil {
Expand All @@ -84,7 +85,7 @@ func listen(handlerConfig api.HandlerConfig) *http.Server {
}

go func() {
fmt.Println("Handle Path: ", apiRoot)
slog.Info("Start listening", "address", httpServer.Addr, "path", apiRoot)
if err := httpServer.ListenAndServe(); err != nil {
if err.Error() != "http: Server closed" {
fmt.Fprintf(os.Stderr, "error: %s", err)
Expand Down
4 changes: 2 additions & 2 deletions internal/api/createentry.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package api
import (
"context"
"errors"
"log"
"log/slog"
"net/http"
"time"

Expand Down Expand Up @@ -78,7 +78,7 @@ func (c CreateHandler) handle(w http.ResponseWriter, r *http.Request) error {
// Handle handles http request to create secret
func (c CreateHandler) Handle(w http.ResponseWriter, r *http.Request) {
if err := c.handle(w, r); err != nil {
log.Println("create error", err)
slog.Error("create error", "error", err)
c.view.RenderError(w, r, err)
}
}
1 change: 0 additions & 1 deletion internal/api/createentry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"bytes"
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"testing"
Expand Down
6 changes: 3 additions & 3 deletions internal/views/entrycreate.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"encoding/json"
"errors"
"fmt"
"log"
"log/slog"
"net/http"
"net/url"
"os"
Expand Down Expand Up @@ -54,12 +54,12 @@ func (e EntryCreateView) Render(w http.ResponseWriter, r *http.Request, entry En
w.Header().Set("Content-Type", "application/json")

if err := json.NewEncoder(w).Encode(entry); err != nil {
log.Println("JSON encode failed", err)
slog.Error("JSON encode failed", "error", err)
}
} else {
newURL, err := uuid.GetUUIDUrlWithSecret(e.webExternalURL, entry.UUID, entry.Key)
if err != nil {
log.Println("Get UUID URL with secret failed", err)
slog.Error("Get UUID URL with secret failed", "error", err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
Expand Down
4 changes: 2 additions & 2 deletions internal/views/entrykeycreate.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"encoding/json"
"errors"
"fmt"
"log"
"log/slog"
"net/http"
"net/url"
"os"
Expand Down Expand Up @@ -44,7 +44,7 @@ func (g GenerateEntryKeyView) Render(w http.ResponseWriter, r *http.Request, res
w.Header().Set("Content-Type", "application/json")

if err := json.NewEncoder(w).Encode(response); err != nil {
log.Println("JSON encode failed", err)
slog.Error("JSON encode failed", "error", err)
}
} else {
newURL, err := uuid.GetUUIDUrlWithSecret(g.webExternalURL, response.UUID, response.Key.String())
Expand Down
4 changes: 2 additions & 2 deletions internal/views/entryread.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"encoding/hex"
"encoding/json"
"errors"
"log"
"log/slog"
"net/http"
"time"

Expand Down Expand Up @@ -47,7 +47,7 @@ func (e EntryReadView) Render(w http.ResponseWriter, r *http.Request, response E
if r.Header.Get("Accept") == "application/json" {
w.Header().Add("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(response); err != nil {
log.Println("JSON encode failed", err)
slog.Error("JSON encode failed", "error", err)
}
} else {
if response.ContentType != "" {
Expand Down

0 comments on commit b62264b

Please sign in to comment.