Skip to content

Commit c9bfdd5

Browse files
committed
Log Request in a separated method
Log more informations in console: - static and dynamic requests - duration - request ip - Handled RemoteAddr more gracefully with non standard HttpRequest - Format
1 parent bac245b commit c9bfdd5

File tree

1 file changed

+34
-8
lines changed

1 file changed

+34
-8
lines changed

server.go

+34-8
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import (
1515
"regexp"
1616
"runtime"
1717
"strconv"
18+
"strings"
1819
"time"
1920
)
2021

@@ -262,6 +263,34 @@ func (s *Server) tryServingFile(name string, req *http.Request, w http.ResponseW
262263
return false
263264
}
264265

266+
func (s *Server) logRequest(ctx Context, sTime time.Time) {
267+
//log the request
268+
var logEntry bytes.Buffer
269+
req := ctx.Request
270+
requestPath := req.URL.Path
271+
272+
duration := time.Now().Sub(sTime)
273+
var client string
274+
275+
// We suppose RemoteAddr is of the form Ip:Port as specified in the Request
276+
// documentation at http://golang.org/pkg/net/http/#Request
277+
pos := strings.LastIndex(req.RemoteAddr, ":")
278+
if pos > 0 {
279+
client = req.RemoteAddr[0:pos]
280+
} else {
281+
client = req.RemoteAddr
282+
}
283+
284+
fmt.Fprintf(&logEntry, "%s - \033[32;1m %s %s\033[0m - %v", client, req.Method, requestPath, duration)
285+
286+
if len(ctx.Params) > 0 {
287+
fmt.Fprintf(&logEntry, " - \033[37;1mParams: %v\033[0m\n", ctx.Params)
288+
}
289+
290+
ctx.Server.Logger.Print(logEntry.String())
291+
292+
}
293+
265294
// the main route handler in web.go
266295
// Tries to handle the given request.
267296
// Finds the route matching the request, and execute the callback associated
@@ -272,23 +301,20 @@ func (s *Server) routeHandler(req *http.Request, w http.ResponseWriter) (unused
272301
requestPath := req.URL.Path
273302
ctx := Context{req, map[string]string{}, s, w}
274303

275-
//log the request
276-
var logEntry bytes.Buffer
277-
fmt.Fprintf(&logEntry, "\033[32;1m%s %s\033[0m", req.Method, requestPath)
304+
//set some default headers
305+
ctx.SetHeader("Server", "web.go", true)
306+
tm := time.Now().UTC()
278307

279308
//ignore errors from ParseForm because it's usually harmless.
280309
req.ParseForm()
281310
if len(req.Form) > 0 {
282311
for k, v := range req.Form {
283312
ctx.Params[k] = v[0]
284313
}
285-
fmt.Fprintf(&logEntry, "\n\033[37;1mParams: %v\033[0m\n", ctx.Params)
286314
}
287-
ctx.Server.Logger.Print(logEntry.String())
288315

289-
//set some default headers
290-
ctx.SetHeader("Server", "web.go", true)
291-
tm := time.Now().UTC()
316+
defer s.logRequest(ctx, tm)
317+
292318
ctx.SetHeader("Date", webTime(tm), true)
293319

294320
if req.Method == "GET" || req.Method == "HEAD" {

0 commit comments

Comments
 (0)