-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
474691b
commit 3abb9fb
Showing
1 changed file
with
61 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
package main | ||
|
||
import ( | ||
"fmt" | ||
"log" | ||
"net/http" | ||
"os" | ||
"time" | ||
) | ||
|
||
func requestLogger(targetMux http.Handler) http.Handler { | ||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
start := time.Now() | ||
|
||
targetMux.ServeHTTP(w, r) | ||
|
||
// log request by who(IP address) | ||
requesterIP := r.RemoteAddr | ||
fmt.Println(start, "Received Request", r.Method, r.RequestURI, requesterIP) | ||
|
||
log.Printf( | ||
"%s\t\t%s\t\t%s\t\t%v", | ||
r.Method, | ||
r.RequestURI, | ||
requesterIP, | ||
time.Since(start), | ||
) | ||
log.Printf( | ||
"DATA: %s", | ||
r.Body, | ||
) | ||
}) | ||
} | ||
|
||
func logRoute(w http.ResponseWriter, r *http.Request) { | ||
html := "" | ||
w.Write([]byte(html)) | ||
} | ||
|
||
func main() { | ||
fileName := "webrequests.log" | ||
|
||
fmt.Println("Making log file ready", "Logfile: ", fileName) | ||
// https://www.socketloop.com/tutorials/golang-how-to-save-log-messages-to-file | ||
logFile, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) | ||
|
||
if err != nil { | ||
panic(err) | ||
} | ||
|
||
defer logFile.Close() | ||
|
||
// direct all log messages to webrequests.log | ||
log.SetOutput(logFile) | ||
|
||
mux := http.NewServeMux() | ||
mux.HandleFunc("/", logRoute) | ||
|
||
fmt.Println("Starting Go Logging Server on port 7777") | ||
http.ListenAndServe(":7777", requestLogger(mux)) | ||
} |