diff --git a/README.md b/README.md index 022ca15..c7d688d 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ Configuration is done using environment variables. - `WOLBODGE_DEVICE_TYPE`: Device type to pick, defaults to `test`. - `test`: A dummy device, used for testing. - `command`: Runs a subprocess to aquire the info. See the example below for more info. +- `WOLBODGE_LOG_REQUESTS`: Should HTTP requests be logged, defaults to `true`. ### Example: Raspberry pi using the command device - `WOLBODGE_DEVICE_TYPE=command` diff --git a/main.go b/main.go index 564184c..0d88413 100644 --- a/main.go +++ b/main.go @@ -20,7 +20,9 @@ func Run() error { logger := log.New(os.Stdout, "", log.LstdFlags) var address string + var logRequests bool Env("WOLBODGE_ADDRESS", &address, ":3000", logger) + Env("WOLBODGE_LOG_REQUESTS", &logRequests, "true", logger) tmpl := template.New("") _, err := tmpl.Parse(embed) @@ -53,8 +55,13 @@ func Run() error { exit := make(chan bool) go devices.KeepDeviceInSync(logger, device, storage.HasSessions, exit) + var handler http.Handler = mux + if logRequests { + handler = routes.Logger(mux, logger) + } + logger.Printf("Listening on %s", address) - err = http.ListenAndServe(address, mux) + err = http.ListenAndServe(address, handler) if err != nil { return fmt.Errorf("failed to listen: %w", err) } diff --git a/routes/logger.go b/routes/logger.go new file mode 100644 index 0000000..aa590ad --- /dev/null +++ b/routes/logger.go @@ -0,0 +1,13 @@ +package routes + +import ( + "log" + "net/http" +) + +func Logger(handler http.Handler, logger *log.Logger) http.HandlerFunc { + return func(res http.ResponseWriter, req *http.Request) { + logger.Printf("%-30s %-10s %s", req.RemoteAddr, req.Method, req.URL.Path) + handler.ServeHTTP(res, req) + } +}