47 lines
1.2 KiB
Go
Raw Normal View History

2017-06-05 18:21:06 +00:00
package main
2017-06-10 18:45:30 +00:00
import (
2017-06-15 13:50:39 +00:00
"net/http"
"os"
2017-06-10 18:45:30 +00:00
"strconv"
"strings"
"time"
2017-06-05 18:21:06 +00:00
2017-06-10 18:45:30 +00:00
"github.com/aerogo/aero"
"github.com/aerogo/log"
)
2017-06-05 18:21:06 +00:00
2017-06-10 18:45:30 +00:00
func init() {
2017-06-15 19:59:14 +00:00
err := log.NewLog()
2017-06-10 18:45:30 +00:00
err.AddOutput(log.File("logs/error.log"))
2017-06-15 13:50:39 +00:00
err.AddOutput(os.Stderr)
2017-06-05 18:21:06 +00:00
2017-06-15 19:59:14 +00:00
request := log.NewLog()
2017-06-15 13:50:39 +00:00
request.AddOutput(log.File("logs/request.log"))
2017-06-05 18:21:06 +00:00
2017-06-10 18:45:30 +00:00
app.Use(func(ctx *aero.Context, next func()) {
start := time.Now()
next()
responseTime := time.Since(start)
responseTimeString := strconv.Itoa(int(responseTime.Nanoseconds()/1000000)) + " ms"
responseTimeString = strings.Repeat(" ", 8-len(responseTimeString)) + responseTimeString
// Log every request
2017-06-15 13:50:39 +00:00
request.Info(ctx.RealIP(), ctx.StatusCode, responseTimeString, ctx.URI())
// Log all requests that failed
switch ctx.StatusCode {
case http.StatusOK, http.StatusFound, http.StatusMovedPermanently, http.StatusPermanentRedirect, http.StatusTemporaryRedirect:
// Ok.
default:
err.Error(http.StatusText(ctx.StatusCode), ctx.RealIP(), ctx.StatusCode, responseTimeString, ctx.URI())
}
2017-06-10 18:45:30 +00:00
// Notify us about long requests
2017-06-15 13:50:39 +00:00
if responseTime >= 200*time.Millisecond {
err.Error("Long response time", ctx.RealIP(), ctx.StatusCode, responseTimeString, ctx.URI())
2017-06-10 18:45:30 +00:00
}
})
}