64 lines
1.7 KiB
Go
Raw Normal View History

2017-06-16 23:12:28 +00:00
package middleware
2017-06-05 18:21:06 +00:00
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-22 20:26:52 +00:00
"github.com/animenotifier/notify.moe/utils"
2017-06-10 18:45:30 +00:00
)
2017-06-05 18:21:06 +00:00
2017-06-16 23:34:54 +00:00
// Log middleware logs every request into logs/request.log and errors into logs/error.log.
2017-06-16 23:25:02 +00:00
func Log() aero.Middleware {
2017-06-21 18:33:57 +00:00
request := log.New()
2017-06-16 23:34:54 +00:00
request.AddOutput(log.File("logs/request.log"))
2017-06-21 18:33:57 +00:00
err := log.New()
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-16 23:12:28 +00:00
return func(ctx *aero.Context, next func()) {
2017-06-10 18:45:30 +00:00
start := time.Now()
next()
responseTime := time.Since(start)
responseTimeString := strconv.Itoa(int(responseTime.Nanoseconds()/1000000)) + " ms"
responseTimeString = strings.Repeat(" ", 8-len(responseTimeString)) + responseTimeString
2017-06-22 20:26:52 +00:00
user := utils.GetUser(ctx)
2017-06-23 13:38:46 +00:00
ip := ctx.RealIP()
hostName := ""
hostNames := GetHostsForIP(ip)
if len(hostNames) != 0 {
hostName = hostNames[0]
}
2017-06-22 20:26:52 +00:00
2017-06-10 18:45:30 +00:00
// Log every request
2017-06-22 20:26:52 +00:00
if user != nil {
2017-06-23 13:38:46 +00:00
request.Info(user.Nick, ip, hostName, responseTimeString, ctx.StatusCode, ctx.URI())
2017-06-22 20:26:52 +00:00
} else {
2017-06-23 13:38:46 +00:00
request.Info("[guest]", ip, hostName, responseTimeString, ctx.StatusCode, ctx.URI())
2017-06-22 20:26:52 +00:00
}
2017-06-15 13:50:39 +00:00
// Log all requests that failed
switch ctx.StatusCode {
case http.StatusOK, http.StatusFound, http.StatusMovedPermanently, http.StatusPermanentRedirect, http.StatusTemporaryRedirect:
// Ok.
default:
2017-06-23 13:38:46 +00:00
err.Error(http.StatusText(ctx.StatusCode), ip, hostName, responseTimeString, ctx.StatusCode, ctx.URI())
2017-06-15 13:50:39 +00:00
}
2017-06-10 18:45:30 +00:00
2017-06-18 15:16:40 +00:00
// Notify us about long requests.
// However ignore requests under /auth/ because those depend on 3rd party servers.
if responseTime >= 200*time.Millisecond && !strings.HasPrefix(ctx.URI(), "/auth/") {
2017-06-23 13:38:46 +00:00
err.Error("Long response time", ip, hostName, responseTimeString, ctx.StatusCode, ctx.URI())
2017-06-10 18:45:30 +00:00
}
2017-06-16 23:12:28 +00:00
}
2017-06-10 18:45:30 +00:00
}