Skip to content

Commit

Permalink
feat: add request logs (#23)
Browse files Browse the repository at this point in the history
* fix: update dev commands

* feat: add middleware for logging
  • Loading branch information
bcho authored Jun 6, 2022
1 parent 35a459e commit 51e548d
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 3 deletions.
5 changes: 3 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,11 @@ vet: ## Run go vet against code.
go vet ./...

run-server: fmt vet ## Run server.
go run *.go serve --db-dsn ./test.sqlite3?_journal_mode=WAL --log-devel --log-level 12
echo "test" > local_dev.token
go run . serve --db-dsn ./test.sqlite3?_journal_mode=WAL --log-devel --log-level 12 --auth-token-file local_dev.token

run-migrate: fmt vet ## Run migration.
go run *.go migrate --db-dsn ./test.sqlite3?_journal_mode=WAL --log-devel --log-level 12 ./data
go run . migrate --db-dsn ./test.sqlite3?_journal_mode=WAL --log-devel --log-level 12 ./data

##@ Build

Expand Down
8 changes: 7 additions & 1 deletion server.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"time"

"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
"github.com/go-logr/logr"
"github.com/jmoiron/sqlx"
Expand Down Expand Up @@ -86,7 +87,12 @@ func NewServer(opts *ServerOptions) (*dbServer, error) {
serverMux := chi.NewRouter()

// TODO: allow specifying cors config from cli / table
serverMux.Use(cors.AllowAll().Handler)
serverMux.Use(
middleware.RequestID,
middleware.RealIP,
serverLogger(rv.logger),
cors.AllowAll().Handler,
)

{
serverMux.
Expand Down
24 changes: 24 additions & 0 deletions server_utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package main

import (
"fmt"
"net/http"

"github.com/go-chi/chi/v5/middleware"
"github.com/go-logr/logr"
)

type httpLogger struct {
logr.Logger
}

func (l httpLogger) Print(v ...interface{}) {
l.Info(fmt.Sprint(v...))
}

func serverLogger(logr logr.Logger) func(http.Handler) http.Handler {
formatter := &middleware.DefaultLogFormatter{
Logger: httpLogger{logr},
}
return middleware.RequestLogger(formatter)
}

0 comments on commit 51e548d

Please sign in to comment.